From c9e82e3cf8e6bf9f31b488c231366413b31278e2 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Mon, 17 Jan 2022 11:22:59 +0100 Subject: [PATCH 01/16] #51371 fixed failing test in iossimulator --- src/libraries/System.IO.FileSystem/tests/File/Create.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/libraries/System.IO.FileSystem/tests/File/Create.cs b/src/libraries/System.IO.FileSystem/tests/File/Create.cs index fb7f4be892c74..b113a4cfc5ad7 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Create.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Create.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; +using System.Runtime.InteropServices; using Xunit; namespace System.IO.Tests @@ -219,9 +220,13 @@ public void LongFileName() [Fact] [PlatformSpecific(CaseSensitivePlatforms)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void CaseSensitive() { + if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator")) + { + return; + } + DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (File.Create(testFile + "AAAA")) From 0428831fdcbb08686734692d23f36f46f9ca930c Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Mon, 17 Jan 2022 15:33:08 +0100 Subject: [PATCH 02/16] #51371 added skiptestexception --- .../tests/Directory/GetFileSystemEntries_str_str.cs | 10 ++++++++-- .../System.IO.FileSystem/tests/File/Create.cs | 9 +++++---- .../System.IO.FileSystem/tests/File/Exists.cs | 1 - 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs b/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs index c4858914a4381..30479da1286a3 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs @@ -4,6 +4,7 @@ using System.Runtime.InteropServices; using Xunit; using System.Linq; +using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Tests { @@ -697,11 +698,16 @@ public void WindowsSearchPatternWhitespace() Assert.Empty(GetEntries(TestDirectory, "\t")); } - [Fact] + [ConditionalFact] [PlatformSpecific(CaseSensitivePlatforms)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void SearchPatternCaseSensitive() { + if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") + || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) + { + throw new SkipTestException("iOS/tvOS simulators run on a macOS host and are subject to the same case sensitivity behavior."); + } + DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testBase = GetTestFileName(); testDir.CreateSubdirectory(testBase + "aBBb"); diff --git a/src/libraries/System.IO.FileSystem/tests/File/Create.cs b/src/libraries/System.IO.FileSystem/tests/File/Create.cs index b113a4cfc5ad7..d3a5c59b7bc8a 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Create.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Create.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Runtime.InteropServices; using Xunit; - +using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Tests { public class File_Create_str : FileSystemTest @@ -218,13 +218,14 @@ public void LongFileName() Assert.False(File.Exists(path)); } - [Fact] + [ConditionalFact] [PlatformSpecific(CaseSensitivePlatforms)] public void CaseSensitive() { - if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator")) + if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") + || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) { - return; + throw new SkipTestException("iOS/tvOS simulators run on a macOS host and are subject to the same case sensitivity behavior."); } DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); diff --git a/src/libraries/System.IO.FileSystem/tests/File/Exists.cs b/src/libraries/System.IO.FileSystem/tests/File/Exists.cs index ec3e0336a41ce..04ca9b565951f 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Exists.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Exists.cs @@ -233,7 +233,6 @@ public void PathWithReservedDeviceNameAsPath_ReturnsFalse(string component) [Theory, MemberData(nameof(UncPathsWithoutShareName))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void UncPathWithoutShareNameAsPath_ReturnsFalse(string component) { Assert.False(Exists(component)); From cfe45921160bc6758e57e38a7f18d5a27a571ede Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Mon, 17 Jan 2022 15:42:04 +0100 Subject: [PATCH 03/16] #51371 added space after reference --- src/libraries/System.IO.FileSystem/tests/File/Create.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libraries/System.IO.FileSystem/tests/File/Create.cs b/src/libraries/System.IO.FileSystem/tests/File/Create.cs index d3a5c59b7bc8a..d38d6ff47c8bf 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Create.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Create.cs @@ -5,6 +5,7 @@ using System.Runtime.InteropServices; using Xunit; using Microsoft.DotNet.XUnitExtensions; + namespace System.IO.Tests { public class File_Create_str : FileSystemTest From 4b8fe65bd2ee78f47ca17d401afcb99006d4fe63 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Wed, 19 Jan 2022 18:34:54 +0100 Subject: [PATCH 04/16] #51371 fixed remaining failing tests --- .../System/IO/StreamConformanceTests.cs | 27 +------------------ .../System/IO/FileCleanupTestBase.cs | 4 +-- .../TestUtilities/System/PlatformDetection.cs | 2 ++ .../tests/Base/FileGetSetAttributes.cs | 3 +-- .../tests/Directory/CreateDirectory.cs | 1 - .../tests/Directory/Exists.cs | 1 - .../Directory/GetFileSystemEntries_str_str.cs | 10 ++----- .../tests/Directory/GetFiles.cs | 1 - .../System.IO.FileSystem/tests/File/Create.cs | 8 +----- .../System.IO.FileSystem/tests/File/Exists.cs | 3 +-- .../tests/FileSystemTest.cs | 2 +- .../System/IO/Pipes/NamedPipeClientStream.cs | 14 +++++++--- .../IO/Pipes/NamedPipeServerStream.Unix.cs | 5 +++- 13 files changed, 26 insertions(+), 55 deletions(-) diff --git a/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs b/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs index 7dc9519665c58..1885c05fa206a 100644 --- a/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs +++ b/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs @@ -711,7 +711,6 @@ public abstract class StandaloneStreamConformanceTests : StreamConformanceTests } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ArgumentValidation_ThrowsExpectedException() { await foreach (Stream? stream in GetStreamsForValidation()) @@ -725,7 +724,6 @@ public virtual async Task ArgumentValidation_ThrowsExpectedException() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Disposed_ThrowsObjectDisposedException() { await foreach (Stream? stream in GetStreamsForValidation()) @@ -815,7 +813,6 @@ public virtual async Task Read_DataStoredAtDesiredOffset(ReadWriteMode mode) [InlineData(ReadWriteMode.SyncArray)] [InlineData(ReadWriteMode.AsyncArray)] [InlineData(ReadWriteMode.AsyncAPM)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Write_DataReadFromDesiredOffset(ReadWriteMode mode) { using Stream? stream = await CreateReadWriteStream(); @@ -1598,8 +1595,7 @@ protected static bool Bidirectional(StreamPair streams) => streams.Stream1.CanRead && streams.Stream1.CanWrite && streams.Stream2.CanRead && streams.Stream2.CanWrite; - [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] + [Fact] public virtual async Task ArgumentValidation_ThrowsExpectedException() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -1611,7 +1607,6 @@ public virtual async Task ArgumentValidation_ThrowsExpectedException() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Disposed_ThrowsObjectDisposedException() { StreamPair streams = await CreateConnectedStreamsAsync(); @@ -1624,7 +1619,6 @@ public virtual async Task Disposed_ThrowsObjectDisposedException() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadWriteAsync_PrecanceledOperations_ThrowsCancellationException() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -1636,7 +1630,6 @@ public virtual async Task ReadWriteAsync_PrecanceledOperations_ThrowsCancellatio } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadAsync_CancelPendingTask_ThrowsCancellationException() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -1646,7 +1639,6 @@ public virtual async Task ReadAsync_CancelPendingTask_ThrowsCancellationExceptio } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadAsync_CancelPendingValueTask_ThrowsCancellationException() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -1656,7 +1648,6 @@ public virtual async Task ReadAsync_CancelPendingValueTask_ThrowsCancellationExc } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadWriteByte_Success() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -1729,7 +1720,6 @@ public virtual async Task ReadWrite_Success_Large(ReadWriteMode mode, int writeS [Theory] [MemberData(nameof(ReadWrite_Success_MemberData))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadWrite_Success(ReadWriteMode mode, int writeSize, bool startWithFlush) { foreach (CancellationToken nonCanceledToken in new[] { CancellationToken.None, new CancellationTokenSource().Token }) @@ -1786,7 +1776,6 @@ public virtual async Task ReadWrite_Success(ReadWriteMode mode, int writeSize, b [Theory] [MemberData(nameof(ReadWrite_Modes))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadWrite_MessagesSmallerThanReadBuffer_Success(ReadWriteMode mode) { if (!FlushGuaranteesAllDataWritten) @@ -1835,7 +1824,6 @@ public virtual async Task ReadWrite_MessagesSmallerThanReadBuffer_Success(ReadWr [Theory] [MemberData(nameof(AllReadWriteModesAndValue), false)] [MemberData(nameof(AllReadWriteModesAndValue), true)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Read_Eof_Returns0(ReadWriteMode mode, bool dataAvailableFirst) { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -1874,7 +1862,6 @@ public virtual async Task Read_Eof_Returns0(ReadWriteMode mode, bool dataAvailab [InlineData(ReadWriteMode.SyncArray)] [InlineData(ReadWriteMode.AsyncArray)] [InlineData(ReadWriteMode.AsyncAPM)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Read_DataStoredAtDesiredOffset(ReadWriteMode mode) { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -1904,7 +1891,6 @@ public virtual async Task Read_DataStoredAtDesiredOffset(ReadWriteMode mode) [InlineData(ReadWriteMode.SyncArray)] [InlineData(ReadWriteMode.AsyncArray)] [InlineData(ReadWriteMode.AsyncAPM)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Write_DataReadFromDesiredOffset(ReadWriteMode mode) { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -2003,7 +1989,6 @@ public static IEnumerable ReadAsync_ContinuesOnCurrentContextIfDesired [Theory] [MemberData(nameof(ReadAsync_ContinuesOnCurrentContextIfDesired_MemberData))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadAsync_ContinuesOnCurrentSynchronizationContextIfDesired(bool flowExecutionContext, bool? continueOnCapturedContext) { await default(JumpToThreadPoolAwaiter); // escape xunit sync ctx @@ -2086,7 +2071,6 @@ public virtual async Task ReadAsync_ContinuesOnCurrentSynchronizationContextIfDe [Theory] [MemberData(nameof(ReadAsync_ContinuesOnCurrentContextIfDesired_MemberData))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadAsync_ContinuesOnCurrentTaskSchedulerIfDesired(bool flowExecutionContext, bool? continueOnCapturedContext) { await default(JumpToThreadPoolAwaiter); // escape xunit sync ctx @@ -2176,7 +2160,6 @@ await Task.Factory.StartNew(() => [InlineData(ReadWriteMode.AsyncMemory)] [InlineData(ReadWriteMode.SyncAPM)] [InlineData(ReadWriteMode.AsyncAPM)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ZeroByteRead_BlocksUntilDataAvailableOrNops(ReadWriteMode mode) { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -2243,7 +2226,6 @@ public virtual async Task ZeroByteRead_BlocksUntilDataAvailableOrNops(ReadWriteM [InlineData(ReadWriteMode.AsyncMemory)] [InlineData(ReadWriteMode.SyncAPM)] [InlineData(ReadWriteMode.AsyncAPM)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ZeroByteWrite_OtherDataReceivedSuccessfully(ReadWriteMode mode) { byte[][] buffers = new[] { Array.Empty(), Encoding.UTF8.GetBytes("hello"), Array.Empty(), Encoding.UTF8.GetBytes("world") }; @@ -2297,7 +2279,6 @@ public virtual async Task ZeroByteWrite_OtherDataReceivedSuccessfully(ReadWriteM [Theory] [InlineData(false)] [InlineData(true)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadWrite_CustomMemoryManager_Success(bool useAsync) { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -2418,7 +2399,6 @@ public virtual async Task CopyToAsync_AllDataCopied_Large(bool useAsync) => [Theory] [MemberData(nameof(CopyToAsync_AllDataCopied_MemberData))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task CopyToAsync_AllDataCopied(int byteCount, bool useAsync) { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -2456,7 +2436,6 @@ await Task.WhenAll(Enumerable.Range(0, 20).Select(_ => Task.Run(async () => } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Timeout_Roundtrips() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -2491,7 +2470,6 @@ public virtual async Task Timeout_Roundtrips() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task ReadTimeout_Expires_Throws() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -2626,7 +2604,6 @@ public virtual async Task ReadAsync_DuringReadAsync_ThrowsIfUnsupported() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Flush_ValidOnWriteableStreamWithNoData_Success() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -2641,7 +2618,6 @@ public virtual async Task Flush_ValidOnWriteableStreamWithNoData_Success() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Flush_ValidOnReadableStream_Success() { using StreamPair streams = await CreateConnectedStreamsAsync(); @@ -2659,7 +2635,6 @@ public virtual async Task Flush_ValidOnReadableStream_Success() [InlineData(0)] [InlineData(1)] [InlineData(2)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public virtual async Task Dispose_ClosesStream(int disposeMode) { if (!CansReturnFalseAfterDispose) diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index 4f9b32add6f0d..0bba8e10a09f6 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -22,7 +22,7 @@ public abstract partial class FileCleanupTestBase : IDisposable /// Initialize the test class base. This creates the associated test directory. protected FileCleanupTestBase(string tempDirectory = null) { - tempDirectory ??= Path.GetTempPath(); + tempDirectory ??= PlatformDetection.IsNotRunningOnMacOS ? Path.GetTempPath() : "/tmp/"; // Use a unique test directory per test class. The test directory lives in the user's temp directory, // and includes both the name of the test class and a random string. The test class name is included @@ -108,7 +108,7 @@ protected string GetTestFileName(int? index = null, [CallerMemberName] string me const int maxLength = 260 - 5; // Windows MAX_PATH minus a bit int excessLength = testFilePath.Length - maxLength; - + if (excessLength > 0) { // The path will be too long for Windows -- can we diff --git a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs index b38d35ebc3440..8ff457f1deed8 100644 --- a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs +++ b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs @@ -76,6 +76,8 @@ public static partial class PlatformDetection public static bool IsUsingLimitedCultures => !IsNotMobile; public static bool IsNotUsingLimitedCultures => IsNotMobile; + public static bool IsNotRunningOnMacOS => !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") + && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator") && !IsMacCatalyst; public static bool IsLinqExpressionsBuiltWithIsInterpretingOnly => s_LinqExpressionsBuiltWithIsInterpretingOnly.Value; public static bool IsNotLinqExpressionsBuiltWithIsInterpretingOnly => !IsLinqExpressionsBuiltWithIsInterpretingOnly; diff --git a/src/libraries/System.IO.FileSystem/tests/Base/FileGetSetAttributes.cs b/src/libraries/System.IO.FileSystem/tests/Base/FileGetSetAttributes.cs index 2c01cd430d32f..bb26bf9127585 100644 --- a/src/libraries/System.IO.FileSystem/tests/Base/FileGetSetAttributes.cs +++ b/src/libraries/System.IO.FileSystem/tests/Base/FileGetSetAttributes.cs @@ -62,10 +62,9 @@ public void SettingInvalidAttributes_Unix(FileAttributes attributes) AssertSettingInvalidAttributes(path, attributes); } - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotRunningOnMacOS))] [InlineData(FileAttributes.Hidden)] [PlatformSpecific(TestPlatforms.AnyUnix & ~(TestPlatforms.OSX | TestPlatforms.FreeBSD))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void SettingInvalidAttributes_UnixExceptOSXAndFreeBSD(FileAttributes attributes) { string path = CreateItem(); diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/CreateDirectory.cs b/src/libraries/System.IO.FileSystem/tests/Directory/CreateDirectory.cs index fb3a74305bca2..7a69bf3aa2801 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/CreateDirectory.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/CreateDirectory.cs @@ -201,7 +201,6 @@ public void AllowedSymbols() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce() { DirectoryInfo testDir = Create(GetTestFilePath()); diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/Exists.cs b/src/libraries/System.IO.FileSystem/tests/Directory/Exists.cs index b5cff81546e15..5337ae1fef824 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/Exists.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/Exists.cs @@ -301,7 +301,6 @@ public void PathWithReservedDeviceNameAsPath_ReturnsFalse(string component) [Theory, MemberData(nameof(UncPathsWithoutShareName))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void UncPathWithoutShareNameAsPath_ReturnsFalse(string component) { Assert.False(Exists(component)); diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs b/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs index 30479da1286a3..d8426618cf65c 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs @@ -698,16 +698,10 @@ public void WindowsSearchPatternWhitespace() Assert.Empty(GetEntries(TestDirectory, "\t")); } - [ConditionalFact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotRunningOnMacOS))] [PlatformSpecific(CaseSensitivePlatforms)] public void SearchPatternCaseSensitive() - { - if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") - || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) - { - throw new SkipTestException("iOS/tvOS simulators run on a macOS host and are subject to the same case sensitivity behavior."); - } - + { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testBase = GetTestFileName(); testDir.CreateSubdirectory(testBase + "aBBb"); diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs b/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs index e3b7a529a774f..e25787c813662 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs @@ -42,7 +42,6 @@ public void EnumerateWithSymLinkToFile() } [ConditionalFact(nameof(AreAllLongPathsAvailable))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void EnumerateFilesOverLegacyMaxPath() { // We want to test that directories under the legacy MAX_PATH (260 characters, including the null) can iterate files diff --git a/src/libraries/System.IO.FileSystem/tests/File/Create.cs b/src/libraries/System.IO.FileSystem/tests/File/Create.cs index d38d6ff47c8bf..f55947be2b16d 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Create.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Create.cs @@ -219,16 +219,10 @@ public void LongFileName() Assert.False(File.Exists(path)); } - [ConditionalFact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotRunningOnMacOS))] [PlatformSpecific(CaseSensitivePlatforms)] public void CaseSensitive() { - if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") - || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) - { - throw new SkipTestException("iOS/tvOS simulators run on a macOS host and are subject to the same case sensitivity behavior."); - } - DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testFile = Path.Combine(testDir.FullName, GetTestFileName()); using (File.Create(testFile + "AAAA")) diff --git a/src/libraries/System.IO.FileSystem/tests/File/Exists.cs b/src/libraries/System.IO.FileSystem/tests/File/Exists.cs index 04ca9b565951f..618f6df535609 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Exists.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Exists.cs @@ -112,8 +112,7 @@ public void PathAlreadyExistsAsDirectory() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/51371", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] - public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow() + public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow() { Assert.All((IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath())), (path) => { diff --git a/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs b/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs index afc49d5244ece..f6449884ba106 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs @@ -62,7 +62,7 @@ public static string GetNamedPipeServerStreamName() return @"LOCAL\" + Guid.NewGuid().ToString("N"); } - if (PlatformDetection.IsWindows) + if (PlatformDetection.IsWindows || !PlatformDetection.IsNotRunningOnMacOS) { return Guid.NewGuid().ToString("N"); } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs index a03b5f1eaa524..d4b15e912d992 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs @@ -7,6 +7,7 @@ using System.Threading; using System.Threading.Tasks; using System.Diagnostics; +using System.Runtime.InteropServices; namespace System.IO.Pipes { @@ -78,7 +79,7 @@ public NamedPipeClientStream(string serverName, string pipeName, PipeDirection d } if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation) { - throw new ArgumentOutOfRangeException(nameof(impersonationLevel), SR.ArgumentOutOfRange_ImpersonationInvalid); + throw new ArgumentOutOfRangeException(nameof(impersonationLevel), SR.ArgumentOutOfRange_ImpersonationInvalid); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { @@ -88,8 +89,15 @@ public NamedPipeClientStream(string serverName, string pipeName, PipeDirection d { IsCurrentUserOnly = true; } - - _normalizedPipePath = GetPipePath(serverName, pipeName); + if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") + || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) + { + _normalizedPipePath = $"/tmp/{pipeName}"; + } + else + { + _normalizedPipePath = GetPipePath(serverName, pipeName); + } _direction = direction; _inheritability = inheritability; _impersonationLevel = impersonationLevel; diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs index 4744afa610486..4d18aea8b2c4f 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs @@ -41,8 +41,11 @@ private void Create(string pipeName, PipeDirection direction, int maxNumberOfSer // We don't have a good way to enforce maxNumberOfServerInstances across processes; we only factor it in // for streams created in this process. Between processes, we behave similarly to maxNumberOfServerInstances == 1, // in that the second process to come along and create a stream will find the pipe already in existence and will fail. + var pipePath = !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") + && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator") ? GetPipePath(".", pipeName) : $"/tmp/{pipeName}"; + _instance = SharedServer.Get( - GetPipePath(".", pipeName), + pipePath, (maxNumberOfServerInstances == MaxAllowedServerInstances) ? int.MaxValue : maxNumberOfServerInstances); _direction = direction; From 7a3053cf7b6da2832b0eb2e594601dd5f5b5c646 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Wed, 19 Jan 2022 18:45:36 +0100 Subject: [PATCH 05/16] #51371 whitespace issue --- .../src/System/IO/Pipes/NamedPipeServerStream.Unix.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs index 4d18aea8b2c4f..2db15594a52e5 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs @@ -43,7 +43,6 @@ private void Create(string pipeName, PipeDirection direction, int maxNumberOfSer // in that the second process to come along and create a stream will find the pipe already in existence and will fail. var pipePath = !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator") ? GetPipePath(".", pipeName) : $"/tmp/{pipeName}"; - _instance = SharedServer.Get( pipePath, (maxNumberOfServerInstances == MaxAllowedServerInstances) ? int.MaxValue : maxNumberOfServerInstances); From 5e2771da6108e8ef538871e3448440d2c6db6286 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Thu, 20 Jan 2022 09:49:42 +0100 Subject: [PATCH 06/16] #51371 removed extra spaces --- .../tests/TestUtilities/System/IO/FileCleanupTestBase.cs | 3 +-- src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index 0bba8e10a09f6..7ee8b9c6ee40e 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -107,8 +107,7 @@ protected string GetTestFileName(int? index = null, [CallerMemberName] string me const int maxLength = 260 - 5; // Windows MAX_PATH minus a bit - int excessLength = testFilePath.Length - maxLength; - + int excessLength = testFilePath.Length - maxLength; if (excessLength > 0) { // The path will be too long for Windows -- can we diff --git a/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs b/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs index f6449884ba106..b2dda99e0831e 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs @@ -62,7 +62,7 @@ public static string GetNamedPipeServerStreamName() return @"LOCAL\" + Guid.NewGuid().ToString("N"); } - if (PlatformDetection.IsWindows || !PlatformDetection.IsNotRunningOnMacOS) + if (PlatformDetection.IsWindows || !PlatformDetection.IsNotRunningOnMacOS) { return Guid.NewGuid().ToString("N"); } From 4b2dfb1e93327bed07c4a993483221aea89d94f8 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Thu, 20 Jan 2022 11:32:33 +0100 Subject: [PATCH 07/16] Squashed commit of the following: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit commit 36cdb5fc0c38cbb44291114e48e2b202ff37db01 Author: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com> Date: Thu Jan 20 11:03:02 2022 +0100 [wasm][debugger] Added support for stepper boundary attribute (#63991) * Hidden methods and step through methods behave the same way. * Perpared flow for setting JustMyCode in the future. * Tests for JustMyCode setting before debug launch. * Transformed into dynamic JustMyCode change flow. * JustMyCode disabled, first 3 cases solved. * Finished behavior for JMC disabled (with 1 difference). * JMC enabled: stepIn np bp + stepIn bp + resume bp. * Functional version (with minor deviations from expected behavior). * Refactoring. * All tests for NonUserCode work. * Fix line number after adding code above. * Stepper boundary with tests. * Save information about multiple decorators. * Fix error in merge. commit 5a523cf27a9b73e61adb1408f21b5e75a2246d9e Author: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com> Date: Thu Jan 20 10:26:06 2022 +0100 [debugger][wasm] Added support for non user code attribute (#63876) * Hidden methods and step through methods behave the same way. * Perpared flow for setting JustMyCode in the future. * Tests for JustMyCode setting before debug launch. * Transformed into dynamic JustMyCode change flow. * JustMyCode disabled, first 3 cases solved. * Finished behavior for JMC disabled (with 1 difference). * JMC enabled: stepIn np bp + stepIn bp + resume bp. * Functional version (with minor deviations from expected behavior). * Refactoring. * All tests for NonUserCode work. * Fix line number after adding code above. * Fix error in merge. * Removing duplicated tests. commit 8f2c84f02b74dbbe6e1f02dc9be37cf3ee288d6e Author: Peter Sollich Date: Thu Jan 20 10:06:45 2022 +0100 Fix issues with verify_regions, clear_batch_mark_array_bits. (#63798) Details: - we cannot verify the tail of the region list from background GC, as it may be updated by threads allocating. - fix case in clear_batch_mark_array_bits where end is equal to the very end of a segment and we write into uncommitted memory in the mark_array. - bgc_clear_batch_mark_array_bits did some checks and then called clear_batch_mark_array_bits which repeated the exact same checks. Renamed clear_batch_mark_array_bits to bgc_batch_mark_array_bits and removed the old copy, removed the declaration for clear_batch_mark_array_bits. commit e4bfedd847990795eb28cda4008b5ff4c58fd561 Author: Jeremy Barton Date: Thu Jan 20 00:06:28 2022 -0800 Fix OpenSSL version check in GetAlpnSupport The previous check failed 3.0.0 because the Minor was 0 and Build was 0. It could probably be rewritten to be `>= new Version(1, 0, 2)`, but that'd require more thinking. commit 2cf6b0d07309a3c19938f4c886fe13e8d5cc28ee Author: Andrew Au Date: Wed Jan 19 20:57:41 2022 -0800 Fix gc_heap::remove_ro_segment (#63473) commit 65a5d0e8a3027f2b240d098f47327ba3e1f743b1 Author: Tlakaelel Axayakatl Ceja Date: Wed Jan 19 19:46:45 2022 -0800 Add ProcessLinkerXmlBase to NativeAOT (#63666) Add Xml Parsing linker files as a reference source to NativeAOT Rename NativeAOT ProcessLinkerXmlBase version to ProcessXmlBase (uses XmlReader) Add ProcessLinkerXmlBase from linker and fix it so it can be used in NativeAOT (uses XPath) commit f1c8b10ef824c5abf0c851f610ab0961ca31693f Author: Egor Chesakov Date: Wed Jan 19 19:43:26 2022 -0800 [Arm64] Keep unrolling InitBlock and CopyBlock up to 128 bytes (#63422) * Add INITBLK_LCL_UNROLL_LIMIT and CPBLK_LCL_UNROLL_LIMIT of 128 bytes in src/coreclr/jit/targetarm64.h * Keep unrolling InitBlock up to INITBLK_LCL_UNROLL_LIMIT bytes when dstAddr points to the stack in src/coreclr/jit/lowerarmarch.cpp * Keep unrolling CopyBlock up to CPBLK_LCL_UNROLL_LIMIT bytes when both srcAddr and dstAddr point to the stack in src/coreclr/jit/lowerarmarch.cpp commit a5158df084780e52005e4dcbd02ee091542e06d0 Author: Will Smith Date: Wed Jan 19 18:44:19 2022 -0800 'cmeq' and 'fcmeq' Vector64.Zero/Vector128.Zero ARM64 containment optimizations (#62933) * Initial work * Added a comma to display * Cleanup * Fixing build * More cleanup * Update comment * Update comment * Added CompareEqual Vector64/128 with Zero tests * Do not contain op1 for now * Wrong intrinsic id used * Removing generated tests * Removing generated tests * Added CompareEqual tests * Supporting containment for first operand * Fix test build * Passing correct register * Check IsVectorZero before not allocing a register * Update comment * Fixing test * Minor format change * Fixed formatting * Renamed test * Adding AdvSimd_Arm64 tests: * Adding support for rest of 'cmeq' and 'fcmeq' instructions * Removing github csproj * Minor test fix * Fixed tests * Fix print * Minor format change * Fixing test * Added some emitter tests * Feedback * Update emitarm64.cpp * Feedback commit 68a923a24edb47f1d0e3c38a69d4091a7587bfc4 Author: Andrew Au Date: Wed Jan 19 17:59:07 2022 -0800 Check if the child object is in the heap range before object_gennum (#63970) commit 752569f66bcde98fcc4dd1e651f9f1f138184c5c Author: Andrew Au Date: Wed Jan 19 17:58:39 2022 -0800 Check if the child object is in the heap range before get_region_plan_gen_num (#63828) commit 5cefc0f9e618e2d8b38d7de67bbd8a50adb9646f Author: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Thu Jan 20 04:23:50 2022 +0300 Fix invalid threading of nodes in rationalization (#64012) The code in question assumes that the ASG will be reversed and thus threads "simdTree" before "location" in the linear order. That dependency, while valid, because "gtSetEvalOrder" will always reverse ASGs with locals on the LHS, is unnecessary and incorrect from the IR validity point of view. Fix this by using "InsertAfter" instead of manual node threading. commit 93dc760481bdde2c463d725c2927b9da8787eb98 Author: Tomáš Rylek Date: Thu Jan 20 01:52:15 2022 +0100 Fix Crossgen2 bug #61104 and add regression test (#63956) The issue tracks the runtime regression failure where Crossgen2-compiled app is unable to locate a type with non-ASCII characters in its name. The failure was caused by the fact that Crossgen2 was incorrectly zero-extending the individual UTF8 characters when calculating the hash whereas runtime is sign-extending them. Thanks Tomas commit 94b699cc6f6b88c6de1d13152143d32285c59555 Author: Jeremy Koritzinsky Date: Wed Jan 19 16:46:00 2022 -0800 Update StructMarshalling design now that DisableRuntimeMarshallingAttribute is approved (#63765) Co-authored-by: Elinor Fung commit a618086f53fa755732697fba171a16e8bf67900a Author: Andy Ayers Date: Wed Jan 19 16:01:16 2022 -0800 JIT: fix up switch map for out-of-loop predecessor (#64014) If we have a loop where some of the non-loop predecessors are switchs, and we add pre-header to the loop, we need to update the switch map for those predecessors. Fixes #63982. commit 7f828a7e6b712bdeab02d75160249cd13c26a467 Author: Egor Bogatov Date: Thu Jan 20 02:08:10 2022 +0300 [arm64] JIT: Redundant zero/sign extensions after ldrX/ldrsX (#62630) commit ae1b755cd074745b0f09e826d3c7064b2a8f20dd Author: Dan Moseley Date: Wed Jan 19 16:07:53 2022 -0700 Retries for flaky WMI test (#64008) commit 54eec5d1f4d7ded21e33e65c63ada26afe80b208 Author: Elinor Fung Date: Wed Jan 19 14:23:48 2022 -0800 Make ILStubGenerated event log ModuleID corresponding to that on other events (#63974) commit 97fec41a752f067f4d6dde170073300e1184693b Author: Santiago Fernandez Madero Date: Wed Jan 19 14:18:21 2022 -0800 Add runtime-extra-platforms pipeline to have matching runtime PR and Rolling builds (#62564) * Add runtime-extended-platforms pipeline to have matching runtime PR and Rolling builds * Fix evaluate changed paths condition for the extra pipeline * PR Feedback and fix condition * Move MacCatalyst back to staging, disable tvOS tests * Disable browser wasm windows legs commit 826e03e4b984d3bb76b2ead5f6ebb847be9c616f Author: Jeremy Koritzinsky Date: Wed Jan 19 14:08:07 2022 -0800 Bump Explicit-layout value types with no fields to at minimum 1 byte size. (#63975) commit 6f8d8b20a0c78dcfc09ea7a43db48a9a4e055e13 Author: Ankit Jain Date: Wed Jan 19 16:41:04 2022 -0500 Disable hot reload tests for AOT configurations (#64006) commit 675c16711007536120fa2ef7b69224e44299d1e3 Author: Egor Chesakov Date: Wed Jan 19 12:59:49 2022 -0800 [Arm64] Don't use D-copies in CopyBlock (#63588) * Increase the maximum number of internal registers allowd per node in src/coreclr/jit/lsra.h * Based on discussion in https://github.com/dotnet/runtime/issues/63453 don't allocate a SIMD register pair if the JIT won't be able to use Q-copies in src/coreclr/jit/lsraarmarch.cpp * Update CodeGen to reflect that Q-copies should be used only when size >= 2 * FP_REGSIZE_BYTES and using of them makes the instruction sequence shorter in src/coreclr/jit/codegenarmarch.cpp * Update comment - we don't use D-copies after that change in src/coreclr/jit/codegenarmarch.cpp commit ac4c7fb9457a8b0972686b017d82367d7a9bf1ca Author: Pavel Savara Date: Wed Jan 19 20:59:01 2022 +0100 - mono_wasm_new_external_root for roots on stack (#63997) - temp_malloc helper via linear buffer in js - small refactorings Co-authored-by: Katelyn Gadd commit 65db54e2a92a2ef8ba8a75c70990e78f21818e18 Author: Egor Bogatov Date: Wed Jan 19 22:23:45 2022 +0300 Add IsKnownConstant jit helper and optimize 'str == ""' with str.StartsWith('c') (#63734) Co-authored-by: Miha Zupan Co-authored-by: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> commit ded841a690e73c04ebdc86c681893bf9fd372751 Author: Egor Bogatov Date: Wed Jan 19 22:22:49 2022 +0300 Don't reuse registers in Debug mode (#63698) Co-authored-by: Bruce Forstall commit 67848f23d51562bd2e54f6490f5aad22f57baffe Author: Brennan Date: Wed Jan 19 11:01:24 2022 -0800 [RateLimiting] Dequeue items when queuing with NewestFirst (#63377) commit 12f434db114e629854e7d5eb966e07d24e243712 Author: Adeel Mujahid <3840695+am11@users.noreply.github.com> Date: Wed Jan 19 20:42:27 2022 +0200 Fix for Werror=use-after-free in PAL (#63954) * Fix for Werror=use-after-free in PAL * Delete Local{Alloc,Free} * Delete LMEM_* macros * Delete PAL_dladdr commit bbbfba31b61a2299c434172f709716325c073ef8 Author: Stephen Toub Date: Wed Jan 19 12:27:25 2022 -0500 Use IndexOf in StringBuilder.Replace(char, char) (#63913) commit df049b9a23c5182bf7f26f224b69bf1f47f9dc2f Author: Dan Moseley Date: Wed Jan 19 09:26:30 2022 -0700 Disable 2 SMTP tests on checked runtime (#63947) commit 8604989022950ef38f94b9150043b31d81f061a5 Author: Maksym Koshovyi Date: Wed Jan 19 17:49:39 2022 +0200 [Group 5] Enable nullable annotations for `Microsoft.Extensions.Configuration.Json` (#63694) * Nullable enable commit a8c1408084714a7db13db7eb5cae10b209d9c096 Author: TobiasLaving <95348503+TobiasLaving@users.noreply.github.com> Date: Wed Jan 19 16:04:02 2022 +0100 Update runtime.json with manjaro information (#63338) Without specifying runtime on manjaro we cannot run the projects. FYI: Manjaro has a "ID_LIKE" param in os_release that has arch as input. Perhaps that would be another way forward. commit 31f20c54ad56946a506d705261a5445930b56d29 Author: Stephen Toub Date: Wed Jan 19 09:57:04 2022 -0500 Improve auto-atomicity for conditionals (#63299) - Allow for automatically making loops that end conditional branches be atomic - Allow for using a following expression conditional to make a prior loop atomic - Allow conditionals to influence the computed minimum length commit 8fe0467efd29d952fc2afbf302c1d8a1bb3b2fa5 Author: Maxim Lipnin Date: Wed Jan 19 16:55:40 2022 +0300 Take MacCatalyst into account in EnvironmentTests.WorkingSet_Valid test (#63995) Follow-up on https://github.com/dotnet/runtime/pull/63934 commit b042bc3043f3f7f475f5bd6e8f58df2952dd9250 Author: Radek Zikmund <32671551+rzikm@users.noreply.github.com> Date: Wed Jan 19 14:15:57 2022 +0100 Avoid allocating byte array when setting ALPN list on Linux (#63674) * Avoid allocating byte array when setting ALPN list * Code review feedback * Apply suggestions from code review Co-authored-by: Stephen Toub * Slice the stackalloc'd buffer to correct length Co-authored-by: Miha Zupan * Code review fixes Co-authored-by: Stephen Toub Co-authored-by: Miha Zupan commit 34794bc5f2bcdbaa9057bb07b8764e2bb6a411a2 Author: Krzysztof Wicher Date: Wed Jan 19 13:45:01 2022 +0100 Enable System.Text.Json tests on netfx (#63803) * Enable System.Text.Json tests on netfx * use NETFRAMEWORK define * disable another two test cases after rebase * disable last test case which repros only on CI for me * add p2p only on netfx commit e54df94bc9a5e1e064835be817d3e9ac773e1d9a Author: Eirik Tsarpalis Date: Wed Jan 19 11:59:34 2022 +0000 Replace "needs more info" label with "needs-author-action" (#63899) commit a5292a6b54ca743efe2e5b6776864efb7c7702a5 Author: Olivier Giniaux Date: Wed Jan 19 12:56:54 2022 +0100 Fix profiling objectsallocatedbyclass (#63814) * Add test for ObjectsAllocatedByClass profiler callbacks * Fix ObjectsAllocatedByClass profiler callbacks based on wrong flag * Fix wrong args in test log Co-authored-by: Olivier Giniaux commit 6e4dfbfe2db42c9c67f1094dd65ec683c44e3457 Author: Stephen Toub Date: Wed Jan 19 06:53:36 2022 -0500 Improve reductions for Regex empty / nothing nodes (#63695) commit 777c353c767c588824a489ad39238fef01c80f4e Author: Stephen Toub Date: Wed Jan 19 06:53:24 2022 -0500 Extend regex switch alternation optimization to IgnoreCase (#63756) IgnoreCase now results in producing sets (e.g. an 'a' becomes '[Aa]') but the source generator's optimization that produces a switch statements for alternations with non-overlapping branches doesn't yet understand such sets. This augments that logic to fix that. commit a25536f790258fe68240feff864713e8d20b418c Author: Stephen Toub Date: Wed Jan 19 06:52:15 2022 -0500 Improve auto-atomicity for Regex loops (#63986) - As part of recognizing loops that could be made atomic, we currently only look at the node guaranteed to come immediately after it, e.g. in a+b+c+, when analyzing a+ we only look at the b+. That's fine in many cases, but if our expression was instead e.g. a*b*c*, we couldn't make a* atomic because we wouldn't be guaranteed it'd be followed by a b, and we wouldn't look at the subsequent nodes to determine what else might follow. When that situation occurs, we can now walk the tree to find the next node, and repeatedly do so as much as is needed in order to find the next node, enabling us to make all of those loops atomic. - We currently perform the auto-atomicity reduction for single-char loops as part of reducing concatenations. But this means we're performing that transformation at a time when the tree isn't fully formed, which means we can't necessarily reach out of a concatenation to what comes after it and use that to influence the atomicity. It also means we might repeat the analysis unnecessarily multiple times, because it's done as part of parenting a node. We can instead do that optimization as part of the final optimization phase, after the tree is already created. - When we find a lazy loop at the end of an expression, we can treat it as atomic, which means we can lower its max bound to its min bound. - When we encounter a loop (lazy or greedy) at the end of an expression, if it has a max bound of 1 (i.e. it's optional), we can proceed to eliminate ending backtracking with its child regardless of whether the child could be made atomic with the start of the loop, since it won't ever repeat more than once. commit eeaee44e6fe4425db044967e025255e6a12c97a9 Author: dotnet-maestro[bot] <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed Jan 19 11:20:02 2022 +0100 [main] Update dependencies from dotnet/runtime dotnet/arcade dotnet/xharness dotnet/icu dotnet/roslyn-analyzers dotnet/llvm-project (#63737) Co-authored-by: dotnet-maestro[bot] Co-authored-by: Alexander Köplinger commit 313baef638104ed64f93e077c84547421884c91b Author: Egor Bogatov Date: Wed Jan 19 13:16:28 2022 +0300 JIT: Fix repeatable failure for max CALLSITE_DEPTH (#63966) commit a354bb152f4e505d53034c3538f971ad4c2f18ac Author: Stephen Toub Date: Wed Jan 19 04:10:27 2022 -0500 Address follow-up feedback to CachedCompletedInt32Task (#63968) commit b68cf65634bb0d6a1a7e588568959cdc33a0322c Author: Adam Sitnik Date: Wed Jan 19 08:58:20 2022 +0100 Reading beyond EOF should return 0 for FILE_FLAG_NO_BUFFERING (#63625) * move Length to SafeFileHandle, so it's cached value can be reused in more places commit ea2a98163327022e6cefb6a424de4cb4e9618277 Author: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com> Date: Wed Jan 19 08:55:35 2022 +0100 [wasm][debugger] Added support for StepThroughAttribute (#63679) * Hidden methods and step through methods behave the same way. * Perpared flow for setting JustMyCode in the future. * Tests for JustMyCode setting before debug launch. * Transformed into dynamic JustMyCode change flow. * JustMyCode disabled, first 3 cases solved. * Finished behavior for JMC disabled (with 1 difference). * JMC enabled: stepIn np bp + stepIn bp + resume bp. * Functional version (with minor deviations from expected behavior). * Refactoring. commit 00e13f5482ea1156e6b37ea5d242d7f27befb8d3 Author: Adam Sitnik Date: Wed Jan 19 08:42:07 2022 +0100 Add tests for creating memory mapped files from non-seekable files (#63927) commit c66e3c49b59e0894ed3e7c41b0e78dcda22528ae Author: Michal Strehovský Date: Wed Jan 19 15:01:43 2022 +0900 Add support for libraries testing with NativeAOT (#63781) This adds support for running libraries tests with NativeAOT. It reuses the single file xunit runner since we cannot `LoadFrom` the tests on NativeAOT. The strategy is the same as for single file testing: do a publish. To do the NativeAOT publish, we include the Microsoft.DotNet.ILCompiler.targets. commit 3104ed8a3579746eaadb6280acc4fae1ae0df6ed Author: Michal Strehovský Date: Wed Jan 19 15:00:52 2022 +0900 Fix up warnings from delegate thunks (#63980) If we hit a p/invoke with a `System.Delegate` in a delegate marshalling stub, blame the delegate type, not the compiler-generated method. Apparently we marshal System.Delegate in MsQuick interop. commit 0b307c95286a4f468fbb627a66515054ff18dc87 Author: Adeel Mujahid <3840695+am11@users.noreply.github.com> Date: Wed Jan 19 07:25:12 2022 +0200 Add managed implementation of Math/MathF.Abs (#63881) * Add managed implementation of Math/MathF.Abs * Cleanup trailing whitespaces in changeset * Delete unused _copysignf macro commit fc3875f14f310cdce716df30a94feb43db79a28a Author: Jose Perez Rodriguez Date: Tue Jan 18 19:47:09 2022 -0800 Fix case where we incorrectly select a prefix as a FindFirstChar optimization when the pattern includdes an alternation that could lead to different prefixes. (#63976) commit 454ac0a6e7584e1c02677d459d20dae5df61fb47 Author: Stephen Toub Date: Tue Jan 18 22:15:32 2022 -0500 Revert "Improve auto-atomicity for Regex loops (#63518)" (#63984) This reverts commit 557901e779a009cf4a51327963727a4d1ded0094. commit da72791c37480532e647e8f69aff3f2b7eef6049 Author: Jan Kotas Date: Tue Jan 18 18:59:04 2022 -0800 Fix System.Reflection.Metadata version in ILVerification nuget package metadata (#63965) Fixes #63944 commit b7d8f5ecfa7bceb8069448951c7fabd65bcf26a0 Author: Tarek Mahmoud Sayed Date: Tue Jan 18 18:39:37 2022 -0800 Fix Failing Globalization Test on OSX (#63971) commit 546c23804538ee751e4bb419942bc0170c3e5e06 Author: Michal Strehovský Date: Wed Jan 19 10:58:17 2022 +0900 Improve ILLink.targets integration (#63914) Runtime side of https://github.com/dotnet/sdk/pull/23470 (depends on that getting merged). Skip touching the IL Linker semaphore that tricks the target into not running. commit 557901e779a009cf4a51327963727a4d1ded0094 Author: Stephen Toub Date: Tue Jan 18 20:40:35 2022 -0500 Improve auto-atomicity for Regex loops (#63518) * Improve auto-atomicity for Regex loops - As part of recognizing loops that could be made atomic, we currently only look at the node guaranteed to come immediately after it, e.g. in a+b+c+, when analyzing a+ we only look at the b+. That's fine in many cases, but if our expression was instead e.g. a*b*c*, we couldn't make a* atomic because we wouldn't be guaranteed it'd be followed by a b, and we wouldn't look at the subsequent nodes to determine what else might follow. When that situation occurs, we can now walk the tree to find the next node, and repeatedly do so as much as is needed in order to find the next node, enabling us to make all of those loops atomic. - We currently perform the auto-atomicity reduction for single-char loops as part of reducing concatenations. But this means we're performing that transformation at a time when the tree isn't fully formed, which means we can't necessarily reach out of a concatenation to what comes after it and use that to influence the atomicity. It also means we might repeat the analysis unnecessarily multiple times, because it's done as part of parenting a node. We can instead do that optimization as part of the final optimization phase, after the tree is already created. - When we find a lazy loop at the end of an expression, we can treat it as atomic, which means we can lower its max bound to its min bound. - When we encounter a loop (lazy or greedy) at the end of an expression, if it has a max bound of 1 (i.e. it's optional), we can proceed to eliminate ending backtracking with its child regardless of whether the child could be made atomic with the start of the loop, since it won't ever repeat more than once. * Extend auto-atomicity to lazy loops commit 14ebc594b2757e29e1f73742ce37d68f855c0a3c Author: Jan Kotas Date: Tue Jan 18 17:36:09 2022 -0800 Do not register ACTIVATION_SIGNAL for secondary PAL copies (#63961) Related to #63959 commit cde93b69b6b099627d3615ec7f54cfb28b25bcde Author: Andy Ayers Date: Tue Jan 18 16:57:51 2022 -0800 JIT: yet another OSR stress mode (#62980) Existing OSR stress use existing patchpoint placement logic and alter the policy settings so that OSR methods are created more eagerly. This new version of OSR stress alters the patchpoint placement logic, to add patchpoints to more places. In conjunction with the eager policy stress above this leads to creation and execution of large numbers of OSR methods. Any IL offset in the method with an empty stack (and not in a handler) is fair game for a patchpoint, so this new method randomly adds patchpoints to the starts of blocks when stack empty (future work may extend this to mid-block stack empty points). The new mode is enabled by setting `COMPlus_JitRandomOnStackReplacement` to a non-zero value; this value represents the likelihood of adding a patchpoint at a stack-empty block start, and also factors into the random seed. (Recall this is parsed in hex, so 0x64 == 100 or larger will put a patchpoint at the start of every stack empty block). Various values are interesting because once a method reaches a patchpoint and triggers OSR, the remainder of that method's execution is in the OSR method, so later patchpoints in the original method may never be reached. So some sort of random/selective patchpoint approach (in conjunction with varying policy settings) is needed to ensure that we create an execute as many different OSR variants as possible. This PR also includes a couple of fixes exposed by local testing of this new stress mode: * The OSR prolog may end up empty, which gcencoder doesn't like. Detect this and add a `nop` for the prolog. * If we're importing the `fgEntryBB` during OSR, we don't need to schedule it for re-importation. This happens if we put a patchpoint at IL offset zero. * Update the selective dumping policy `COMPlus_JitDumpAtOSROoffset` to only dump OSR method compilations. A new test leg is added to `jit-experimental` to run with this mode enabled with a probability of 21% (0x15) and quick OSR triggers. Also included: * fix probability calc * remove obsolete assert * osr exposed does not apply to simd * only pad zero-sized OSR prolog if we're reporting generic context * Add ability to have patchpoint at specified offset. * Fix interaction of stress patchpoints and profile instrumentation. We need to force block-based instrumentation if we might have stress patchpoints. commit 93cb3559a17aca424e3ce1206a71496da2c34b69 Author: Honza Rameš Date: Wed Jan 19 01:12:18 2022 +0100 Reduce allocations in code generated by Logging generators (#61162) (#62011) commit c50185bb24ace683f2ce6c5e4351ce2104bd1349 Author: Aleksey Kliger (λgeek) Date: Tue Jan 18 18:40:42 2022 -0500 [mono] Hot Reload: initial push to support adding lambdas (#63513) Adds support for: * Adding static lambdas to existing methods, whether or not they had lambdas before. * Adding lambdas that capture `this` to existing methods that already captured `this` before * Adding new static or instance methods to existing types * Adding static fields to existing types * Adding new types (note that adding instance fields currently will fail. It'll go in in a future PR that will address https://github.com/dotnet/runtime/issues/63643). Note that reflection on newly added members isn't tested yet and likely doesn't work. Fixes https://github.com/dotnet/runtime/issues/50249 Contributes to https://github.com/dotnet/runtime/issues/57365 * Add AddStaticField test; cleanup AddLambdaCapturingThis * Add AddNestedClass testcase * hot_reload: add a comment about remaining work * move per-class metadata update info to MonoClassMetadataUpdateInfo Use a property on the class instead of a hash table in the baseline image to keep track of added fields and methods * Cleanup pass1 to check add/update against prior gen Instead of the baseline image * adding a class Working on making mono_metadata_nested_in_typedef do the right thing for nested classes Contributes to making mono_class_create_from_typedef do the right thing for nested classes. * fix: correct mutant table population when the baseline table is empty In that case the table row_size and size_bitmap of the baseline are both 0, so offset calculations don't work. In that case when we know we need to add rows to the mutant table, use the uncompressed layout (32-bit columns, always) same as the EnC delta. * Calling new methods on a nested class works * adding fields Doesn't work yet. Dies in mono_class_get_field, called from mono_field_from_token_checked. The problem we're going to have to deal with is that unlike MonoMethod which is allocated upon lookup, the MonoClassFields of a class are allocated contiguously in class initialization. And there are not really enough fields in MonoClassField to indicate "this is not an ordinary field, don't do pointer arithmetic with it". One idea is to steal a bit from MonoClassField:parent and always check it as a trigger to go on a slower path. * adding static fields Rework the delta info to store info about "members" (rather than methods and fields separately). Add a MonoClassMetadataUpdateField subclass of MonoClassField that has extra info. Add new component methods to go from a MonoClassField to an index, and from a field token to a MonoClassField. Set MonoClassField:offset to -1 to generally go down the "special static field" codepath since we will need to do some one-off work to make a storage area for added static fields. Instance fields are not supported yet and error out during the update pass for now. * fix custom attribute lookups on new classes/methods/fields * Add a sketch of HotReloadInstanceFieldTable This is a class that manages the lifetime for added instance fields for reference types that had new fields added to them by EnC It's basically ConditionalWeakTable> where the outer key is the object instance, the inner key is the fielddef token, and the value is a Store. The store has a single object? field which the location where the field's value will go. For reference types this is the reference directly, and for valuetypes and primitives, this is the boxed object (so to get the actual storage address you need to add sizeof(MonoObject)). * mono_metadata_update_get_static_field_addr two reminders: 1. The static field area needs to be GC-visible 2. We should really handle added fields on un-inited classes by allocating the instances in the normal way - in the layout algorithm. * Free MonoClassMetadataUpdateInfo when BaselineInfo is destroyed * placeholder struct for runtime class data; instance offset placeholder * static field storage Need to store the fields in a GC root, and in pinned allocations. * Implement hot_reload_get_static_field_addr() * Add mono_metadata_update_find_method_by_name Now we can find .cctor This is enough that a basic sample with an added static lambda works * Fix infinite loop * fix build * fix dynamic components builds * fix windows build * Fix inadvertent fallthru in previous fix * Report new capabilities NewTypeDefinition is not completely functional because adding instance fields is not supported yet. But adding classes with only static methods works. * tests: describe what existing tests do, add placeholder static lambda test * tests: Add AddStaticLambda test case Adding a brand new static lambda to an existing method body is supported * Destroy the runtime part of MonoClassMetadataUpdateInfo, too * rename Mono.HotReload file it has more classes than just the instance table * tests: add ActiveIssue for supporting adding instance fields * ifdef out Mono.HotReload.InstanceFieldTable it's not ready yet * Remove get_added_members from hot reload component interface Doesn't seem necessary to expose this yet. It's only used in hot_reload.c right now * Change the AddStaticLambda sample to use Func To check that lambdas with parameters work * Use a mempool allocated GSlist for the added members This avoids invalidating iterators in case we add members on one thread while another thread is iterating. If it turns out we need random access, we can switch to a GArray with locking. But so far we only ever iterate. * Use mono_get_corlib instead of passing MonoDefaults to hot_reload * use normal GENERATE_TRY_GET_CLASS_WITH_CACHE * [metadata] make m_field_set_parent and m_field_set_meta_flags inline m_ prefix functions are supposed to be inline commit d2844ebf57568de4926517c521a94a721d9c26a8 Author: Bradley Grainger Date: Tue Jan 18 15:32:16 2022 -0800 Add `UnicodeRange.ArabicExtendedB` (#63901) commit 8d5f5267d33f7703c014cc89670f1f7aa47544f9 Author: Andrii Kurdiumov Date: Wed Jan 19 05:23:32 2022 +0600 Update links to the project for DllImportGenerator (#63940) As coincidence, I think `RestoreAdditionalProjectSources` not needed anymore. commit 83b52cdc310ebd77cddff7efd772a0800a403f47 Author: Alexander Köplinger Date: Tue Jan 18 23:13:58 2022 +0100 [iOS/tvOS] Remove P/Invokes to libproc from System.Private.CoreLib (#63934) They aren't allowed by Apple when submitting to the App Store. Finishes https://github.com/dotnet/runtime/issues/61265 commit b0de23b1677fbaf4fbcde814ec0bad6f60094920 Author: Andy Gocke Date: Tue Jan 18 13:37:41 2022 -0800 Revert "Enable GC Regions by default (#59283)" (#63935) This reverts commit cf91716. This looks to be creating a lot of crashes in a lot of different unit tests on Mac. Reverting seems to halt the Mac failures (see https://dev.azure.com/dnceng/public/_build/results?buildId=1557880) Fixes #63439 commit 0266f034221188bc7d0156ba76a571c71885c68f Author: Kunal Pathak Date: Tue Jan 18 11:04:48 2022 -0800 Fix decoding errors (#63929) commit 078da6c37e2ab602fe37ab699051ef71161ce2cc Author: Bruce Forstall Date: Tue Jan 18 11:04:22 2022 -0800 Introduce `BasicBlock::KindIs()` for checking bbJumpKind (#63203) * Introduce `BasicBlock::KindIs()` for checking bbJumpKind This can simplify code that is checking for multiple `bbJumpKind` kinds with an `if` statement, where a `switch` is not warranted. It's the same usage model as `GenTree::OperIs()`. e.g., ``` if (block->KindIs(BBJ_COND, BBJ_SWITCH, BBJ_RETURN)) ``` * Fix argument name commit 82b8d79b6f858f0d44791e3eab36735b7093d935 Author: Shane Krueger Date: Tue Jan 18 13:56:09 2022 -0500 Fix NullabilityInfoContext.Create to properly analyze types with nested generic types (#63556) commit f04a24249835096eea1a1a66e4af03cfec5ed32b Author: Artem Kliatchkine Date: Tue Jan 18 18:18:45 2022 +0100 Set zero (infinite) options timeout in case of Timeout.InfiniteTimeSpan (#55984) (#63733) Co-authored-by: Artem Kliatchkine commit 2eb2e883dc807897fe07dd6559462e37e8613693 Author: Tomas Weinfurt Date: Tue Jan 18 09:18:29 2022 -0800 improve protocol detection in jail (#63565) * improve protocol detection in jail * add comment commit d18d6c703295555d466fb159f8dec64857f68ed9 Author: Kevin Jones Date: Tue Jan 18 12:15:11 2022 -0500 Update SAN test to account for OpenSSL 3 changes commit 64896116e66377aa8e951abb9e9505aff8a25f89 Author: Kevin Jones Date: Tue Jan 18 11:36:15 2022 -0500 Fix OpenSSL 3 reporting an OutOfMemoryException for missing private key commit 5a12420546d7f0d963bcccf082400c1b057e38ef Author: Maxim Lipnin Date: Tue Jan 18 18:21:33 2022 +0300 Remove individual exclusions for DllImportGenerator.Unit.Tests in favor of the general one for the entire set of mobile targets (#63924) commit 39ef452edcf90bae76a1e4c8c1c24209e17ac5f2 Author: Maxim Lipnin Date: Tue Jan 18 18:20:15 2022 +0300 Disable DllImportGenerator.Unit.Tests test suite on macOS+arm64+CoreCLR (#63887) commit 856e8c3510cb0aaaa3b1a1679552c03ae5308b9e Author: Adeel Mujahid <3840695+am11@users.noreply.github.com> Date: Tue Jan 18 17:16:10 2022 +0200 Fix compilation with older gcc (#63721) commit 2f366a85444570429f8739b13bde18226a10bc86 Author: Adeel Mujahid <3840695+am11@users.noreply.github.com> Date: Tue Jan 18 17:12:47 2022 +0200 Delete a few unused PAL APIs (#63916) * Delete _fullpath PAL API * Delete PAL_wcscspn * Delete PAL_wcstok commit 207590a7b82afa086e889f3fc695b104713f7c8e Author: Michal Strehovský Date: Wed Jan 19 00:10:36 2022 +0900 Fold coreclr/ToolBox into coreclr/tools (#63917) This separation only existed because of Razzle build sequencing of desktop CLR. It doesn't make sense for CoreCLR. The only thing the extra directory is doing now is that it breaks tab completion when navigating the CoreCLR source tree because ToolBox comes before tools alphabetically and most things live in tools. commit e30fe9b4d3afabc4acdfcaa539ecf213c16aea1a Author: Theodore Tsirpanis Date: Tue Jan 18 16:58:11 2022 +0200 Encapsulate the logic of caching the last synchronously completed task. (#61781) * Encapsulate the logic of caching the last synchronously completed task. * Apply suggestions from code review Co-authored-by: Adam Sitnik commit e6ad043996419f04b1c0ae9fea113318f61e234f Author: Michal Strehovský Date: Tue Jan 18 23:32:28 2022 +0900 Split CheckNotDisposed to allow inlining (#63863) * Split CheckNotDisposed to allow inlining `CheckNotDisposed` is not getting inlined because RyuJIT thinks it's not profitable (ldstr/newobj/throw is expensive). If we extract the rare path into a separate method, it changes the profitability math and allows inlining to happen. * Review feedback commit dfb36ae68d9a099c9b90317c97bdf485bab4121e Author: Stephen Toub Date: Tue Jan 18 09:31:12 2022 -0500 Fix a few IndexOf{Any} uses (#63852) commit 7a0388a9f1a11b723aa09aeae3436a078b32bb43 Author: Eirik Tsarpalis Date: Tue Jan 18 13:33:57 2022 +0000 Extend triage board automation to more pods (#63897) commit 8d8ef6dac58acf2ab944289c69dd46ee9e12d717 Author: Tom Deseyn Date: Tue Jan 18 11:00:35 2022 +0100 FileSystemEntry.Unix: don't make a syscall to check hidden on Linux. (#63878) commit 24bdc3844c3de6d6a3c47534411c8322ae1a7bc6 Author: dotnet-maestro[bot] <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Tue Jan 18 10:41:02 2022 +0100 [main] Update dependencies from dotnet/linker (#63445) Co-authored-by: dotnet-maestro[bot] commit 126db6dd10fcf618a9ab17ed93347044cc5a3a24 Author: Michal Strehovský Date: Tue Jan 18 14:19:20 2022 +0900 Disable warnings as errors in the repro project (#63910) commit d0e2dac3a828b6afda5cff812b7b09b9dba213b7 Author: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Tue Jan 18 01:23:41 2022 +0300 Actually properly type primary selectors (#63752) * Use only one [out] parameter in IsFieldAddr Since only one is needed. * Actually properly type primary selectors commit d48a44f2ee2f6b4b039ca10cfd5dc01c331669f5 Author: Michal Strehovský Date: Tue Jan 18 02:11:44 2022 +0900 Separate variance information in mangled names (#63866) Fixes https://github.com/dotnet/runtimelab/issues/1821. Eventually we'll need to have a holistic look at how we mangle things. commit 6dcb03913c7d55dca824abcd21617212bef62553 Author: Jan Kotas Date: Mon Jan 17 07:46:40 2022 -0800 Delete UMThkCallFrame (#63826) * Delete UMThkCallFrame * Place UnmanagedToManagedFrame under FEATURE_COMINTEROP commit 4fac9549fea1ccbf296aeaa0861478825d70c5c3 Author: Mandar Sahasrabuddhe Date: Mon Jan 17 16:05:28 2022 +0530 Fix escaped strings for TryGetDateTime(Offset) (#63534) * Fix escaped strings for TryGetDateTime(Offset) Fix the exception thrown when the escaped DateTime(Offset) property value is unescaped and it becomes shorter than the minimum expected length. In such case the Try* method should fail and returns false. Fixes #62720 * Fix escaped strings for TryGetDateTime(Offset) Fix the exception thrown when the escaped DateTime(Offset) property value is unescaped and it becomes shorter than the minimum expected length. In such a case, the Try* method should fail and return false. Fixes #62720 * Fix escaped strings for TryGetDateTime(Offset) Fix the exception thrown when the escaped DateTime(Offset) property value is unescaped and it becomes shorter than the minimum expected length. In such a case, the Try* method should fail and return false. Fixes #62720 * Fix escaped strings for TryGetDateTime(Offset) Fix the exception thrown when the escaped DateTime(Offset) property value is unescaped and it becomes shorter than the minimum expected length. In such a case, the Try* method should fail and return false. Fixes #62720 * Fix escaped strings for TryGetDateTime(Offset) Fix the exception thrown when the escaped DateTime(Offset) property value is unescaped and it becomes shorter than the minimum expected length. In such a case, the Try* method should fail and return false. Fixes #62720 commit d72ed27cfe8656807ece255b275ca9d617af073b Author: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Mon Jan 17 13:11:43 2022 +0300 Treat CLS_VAR_ADDR as never null (#63844) Allows the LIR DCE to remove some indirections that were previously incorrectly thought to be throwing. Contributes to CLS_VAR deletion (by minimizing the diffs). commit bf1d4a10b998a80b92728f80aa5ebbcd5138347a Author: Radek Zikmund <32671551+rzikm@users.noreply.github.com> Date: Mon Jan 17 11:11:10 2022 +0100 Fix generating RunTests.sh and RunTests.cmd scripts (#63875) This fixes issue where generated RunTests.sh in the "To repro directly: " section contained unevaluated variables like RUNTIME_PATH, which prevented simple copy-pasting the code into the terminal commit ae2f60c950cc021921fce83c796cbcb5ff96c658 Author: Andrii Kurdiumov Date: Mon Jan 17 09:57:15 2022 +0600 NativeAOT: Allow Delegate and MulticastDelegate marshalling (#63219) - Closes https://github.com/dotnet/runtimelab/issues/1107 - Progress towards https://github.com/GtkSharp/GtkSharp/issues/300 commit 84926be4243143b7830e78cb7727057ed711a3cc Author: Andrii Kurdiumov Date: Mon Jan 17 07:42:08 2022 +0600 Prevent assert if stack trace has function pointer (#63787) commit 217b288cfabd2368082343c7e36e7ac0a8f96db9 Author: Adeel Mujahid <3840695+am11@users.noreply.github.com> Date: Mon Jan 17 03:10:54 2022 +0200 Convert h2inc to a cmake function (#63841) * Convert h2inc to a cmake function * Reuse preprocess_file commit ec349cd8e9960ec44bf528eef52c56a87e601207 Author: Tomáš Rylek Date: Sun Jan 16 20:50:01 2022 +0100 Fix a few IL tests using the namespace syntax without an actual namespace (#63772) commit 4f34cedc8eefb2a396646a67869e784f06d7def8 Author: Tomáš Rylek Date: Sun Jan 16 20:45:15 2022 +0100 Disable the Runtime_34587 regression test with GH issue #63818 (#63819) commit bf65675a8181d5448134788a148f844d35c4f091 Author: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Sun Jan 16 20:21:52 2022 +0300 Compress operand kinds array and optimize `OperIsLocal` (#63253) * Delete GTK_CONST * Delete OperIsRelop * Delete GTK_RELOP * Delete GTK_LOGOP * Delete GTK_LOCAL * Compress oper kinds They now fit into 8 bits. commit 23de81782ca9cd24f024bd598563d363df29660c Author: Zoltan Varga Date: Sat Jan 15 22:05:07 2022 -0500 [mono] Disable partial generic sharing for gparams with non-enum constraints for method gparams too. (#63813) This is an optimization, but it also avoids hitting some gsharing limitations wrt calling abstract static methods from gshared code. Fixes https://github.com/dotnet/runtime/issues/60447. commit c5c7967ddccc46c84c98c0e8c7e00c3009c65894 Author: Stephen Toub Date: Sat Jan 15 20:35:25 2022 -0500 Unify string.{Last}IndexOfAny and span.{Last}IndexOfAny (#63817) * Unify string.{Last}IndexOfAny and span.{Last}IndexOfAny Currently, string.IndexOfAny delegates to span.IndexOfAny (MemoryExtensions) for 1 through 5 values, and for more than it, it falls back to its own "probabilistic map"-based implementation, which tries to avoid looping through each value character for each character in the input. span.IndexOfAny doesn't do that, instead always looping through every char for every input char. This PR moves the logic from string into MemoryExtensions and then has string unconditionally delegate to span. string.LastIndexOfAny in contrast would only delegate to span's implementation if the values list actually only had a single character in it; otherwise, it would again fall back to its own "probabilistic map"-based implementation. This PR again moves that fallback into MemoryExtensions, with string unconditionally delegating to it. MemoryExtensions also has LastIndexOf overloads for 2 and 3 items, so rather than using the probabilistic path for those, it delegates to the existing overloads. * Address PR feedback commit 1e22b3f00501e8263af571ad74cb043fb3407b70 Author: Jeremy Koritzinsky Date: Sat Jan 15 12:59:33 2022 -0800 Refactor the "produce an RSP file" step into a separate step from the "run ILC" step to make it easier to generate the RSP file on the fly (#63820) commit fd2883f7bb60e75df6edcec58ac7bc79ecd10196 Author: Jan Kotas Date: Sat Jan 15 12:21:07 2022 -0800 Delete notifyexternals.* (#63835) Leftovers from loader lock MDA commit 78dea7ff6599dd851210df6db330ee3b58f5294c Author: Stephen Toub Date: Sat Jan 15 10:28:53 2022 -0500 Add Regex FindFirstChar optimization for a literal after an atomic loop (#63477) * Add Regex FindFirstChar optimization for a literal after an atomic loop If after all of our analysis we can't find anything to IndexOf{Any} as part of finding the next match location, we'll also look for a literal (a single char, a string of chars, or a set of a small number of chars) following an unbounded atomic set loop that starts the pattern. In that case, we can IndexOf for the literal, and then walk backwards through the characters prior to it looking for the beginning of the match. * Extend optimization to Setloop/lazy in addition to Setloopatomic commit c30d55ec5b584e26186a85adedf313c81a64269c Author: Tanner Gooding Date: Sat Jan 15 05:00:18 2022 -0800 Perform some minor code cleanup of the System.Numerics and System.Runtime.Intrinsics namespaces (#63753) * Ensure the System.Numerics and System.Runtime.Intrinsics namespaces are using explicit type when "not apparent" to match repo conventions * Ensure the System.Runtime.Intrinsics types are using TARGET_64BIT to match project convention * Improving some docs and simplifying names where possible commit a2e017dc876729678d7874706086bd444f010bcf Author: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Sat Jan 15 15:42:31 2022 +0300 Fix MOffset size estimate (#63766) commit 9db60963097adac1c25a5117d3918de17e1b5fb1 Author: Egor Bogatov Date: Sat Jan 15 15:20:36 2022 +0300 JIT: Mark constant arguments of HWINTRINSIC nodes as DONT_CSE (#63442) commit 20e6ec1a43cab03cd2d48f9fad32d56e83787ea0 Author: Geoff Kizer Date: Sat Jan 15 04:03:03 2022 -0800 Avoid unnecessary string allocation in HttpRuleParser.GetHostLength (#63641) * avoid unnecessary string allocation in HttpRuleParser.GetHostLength Co-authored-by: Geoffrey Kizer commit 25d999b5a6711fc6d2ffc42fa38a58ec865a7232 Author: Stephen Toub Date: Sat Jan 15 06:50:49 2022 -0500 Improve use of {Last}IndexOf{Any} in Regex loops (#63428) * Improve .*string to LastIndexOf "string" rather than just 's' * Enable .*string LastIndexOf optimization in the face of an UpdateBumpalong If the loop starts the expression, we will have inserted an UpdateBumpalong node, but that was then interfering with detecting a subsequent character/string. * Use IndexOf{Any} in lazy loop backtracking * Improve how sets are described in comments * Change RealWorld tests to be invoked once per engine To help with debugging * Address PR feedback commit 386f87139c7fe48f6b733e3cae6d09128c827192 Author: Aleksey Kliger (λgeek) Date: Sat Jan 15 04:05:03 2022 -0500 [metadata] Use MonoDefaults from components without hacks (#63822) commit 692052e016407e6eb11feeaee5269625c3ee741a Author: Ankit Jain Date: Fri Jan 14 23:52:13 2022 -0500 Split `sendtohelixhelp.proj` to extract wasm, and mobile bits to separate files. (#63373) Extract wasm, and mobile specific bits from sendtohelixhelp.proj into … .. separate files, so they can be easier to manage. - the platform specific properties are set in their respective files (for eg `sendtohelixhelp-wasm.proj`) - a new target `BuildHelixCommand` is extracted from `BuildHelixWorkItems`, which runs first - and essentially builds `@(HelixCommand)` - Platform specific targets can run via `$(BuildHelixWorkItemsDependsOn)` - which then add any "special" helix work items - `BuildHelixWorkItems` in the main file supports adding for the regular case, which is controlled by `$(EnableDefaultBuildHelixWorkItems)`. Also, fixes https://github.com/dotnet/runtime/issues/52137 commit 9daaab152ff1c0794ee21645bf57acf444f900ff Author: Anton Firszov Date: Sat Jan 15 03:15:26 2022 +0100 serialize SendPacketsAsync tests (#63702) commit 40047f2a82595546eadbabf9e438f7592eb1f002 Author: Stephen Toub Date: Fri Jan 14 20:48:36 2022 -0500 Improve Regex UpdateBumpalong optimization for non-atomic and lazy loops (#63398) * Improve handling of UpdateBumpalong for non-atomic loops For atomic greedy loops, UpdateBumpalong is serving its purpose: upon consuming as much as possible for the loop, base.runtextpos is set to that position so that the next time FindFirstChar runs, it'll start from at least that location. However, for non-atomic greedy loops, with base.runtextpos being set to the ending position after each backtracking, we end up inadvertently voiding any benefits of the UpdateBumpalong, as we end up overwriting the further position with the shorter position. A simple tweak to that, only setting the position if it's greater, yields significant benefits, in particular when there's no match. * Add more tests for lazy loops These just duplicate the greedy loop tests and tweak them for lazy. * Insert UpdateBumpalong for lazy loops as well * Address PR feedback commit 513fe2863ad5ec6dc453d223d4b60f787a0ffa78 Author: Tomáš Rylek Date: Sat Jan 15 00:36:58 2022 +0100 More duplicate projects under JIT/Methodical/NaN to delete (#63771) commit 2692407f03ce8b648c54daa4d3a3eb534132edc9 Author: Santiago Fernandez Madero Date: Fri Jan 14 13:36:50 2022 -0800 Build all packages on source-build even when in servicing (#63755) commit e1c69cc75a4c51ea3e3011a084f74b486b2dbc88 Author: Tomáš Rylek Date: Fri Jan 14 21:47:44 2022 +0100 Move localloc/common library under JIT folder (#63510) In today source tree we have five different libraries named 'common'. This change is a first step in deduplicating their names; I have also moved the library under the JIT/ folder as it's used not only by JIT/jit64 tests but also by Methodical and Regression tests. Thanks Tomas commit 3a83c5ca772a1a74e1707474c1d05c283f264a2f Author: Jan Kotas Date: Fri Jan 14 12:47:18 2022 -0800 Delete unused method (#63797) commit 02e22b02975d50944220e6e9a494af491487c6a9 Author: Tomáš Rylek Date: Fri Jan 14 21:00:01 2022 +0100 Remove string[] args from Main methods under JIT/Methodical (#63770) In most cases the arguments were formal and not really used so I just fixed the Main method signature. In a bunch of cases the command-line arguments supported variant functionality of the test case but I haven't found any test projects that would be exercising this functionality. I don't think it makes sense to keep untested code paths so I deleted the logic pertaining to non-empty command-line arguments. In the particular case of stringintern tests, each test apparently had a TestSameObjRef and TestDiffObjRef variant, triggered by command-line arguments. I tried to run TestDiffObjRef but it ended up failing left and right - not suprising for untested code logic - so I also deleted the TestDiffObjRef variants as I suppose the invariants previously tested there no longer hold. Thanks Tomas commit 562606671166edb60234c5062f69b35f6b2ac5c9 Author: Egor Chesakov Date: Fri Jan 14 10:44:07 2022 -0800 Enable superpmi-collect pipeline on macOS arm64 (#63691) * Enable superpmi-collect on macOS Arm64 in eng/pipelines/coreclr/superpmi-collect.yml * Add -platform argument and use the value for determining what Helix queue to use in src/coreclr/scripts/superpmi_collect_setup.py * Pass platform to superpmi_collect_setup.py in eng/pipelines/coreclr/templates/run-superpmi-collect-job.yml * Copy *.dylib on macOS and *.so on Linux in src/coreclr/scripts/superpmi_collect_setup.py * Install azure-storage-blob in eng/pipelines/coreclr/templates/run-superpmi-collect-job.yml * Remove macOS/x64 from platforms list in eng/pipelines/coreclr/superpmi-collect.yml * Add "CoreCLR Product Build OSX x64 checked" that produces required artifacts that consumed by macOS/arm64 superpmi-collect-job * Fix typo in libraries_test_assets should correspond to target arch in eng/pipelines/coreclr/templates/superpmi-collect-job.yml * Update a comment indicating what Helix queues are used for macOS in src/coreclr/scripts/superpmi_collect_setup.py * Workaround https://github.com/dotnet/sdk/issues/23430 in src/coreclr/scripts/superpmi_benchmarks.py * Enable macOS/arm64 benchmarks collection in eng/pipelines/coreclr/superpmi-collect.yml commit a991e1349e4325770d8e2ddf085184a68cd2555b Author: Elinor Fung Date: Fri Jan 14 10:49:26 2022 -0500 Make ObjectiveC tests in System.Runtime.InteropServices.Tests check exit code for remote execution (#63769) commit 33179fa0ac1ab75bb09e5cc7ed63aa6629c51411 Author: Maksym Koshovyi Date: Fri Jan 14 17:49:06 2022 +0200 [Group 5] Enable nullable annotations for `Microsoft.Extensions.Configuration.Ini` (#60368) * Add annotations * Use pattern matching * NetCoreAppMinimum * ReadLine won't return null * Update src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.csproj Co-authored-by: Eric Erhardt * Add comment * Revert non-nullable change Co-authored-by: Eric Erhardt commit 3956126d55e32203a8926a54a8ee3090b3e69749 Author: MSDN.WhiteKnight <35516665+MSDN-WhiteKnight@users.noreply.github.com> Date: Fri Jan 14 20:33:03 2022 +0500 Fix typo in SRM package description (#63782) commit d568a3fec2c9a2e7341466a28f88f52558fddf6c Author: Tarek Mahmoud Sayed Date: Fri Jan 14 07:27:32 2022 -0800 Introduce Activity.IsStopped Property (#63713) Co-authored-by: Dan Moseley commit 0b527a201f4c286f13ef8b829bbd1651bdad7a52 Author: Zoltan Varga Date: Fri Jan 14 08:07:47 2022 -0500 Fix a style issue. (#63776) commit b184ee0393aaf0395a69e70590d5c529e8c93ccf Author: Adam Sitnik Date: Fri Jan 14 10:04:11 2022 +0100 MemoryMappedFile: don't check for file existence if there is no need (#63754) Co-authored-by: Stephen Toub commit c96869a6d10a235b5a26c9e15d685fabc7f87cb0 Author: Michal Strehovský Date: Fri Jan 14 17:03:22 2022 +0900 Disable annoying warnings in the repro project (#63777) We have repo-wide WarnAsError that makes this super annoying in a repro project. commit b7e0a85ab6111b77ad19a1c2db0dedcedded4940 Author: Qiao <35673267+shushanhf@users.noreply.github.com> Date: Fri Jan 14 14:33:20 2022 +0800 [LoongArch64] add all the coreclr-build-config files (#62889) commit 1ba80f698c85b525545f1a13c02eb405588b0461 Author: Andrii Kurdiumov Date: Fri Jan 14 12:20:45 2022 +0600 Remove errors during first run of runpaltests.h (#62642) * Remove errors during first run of runpaltests.h If you run `runpaltests.h` for first time, you will see 2 errors about file or folder not found. First error comes from using `RELATIVE_PATH_TO_PAL_TESTS` which does not used anywhere, except maybe some platform where you can `cd` to non-existing folder. In that case 3rd parameter to script would be interpreted incorrectly. I doubt that, but who know what's somewhere deep in infra. Second error is entirely preventable, since `cd $PAL_TEST_OUTPUT_DIR` does not affect anything until subsequent `cd $PAL_TEST_OUTPUT_DIR` on line 118. Discovered here https://github.com/dotnet/runtime/pull/62625#issuecomment-991172978 * Remove not nescessary cd * Fix * oopsie commit 27fdc2d22f8717c7b0ba254ae9ef2900d00f5e7a Author: Stephen Halter Date: Thu Jan 13 17:20:28 2022 -0800 Avoid deadlock with ConfigurationManager (#62209) Co-authored-by: Eric Erhardt commit 2c28e63f9360280011a3b03c1ca6dc0edce1fae4 Author: Alexander Köplinger Date: Thu Jan 13 22:17:54 2022 +0100 Temporarily disable coredumps during library testing on macOS (#63742) System.Runtime.InteropServices.Tests seems to produce >10GB of coredumps which overwhelms CI. commit 79e40e35ce3e218ad2d81259572e462b56bfd807 Author: Kevin Jones Date: Thu Jan 13 15:04:36 2022 -0500 Add public constants for HMAC and hash sizes commit c912a1532a1bb653a21a3749aaad7c5fb556ae01 Author: Kevin Jones Date: Thu Jan 13 14:07:55 2022 -0500 Change non-breaking spaces (U00A0) to a plain space in code files (#63688) commit ec0c7f3a91b9fc47f7a867f0b997ba34560302e7 Author: Aaron Robinson Date: Thu Jan 13 12:20:43 2022 -0500 Add negative tests for by-ref in UnmanagedCallersOnly scenarios. (#63711) commit c78d9fa3edb2ae8e14f0529566c20d33a2512cab Author: Maxim Lipnin Date: Thu Jan 13 19:08:27 2022 +0300 Disable System.Drawing.Common.Tests test suite on Windows+Mono (#63726) commit 048e1a395523f1855c054d01a3f1f4c55d873ea4 Author: Simon Rozsival Date: Thu Jan 13 16:57:12 2022 +0100 [Android] Throw PNSE for unavailable network information (#63633) * Update tests * Add android specific implementation * Add UnsupportedOSPlatform attributes * Fix typo * Remove unnecessary file reference * Clean-up code * Minor code clean-up * Remove dictionary * Refactoring * Revert comment change commit 77bdad50a01f3a330c03b093544245d39620314b Author: Alexander Köplinger Date: Thu Jan 13 16:06:39 2022 +0100 Bump to macOS 10.14 minimum in libs and mono builds too (#63682) https://github.com/dotnet/runtime/pull/62822 bumped the minimum CMAKE_OSX_DEPLOYMENT_TARGET to 10.14, but the libs.native and mono parts of the build still used the old 10.13 value. In build-native.sh for libs.native we can actually remove the explicit setting since we're already setting it in eng/native/configurecompiler.cmake. commit 01cdd1dcaebcc9f2ab36027204142a6703a1b70b Author: Pavel Savara Date: Thu Jan 13 15:42:08 2022 +0100 [wasm] Emscripten uses `require` even when targeting ES6. This deals with the consequences. (#63718) commit a13ee96335ea4c41cfe273855611caec4c35cae8 Author: Thays Grazia Date: Thu Jan 13 09:53:43 2022 -0300 [wasm][debugger] Fixing error after receiving loaded_files = null (#63591) * Fixing #39301 * Addressing @radical comments * Sending the error toconsole in the browser. * Applying @radical suggestion. * Update src/mono/wasm/debugger/DebuggerTestSuite/BreakpointTests.cs Co-authored-by: Ankit Jain * Update src/mono/wasm/debugger/tests/debugger-test/wasm-page-without-assets.html Co-authored-by: Ankit Jain * Space -> tabs * Fix compilation error. Co-authored-by: Ankit Jain commit 64c05a3bcb4e71ee9972a3fb47eb4d3e061d3462 Author: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Thu Jan 13 12:58:37 2022 +0300 Reconfigure the field sequences for statics (#62632) * Reconfigure the field sequences for statics To make the "boxed static" and, in the future, "shared" cases identical to simple ones. It used to be that we attached the field sequence to the "inner" constant, and then added the "#FirstElem" pseudo-field for the outer offset. This was causing complexity and mistakes in the pattern matching performed by "IsFieldAddr". The solution is straightforward: always use the outer offset for the sequence. The much simpler pattern is easier and cheaper to recognize, with less room for false positives. * Drop support for mutable RVA statics They were broken on 32 bit already, and this change does not break them on 64 bit, but we'll reserve the right to do that in the future as the scenario appears to be non-existent. commit 46db4aa3c505ac36cf8d0d612d4161bb7239ed87 Author: Michal Strehovský Date: Thu Jan 13 15:28:38 2022 +0900 Add NativeAOT libraries tests annotations (#63668) Adds `ActiveIssue`/`Conditional` attributes to libraries tests so that we can get a clean run with NativeAOT. Starting with System.Collections, System.Runtime, and System.IO.FileSystem. commit f580068aa93fb3c6d5fbc7e33f6cd7d52fa86b24 Author: Dmitry Bogatykh Date: Thu Jan 13 07:00:39 2022 +0300 Fix JsonObject constuctor (#63150) * Fix JsonObject constuctor * Fix constructor this * JsonObject constructor test * Augment tests Co-authored-by: Layomi Akinrinade commit c7630198c93988fcf2cab2e6e30aadc76328e09a Author: Pavel Savara Date: Thu Jan 13 02:55:18 2022 +0100 [wasm] Load assets earlier (#63623) - allow Module.config to have assets with buffer instead of url - change sample to show how emscripten callbacks are triggered - pass config into onConfigLoaded and made it async - split asset download from copying it into memory - moved startup sequence to configure_emscripten_startup and documented it there - diagnostic_tracing as CLI parameter for tests - throttle parallel download of assets - move tests which fail on V8 to browser or nodeJS scenarios commit d5c22b0f742f4dba6d6dc46d3bec3bb6584e8b86 Author: Stephen Toub Date: Wed Jan 12 20:19:47 2022 -0500 Remove constraints from Regex source generator partial class declaration (#63637) commit 93c61341c1b2baa62f1f287c69c94ec11816b559 Author: Tarek Mahmoud Sayed Date: Wed Jan 12 17:02:47 2022 -0800 Add ActivityContext.TryParse overload (#63692) commit dc67c7022efae05891dfc1eb7b21afa001a1b99c Author: Mike McLaughlin Date: Wed Jan 12 16:00:38 2022 -0800 Fix native frame unwind in syscall on arm64 for VS4Mac crash report. (#63598) * Fix native frame unwind in syscall on arm64 for VS4Mac crash report. Add arm64 version of StepWithCompactNoEncoding for syscall leaf node wrappers that have compact encoding of 0. Fix ReadCompactEncodingRegister so it actually decrements the addr. Change StepWithCompactEncodingArm64 to match what MacOS libunwind does for framed and frameless stepping. arm64 can have frames with the same SP (but different IPs). Increment SP for this condition so createdump's unwind loop doesn't break out on the "SP not increasing" check and the frames are added to the thread frame list in the correct order. Add getting the unwind info for tail called functions like this: __ZL14PROCEndProcessPvji: 36630: f6 57 bd a9 stp x22, x21, [sp, #-48]! 36634: f4 4f 01 a9 stp x20, x19, [sp, #16] 36638: fd 7b 02 a9 stp x29, x30, [sp, #32] 3663c: fd 83 00 91 add x29, sp, #32 ... 367ac: e9 01 80 52 mov w9, #15 367b0: 7f 3e 02 71 cmp w19, #143 367b4: 20 01 88 1a csel w0, w9, w8, eq 367b8: 2e 00 00 94 bl _PROCAbort _TerminateProcess: -> 367bc: 22 00 80 52 mov w2, #1 367c0: 9c ff ff 17 b __ZL14PROCEndProcessPvji The IP (367bc) returns the (incorrect) frameless encoding with nothing on the stack (uses an incorrect LR to unwind). To fix this get the unwind info for PC -1 which points to PROCEndProcess with the correct unwind info. This matches how lldb unwinds this frame. Always address module segment to IP lookup list instead of checking the module regions. Strip pointer authentication bits on PC/LR. commit cfe5e98c03d4915b97eeee294b07eeead6e3d824 Author: Tanner Gooding Date: Wed Jan 12 16:00:04 2022 -0800 Implement the last of the approved cross platform hardware intrinsics, except shuffle (#63414) * Exposing Sum for Vector64/128/256 * Adding support for ShiftLeft, ShiftRightArithmetic, and ShiftRightLogical to Vector and Vector64/128/256 * Adding support for Load, LoadAligned, LoadAlignedNonTemporal, and LoadUnsafe to Vector64/128/256 * Adding support for Store, StoreAligned, StoreAlignedNonTemporal, and StoreUnsafe to Vector64/128/256 * Adding support for ExtractMostSignificantBits to Vector64/128/256 * Adding tests covering Vector64/128/256.Sum * Adding tests covering Vector64/128/256.ShiftLeft, ShiftRightArithmetic, and ShiftRightLogical * Moving System.Runtime.InteropServices.UnmanagedType down to System.Runtime so the `unmanaged` constraint can be used * Adding tests covering Vector64/128/256.Load, LoadAligned, LoadAlignedNonTemporal, and LoadUnsafe * Fixing a few issues in the source and tests to ensure the right paths are being taken * Adding tests covering Vector64/128/256.Store, StoreAligned, StoreAlignedNonTemporal, and StoreUnsafe * Adding tests covering Vector64/128/256.ExtractMostSignificantBits * Ensure AlignedAlloc is matched by AlignedFree * Fixing a couple test issues and the handling of Scalar.ExtractMostSignificantBit for nint/nuint * Applying formatting patch * Ensure gtNewOperNode uses TYP_INT when dealing with the shiftCount * Fixing a couple ARM64 node types * Ensure the shift intrinsics use impPopStack().val on ARM64 * Responding to PR feedback commit 8fef95be4a4fee42005a511d9b31a034e1fc3baf Author: Tomas Weinfurt Date: Wed Jan 12 13:32:51 2022 -0800 fix LocalCertificateSelectionCallback on unix (#63200) * fix LocalCertificateSelectionCallback on unix * fix linux * use Tls12 * attempt to fix build * fix macOS * fix test on windows * skip win7 * add issue reference for windows * feedback from review * fix space commit b25b96ee16aeab4890f898e8428754f1516b5e9b Author: Ulrich Weigand Date: Wed Jan 12 21:41:44 2022 +0100 [source-build][mono] Do not build Microsoft.NET.Runtime.MonoTargets.Sdk (#61607) * Does not build due to missing Microsoft.DotNet.CilStrip.Sources external dependency in source-build. * Package is not needed for source-build anyway. commit c8d3a065203d55c39b779440f69f8a4b49b210c2 Author: Maxim Lipnin Date: Wed Jan 12 23:40:14 2022 +0300 Re-enable System.Net.Security UnitTests project on Android (#63669) commit 6de7147b9266d7730b0d73ba67632b0c198cb11e Author: Marek Safar Date: Wed Jan 12 18:10:45 2022 +0100 Enable IDE0059 analyzer: Unnecessary assignment of a value (#63340) commit 635cfb3409fcce4257e35ba0cf3d385fdee3a6ad Author: dotnet-maestro[bot] <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed Jan 12 16:31:06 2022 +0100 [main] Update dependencies from dotnet/xharness (#63680) Co-authored-by: dotnet-maestro[bot] commit fdbd12dece187efb745e62572ab12e62310a18a5 Author: Egor Bogatov Date: Wed Jan 12 18:25:52 2022 +0300 JIT: Update bbFlags after replacing RET_EXPR (#63657) commit 240c23a16638d6203b300f60ea2314669c3efdf5 Author: Meri Khamoyan <96171496+mkhamoyan@users.noreply.github.com> Date: Wed Jan 12 18:01:50 2022 +0400 commit 170d58115df5f51e7baaca9bf2e898d4f2ef327d Author: Maxim Lipnin Date: Wed Jan 12 16:33:46 2022 +0300 Disable MemoryMappedFileTests failing on macOS/arm64 + coreclr due to too long path (#63438) Some MemoryMappedFileTests tests, which invoke `MemoryMappedFile.CreateNew`, fail with ` System.IO.PathTooLongException : The specified file name or path is too long, or a component of the specified path is too long. `. This pull request temporarily disables them to clean up the rolling build: - MemoryMappedFileTests_CreateNew - MemoryMappedViewAccessorTests - MemoryMappedViewStreamTests - AnonymousMemoryMappedViewStreamConformanceTests. See also https://github.com/dotnet/runtime/issues/63240 commit e731cce92151cd9afa7ca13e9af353edd45e4598 Author: Aaron Robinson Date: Wed Jan 12 08:33:22 2022 -0500 Fix a bug in the detection of Windows Nano from native test clients. (#63656) * Fix a bug in the detection of Windows Nano from native test clients. commit d4f06a9c524819dfd1345745a17b3cc6e060ba8b Author: Adeel Mujahid <3840695+am11@users.noreply.github.com> Date: Wed Jan 12 15:05:32 2022 +0200 Reuse ARRAY_SIZE from minipal (#63661) commit 74103c2a12232c19622d62f74419c9d78727d93e Author: Stephen Toub Date: Wed Jan 12 07:11:07 2022 -0500 Fix index in XmlQueryRuntime.MatchesXmlType (#63366) commit ecc20c5f6bd542588f7e93571f091f88e37f6482 Author: dotnet-maestro[bot] <42748379+dotnet-maestro[bot]@users.noreply.github.com> Date: Wed Jan 12 11:52:16 2022 +0100 [main] Update dependencies from 7 repositories (#63392) Co-authored-by: dotnet-maestro[bot] commit c81ad33fd41a57ae2d3945d3852663c391e91a16 Author: Jakob Botsch Nielsen Date: Wed Jan 12 11:20:33 2022 +0100 Fix ArgIterator::GetArgLoc by-ref check for HFAs/HVAs (#63587) This check was not taking into account that HFAs and HVAs are not passed by ref (except for in varargs), even when they are larger than 16 bytes. However we do not hit this bug in reflection invocation as we do not use the size from ArgLocDesc but rather end up calling MethodTable::GetNumInstanceFieldBytes to get the size. Also fix the hashing used in the ABIStress test. The hashing was using HashCode.Add with T being our custom types that have automatically implemented GetHashCode(). Those implementations only base the hash code on the first field in certain cases, which was hiding this particular issue. Change the hashing to use HashCode.AddBytes instead. commit b9d8d846e73588b400ebf7f21b6bbd577ff0765e Author: Marek Fišera Date: Wed Jan 12 09:39:53 2022 +0100 Make test System.Data.Tests.AppDomainsAndFormatInfo.Bug55978 more robust (#63028) Add explicit 1 minute difference to all datetimes in rows. commit 4e2102b73b4ab673242fcb480937130b12d04d1b Author: Andrii Kurdiumov Date: Wed Jan 12 13:52:01 2022 +0600 Add dependency analysis documentation from CoreRT (#63665) commit ef7ff071099d185a5f66b55966866fcc964e287c Author: Jeremy Koritzinsky Date: Tue Jan 11 21:25:46 2022 -0800 Capture and record output from tests from Console.Out into the test results (#63606) * Capture and record output from tests from Console.Out into the test results. * Simplify construction. * Fix nullability * Fix constructor visibility commit ad1b5b88f8a181a78a033e3b2d7a8c9a626f1c51 Author: Zoltan Varga Date: Tue Jan 11 23:08:26 2022 -0500 [mono] Convert RuntimeAssembly icalls to use QCallAssembly/ObjectHand… (#63558) * [mono] Convert RuntimeAssembly icalls to use QCallAssembly/ObjectHandleOnStack. * Call the ResourceResolve callback from managed code. * Merge some accessor icalls into a GetInfo () icall. * [mono] Remove some redundant error_init () calls, the caller should initialize 'error'. * Fix a failure. * Fix some nullability issues. commit cbfdf3f0d446b5e36aa2d6f495098c3599f958f8 Author: Jan Kotas Date: Tue Jan 11 18:43:24 2022 -0800 Use open StrongNameKeyId for ILVerification.dll (#63583) commit cfe08dbd81315d3b50f308577822de000f8acb7d Author: Nathan Ricci Date: Tue Jan 11 20:53:56 2022 -0500 [Perf] Enable LLVM on perf runs (#63504) Add MonoEnableLLVM to build for llvm perf jobs commit 8edc17d756089941ba897edecb187ac716e3ef63 Author: Michal Strehovský Date: Wed Jan 12 09:53:16 2022 +0900 Fix address mode for `IconHandle + Icon` (#63608) For a NativeAOT change that I'm working on, I'm seeing inefficient address mode getting generated for trees in the shape of `IconHandle + Icon`. The logic I'm touching is swapping this to `Icon + IconHandle` and that makes us miss the if check on the following line because `!op2->IsIntCnsFitsInI32`. That makes us miss generating this tree as `[reg + offset]`. Submitting this as a separate pull request because my actual change will likely need a JitInterface GUID update. This should be no diff for non-AOT scenarios. commit dadc7ce7ab3acdf99cd1a324cad7720c1e16f3c5 Author: Tomáš Rylek Date: Wed Jan 12 01:30:07 2022 +0100 Unify JIT/Methodical/eh/common and JIT/jit64/eh/common (#63597) I have moved the support library under JIT/common similar to treatment of the localloc/common library I'm moving in https://github.com/dotnet/runtime/pull/63510 I have slightly modified the implementation to support merged tests (let each test case use its own StringRecorder). Thanks Tomas commit 4f89b79d842ece91d04a47d5483c7b34abd2e954 Author: Tanner Gooding Date: Tue Jan 11 16:24:01 2022 -0800 Ensure the JIT view of InstructionSets is correct in the face of JitConfig switches (#62420) * Adding a regression test for dotnet/runtime#60035 * Add the correct "ISA implications" for Vector64/128 * Moving the `COMPlus_Enable*` HWIntrinsic ISA switches to the VM * Ensure Set64BitInstructionSetVariants is called before EnsureValidInstructionSetSupport * Ensure opts.compSupportsISA isn't overwritten to 0 * Ensure that Lzcnt is dependent on X86Base and AvxVnni is dependent on Avx2 * Adding x64, x86, and Arm64 specific views to help with debugging CorInfoInstructionSet * Keep the JIT in charge of "artificial" ISAs * Update JitBlue/Runtime_34587 to also validate the xplat SIMD types commit 81fcfb6a565857ed1da6c98b3a95976e16d66ccf Author: Michal Strehovský Date: Wed Jan 12 09:22:33 2022 +0900 Delete `CEEInfo::IsCompilingForNGen` (#63613) And related dead code. Contributes to #54129. commit 4e22ade9e1658d86d6de068cf0f079f3605b874b Author: dotnet bot Date: Tue Jan 11 15:53:02 2022 -0800 Localized file check-in by OneLocBuild Task: Build definition ID 679: Build ID 1547845 (#62663) commit 032129cb2730a1609a8377d07cbcf891a7c8c5bb Author: SingleAccretion <62474226+SingleAccretion@users.noreply.github.com> Date: Wed Jan 12 01:57:38 2022 +0300 Delete some null checks (#63024) It recently came to light that we can delete some nullchecks, using knowledge that some VN functions are never null and that "object.GetType" throws on null "this". This very simple change does just that. commit 74dc242fb93d4e500e9f0561fb49258adc9142d6 Author: Christopher Yeleighton Date: Tue Jan 11 23:39:42 2022 +0100 HostBuilder.Build doc: mention lifetime (#63123) * HostBuilder.Build doc: mention lifetime Mention that the host application lifetime service will be added *in addition* to the services configured to be run. * ExecuteAsync: See Worker Services in .NET * StartAsync: mention IHostApplicationLifetime 1. The application will run until interrupted or until `HostApplicationLifetime.StopApplication()` is called. 2. Document how to configure `Services`. * mv mention StopApplication to StartAsync Co-authored-by: Eric Erhardt * Build doc: mv services to remarks * typo fix * Starts only hosted services Co-authored-by: Eric Erhardt * See see * IHost.Services are RO Co-authored-by: Genevieve Warren <24882762+gewarren@users.noreply.github.com> * Use indicative Co-authored-by: Genevieve Warren <24882762+gewarren@users.noreply.github.com> * Oxford commas Co-authored-by: Genevieve Warren <24882762+gewarren@users.noreply.github.com> * see in remarks * typo fix Co-authored-by: Eric Erhardt Co-authored-by: Eric Erhardt Co-authored-by: Genevieve Warren <24882762+gewarren@users.noreply.github.com> commit ff74f55422c512296d6ffc70e82e0de7219f5ce8 Author: Maksym Koshovyi Date: Wed Jan 12 00:21:39 2022 +0200 [Group 4] Enable nullable annotations for `Microsoft.Extensions.Configuration.FileExtensions` (#57434) * Annotate * Update FileConfigurationProvider.cs * DisableImplicitAssemblyReferences * Use compaund assigment * DisallowNull * Suppress warning * GetFileProvider non nullable return commit 64f48857a6193a81faa32825cc78d7340a3ebd46 Author: Josip Medved Date: Tue Jan 11 10:41:22 2022 -0800 Added DrawRectangle overload accepting RectangleF (#62385) * Added DrawRectangle overload accepting RectangleF * Added DrawRectangle overload to reference assembly file * Added FillPie overload accepting RectangleF * Added test cases for DrawRectangle accepting RectangleF * Added FillPie argument test cases * Added XML parameters for newly added FillPie and DrawRectangle * Moving DrawRectangle and FillPie with RectangleF to netcoreapp * Moving DrawRectangle and FillPie RectangleF tests to netcoreapp * Only testing RectangleF overloads in GraphicsTests.Core.cs; other overloads stay as they are. * FillPie tests that were newly added as part of issue #62385 are split in the same manner. * Removing RectangleF overload from mono tests DrawRectangle with RectangleF overload is new and not compiled into mono. commit bd9f1c40d942eb0d62d59cb4592408fde2f5939b Author: Badre BSAILA <54767641+pedrobsaila@users.noreply.github.com> Date: Tue Jan 11 18:54:05 2022 +0100 add capture group name in comment (#63255) * add capture group name in comment * Some fixes for using capture group name - Pass correct arguments into GroupNameFromNumber from RegexCode - Use capture group name for backreferences and backreference conditionals as well - Only render the group number if there is no name - Consistenly use the "capture group" suffix - Clean up GroupNameFromNumber to avoid duplicate string.Empty fallback cases - Fixes rendering of balancing groups Co-authored-by: Stephen Toub commit b8a8c7a4c94c02d18c0224bd94108ec5887d77f2 Author: Anthony Meehan Date: Wed Jan 12 00:58:41 2022 +0800 LoggingHttpMessageHandler should log unescaped URL in log message (#62894) (#63012) Modifies the logging in LoggingHttpMessageHandler and LoggingScopeHttpMessageHandler to log the AbsoluteUri so the unescaped Uri is logged commit cf91716becf05b255ab9e201d3ff32cfb43230e0 Author: Manish Godse <61718172+mangod9@users.noreply.github.com> Date: Tue Jan 11 08:52:53 2022 -0800 Enable GC regions by default (#59283) * Enable regions by default * ApproxTotalBytesInUse * one line fix * initialize CurrentThread before initializing GC Without this fix enabling Regions is failing AOT tests on checked build. * use GetCurrentThreadIfAvailable within GCToEEInterface::GetThread This is similar to GCToEEInterface::GetThread implementation in the runtime. Co-authored-by: Maoni Stephens commit b389de59bafd7ee8d20ef6d97cb88b3712b99dcd Author: Simon Rozsival Date: Tue Jan 11 17:43:53 2022 +0100 Prevent potential out of bounds write on Android SslStream This PR makes sure we never write more bytes into the destination buffer than we allocated. The way we currently use this function always is safe because we ensure that the destination buffer is large enough beforehand but it could be a problem if we reused this function somewhere else in the future. If there's too much data in the input buffer to fit into the destination buffer we read only as much as we can and we leave the rest of the data intact for future reads. commit 59b55a213f814b3cf50bbc177b2a8fdc1294b932 Author: Thays Grazia Date: Tue Jan 11 12:31:15 2022 -0300 [mono][debugger] Fix step on ios when using interpreter (#63515) * fix step on ios when using interpreter * Apply review suggestions. * Removing unrelated change commit 1297ac80688231d8cc07de475823b58c3e18d7ee Author: Thays Grazia Date: Tue Jan 11 12:31:02 2022 -0300 Should read this byte only in earlier versions. (#63503) commit 8c47d32ff995de1ee38b55af06e81c64a4cbad69 Author: Simon Rozsival Date: Tue Jan 11 15:18:34 2022 +0100 [Android] Fix accessing network interfaces information (#62780) * Re-enable tests * Dynamically load getifaddrs if necessary * Prevent redeclaration of the ifaddrs struct * Fix typo * Do not close the dynamic library * Enable the fixed functional tests in CI * Reduce code duplication for obtaining libc file name * Simplify usage of the function pointers * Move typedefs * Rename the _ensure_ function * Remove fptr typedefs * Update comment * Add missing include * Update comment * Remove unnecessary comment * Move static variable * Remove unnecessary change * Move LIBC_FILENAME to the utilities header * Avoid error if constant is undefined * Conditionally include ifaddrs * Try to fix cmake_symbol_exists issue for browser * Minor tweaks * Try different way of detecting getifaddrs * Use the hack only for Android builds * Revert "Move LIBC_FILENAME to the utilities header" This reverts commit 4e6768718a09002680d55a13ba2693eded03d749. * Revert "Reduce code duplication for obtaining libc file name" This reverts commit aca15d1c169196ce2710a328ebb2210ccbefd283. * Simplify opening libc * Update code style * Fix race condition * Prevent race condition * Switch locking implementation for a lock-free implementation * Enable unit test for Android * Try using weak symbols * Fix function name * Revert "Fix function name" This reverts commit f927aaec9f439e70378806cd7b6947bdc9f216fd. * Revert "Try using weak symbols" This reverts commit 46d3edeed0a7f23cdcc1e4b7bbcb167b04835097. * Refactor code to use pthread_once commit 61d5a4a3b836486acc24643da24104f627cbdd30 Author: Ilona Tomkowicz <32700855+ilonatommy@users.noreply.github.com> Date: Tue Jan 11 14:54:14 2022 +0100 [wasm][debugger] Add getter properties unfolding in structures. (#63574) * Add getter properties unfolding in structures. * Changed to TryParse in case of reaching beyond the array while doing parts[4]. * Applied @radical's suggestion about array safety. * Applied @radical's ElementType check simplifiaction. commit 4646f13a8ec8a79657631619baf21547079063f1 Author: Peter Sollich Date: Tue Jan 11 14:41:07 2022 +0100 Fix case where we fail to commit the start of a new region, but don't clean up the entry in the region allocator. (#63577) The region itself though looks like it is on a region free list (heap_segment_allocated is null), so we crash when we try to remove it from its free list, as its containing_free_list is null. Fix is to delete the region in the region allocator's map, i.e. cause it to be marked as free. commit fe8422cdff450941bc3ba4b120576e8822459df4 Author: Pavel Ivanov Date: Tue Jan 11 17:39:59 2022 +0500 Remove leading and trailing white-spaces from section name (#63549) * Reproduce the issue with spaces around the section name * Remove leading and trailing whitespaces from section name commit 1ba27341169ebe6117bf112bd8976dc960327eec Author: Aaron Robinson Date: Tue Jan 11 07:39:27 2022 -0500 Update CoreShim.cpp (#63600) Correct calling convention for corerun export using in CoreShim. --- .config/dotnet-tools.json | 2 +- .github/fabricbot.json | 1209 ++++- Directory.Build.props | 1 + docs/coding-guidelines/project-guidelines.md | 2 +- docs/design/features/standalone-gc-loading.md | 2 +- .../DllImportGenerator/StructMarshalling.md | 73 +- docs/pr-builds.md | 94 + docs/pr-guide.md | 63 +- docs/project/glossary.md | 2 +- .../coreclr/debugging-aot-compilers.md | 4 + .../debuging-compiler-dependency-analysis.md | 47 + eng/CodeAnalysis.src.globalconfig | 2 +- eng/Version.Details.xml | 248 +- eng/Versions.props | 114 +- eng/build.sh | 6 +- eng/common/cross/toolchain.cmake | 11 +- eng/common/generate-graph-files.ps1 | 86 - eng/common/post-build/publish-using-darc.ps1 | 28 +- eng/common/sdl/configure-sdl-tool.ps1 | 9 +- eng/common/sdl/execute-all-sdl-tools.ps1 | 4 +- .../templates/job/generate-graph-files.yml | 48 - eng/common/templates/jobs/codeql-build.yml | 31 + eng/common/templates/jobs/jobs.yml | 10 - .../channels/generic-internal-channel.yml | 190 - .../channels/generic-public-channel.yml | 192 - .../templates/post-build/post-build.yml | 538 +- eng/common/templates/steps/execute-codeql.yml | 32 + eng/common/templates/steps/source-build.yml | 2 +- eng/liveBuilds.targets | 3 + eng/native/build-commons.sh | 6 +- eng/native/configurecompiler.cmake | 10 + eng/native/configureplatform.cmake | 9 + eng/native/functions.cmake | 71 +- eng/native/init-os-and-arch.sh | 4 + eng/native/tryrun.cmake | 6 +- eng/packaging.targets | 6 +- eng/pipelines/common/global-build-job.yml | 9 +- eng/pipelines/common/platform-matrix.yml | 4 +- .../templates/runtimes/run-test-job.yml | 5 +- eng/pipelines/common/variables.yml | 14 +- eng/pipelines/common/xplat-setup.yml | 19 +- eng/pipelines/coreclr/perf_slow.yml | 3 +- eng/pipelines/coreclr/superpmi-collect.yml | 18 +- .../templates/run-superpmi-collect-job.yml | 6 +- .../templates/superpmi-collect-job.yml | 4 +- .../libraries/helix-queues-setup.yml | 66 +- eng/pipelines/libraries/outerloop-mono.yml | 8 +- eng/pipelines/libraries/outerloop.yml | 18 +- eng/pipelines/libraries/variables.yml | 2 +- eng/pipelines/runtime-community.yml | 4 +- ...manual.yml => runtime-extra-platforms.yml} | 658 +-- eng/pipelines/runtime-staging.yml | 406 +- eng/pipelines/runtime.yml | 210 +- eng/pipelines/runtimelab.yml | 4 +- eng/run-test.sh | 2 +- eng/targetingpacks.targets | 6 +- eng/testing/RunnerTemplate.sh | 3 +- eng/testing/default.rd.xml | 81 + eng/testing/tests.props | 1 + eng/testing/tests.singlefile.targets | 26 +- global.json | 10 +- .../Microsoft.ILVerification.pkgproj | 2 +- src/coreclr/CMakeLists.txt | 1 - .../src/System/Math.CoreCLR.cs | 8 - .../System/Reflection/Emit/ModuleBuilder.cs | 4 +- .../src/System/Reflection/Emit/TypeBuilder.cs | 2 +- .../src/System/Reflection/RuntimeModule.cs | 2 +- .../src/System/RuntimeType.CoreCLR.cs | 4 +- .../src/System/StubHelpers.cs | 4 +- src/coreclr/ToolBox/CMakeLists.txt | 2 - src/coreclr/binder/assemblybindercommon.cpp | 2 +- src/coreclr/binder/bindertracing.cpp | 4 +- src/coreclr/binder/inc/bindertracing.h | 2 +- src/coreclr/build-runtime.sh | 2 + .../classlibnative/float/floatdouble.cpp | 9 - .../classlibnative/float/floatsingle.cpp | 21 - src/coreclr/classlibnative/inc/floatdouble.h | 1 - src/coreclr/classlibnative/inc/floatsingle.h | 1 - src/coreclr/clrdefinitions.cmake | 13 +- src/coreclr/debug/createdump/crashinfomac.cpp | 6 +- src/coreclr/debug/createdump/stackframe.h | 9 +- src/coreclr/debug/createdump/threadinfo.cpp | 10 + src/coreclr/debug/daccess/daccess.cpp | 8 +- src/coreclr/dlls/mscordac/CMakeLists.txt | 2 +- .../dlls/mscordac/mscordac_unixexports.src | 3 - src/coreclr/gc/gc.cpp | 198 +- src/coreclr/gc/gcinterface.dac.h | 2 +- src/coreclr/gc/gcpriv.h | 14 +- src/coreclr/gc/unix/gcenv.unix.cpp | 6 +- src/coreclr/hosts/corerun/dotenv.cpp | 5 +- src/coreclr/hosts/coreshim/CoreShim.cpp | 2 +- src/coreclr/ildasm/dasm.cpp | 10 +- src/coreclr/ildasm/dasm_formattype.cpp | 4 +- src/coreclr/inc/bbsweep.h | 4 - src/coreclr/inc/clrconfigvalues.h | 41 +- src/coreclr/inc/corhlpr.h | 5 - src/coreclr/inc/corinfo.h | 6 - src/coreclr/inc/corinfoinstructionset.h | 16 + src/coreclr/inc/dacvars.h | 2 +- src/coreclr/inc/formattype.cpp | 44 +- src/coreclr/inc/holder.h | 9 +- src/coreclr/inc/icorjitinfoimpl_generated.h | 4 - src/coreclr/inc/jiteeversionguid.h | 10 +- src/coreclr/inc/switches.h | 2 +- src/coreclr/inc/vptr_list.h | 3 - src/coreclr/jit/ICorJitInfo_API_names.h | 1 - src/coreclr/jit/ICorJitInfo_API_wrapper.hpp | 9 - src/coreclr/jit/assertionprop.cpp | 16 +- src/coreclr/jit/block.h | 11 + src/coreclr/jit/codegenarm64.cpp | 5 +- src/coreclr/jit/codegenarmarch.cpp | 57 +- src/coreclr/jit/codegencommon.cpp | 21 +- src/coreclr/jit/codegenlinear.cpp | 2 +- src/coreclr/jit/compiler.cpp | 190 +- src/coreclr/jit/compiler.h | 38 +- src/coreclr/jit/compiler.hpp | 80 +- src/coreclr/jit/ee_il_dll.cpp | 15 +- src/coreclr/jit/emit.h | 9 + src/coreclr/jit/emitarm64.cpp | 42 +- src/coreclr/jit/emitxarch.cpp | 13 + src/coreclr/jit/fgbasic.cpp | 50 +- src/coreclr/jit/fgdiagnostic.cpp | 6 +- src/coreclr/jit/fginline.cpp | 11 +- src/coreclr/jit/fgopt.cpp | 19 +- src/coreclr/jit/fgprofile.cpp | 23 +- src/coreclr/jit/fgstmt.cpp | 2 +- src/coreclr/jit/flowgraph.cpp | 28 +- src/coreclr/jit/gentree.cpp | 569 +- src/coreclr/jit/gentree.h | 201 +- src/coreclr/jit/gtlist.h | 54 +- src/coreclr/jit/hwintrinsic.cpp | 4 +- src/coreclr/jit/hwintrinsicarm64.cpp | 470 +- src/coreclr/jit/hwintrinsiccodegenarm64.cpp | 23 + src/coreclr/jit/hwintrinsiclistarm64.h | 36 +- src/coreclr/jit/hwintrinsiclistxarch.h | 30 +- src/coreclr/jit/hwintrinsicxarch.cpp | 427 ++ src/coreclr/jit/importer.cpp | 250 +- src/coreclr/jit/inline.def | 2 + src/coreclr/jit/inlinepolicy.cpp | 22 +- src/coreclr/jit/inlinepolicy.h | 4 + src/coreclr/jit/instrsarm64.h | 8 +- src/coreclr/jit/jit.h | 3 +- src/coreclr/jit/jitconfigvalues.h | 64 +- src/coreclr/jit/lclvars.cpp | 4 +- src/coreclr/jit/lir.cpp | 2 +- src/coreclr/jit/loopcloning.cpp | 6 +- src/coreclr/jit/lower.cpp | 4 +- src/coreclr/jit/lowerarmarch.cpp | 77 +- src/coreclr/jit/lsra.cpp | 12 +- src/coreclr/jit/lsra.h | 2 +- src/coreclr/jit/lsraarm64.cpp | 75 +- src/coreclr/jit/lsraarmarch.cpp | 52 +- src/coreclr/jit/lsrabuild.cpp | 19 +- src/coreclr/jit/morph.cpp | 147 +- src/coreclr/jit/namedintrinsiclist.h | 1 + src/coreclr/jit/optcse.cpp | 4 +- src/coreclr/jit/optimizer.cpp | 61 +- src/coreclr/jit/rangecheck.cpp | 2 +- src/coreclr/jit/rationalize.cpp | 9 +- src/coreclr/jit/redundantbranchopts.cpp | 2 +- src/coreclr/jit/simdashwintrinsic.cpp | 140 +- src/coreclr/jit/simdashwintrinsiclistarm64.h | 3 + src/coreclr/jit/simdashwintrinsiclistxarch.h | 6 + src/coreclr/jit/targetarm64.h | 6 +- src/coreclr/jit/valuenum.cpp | 315 +- src/coreclr/jit/valuenumfuncs.h | 9 +- src/coreclr/md/enc/metamodelrw.cpp | 4 +- .../Microsoft.NETCore.Native.Publish.targets | 2 + .../Microsoft.NETCore.Native.targets | 27 +- src/coreclr/nativeaot/Runtime/CommonMacros.h | 7 +- src/coreclr/nativeaot/Runtime/EHHelpers.cpp | 2 +- src/coreclr/nativeaot/Runtime/MathHelpers.cpp | 4 +- src/coreclr/nativeaot/Runtime/RhConfig.cpp | 2 +- src/coreclr/nativeaot/Runtime/gcrhenv.cpp | 2 +- src/coreclr/nativeaot/Runtime/rhassert.cpp | 2 +- src/coreclr/nativeaot/Runtime/stressLog.cpp | 4 +- src/coreclr/nativeaot/Runtime/thread.cpp | 4 +- .../nativeaot/Runtime/unix/PalRedhawkUnix.cpp | 2 +- .../src/System/Math.CoreRT.cs | 12 - .../InteropServices/ComWrappers.CoreRT.cs | 2 - .../src/System/Runtime/RuntimeImports.cs | 12 - .../System/Threading/Thread.CoreRT.Windows.cs | 3 +- .../RuntimeInteropData.CoreRT.cs | 3 +- .../src/System/ActivatorImplementation.cs | 3 +- ...imeAssembly.GetTypeCore.CaseInsensitive.cs | 6 +- .../Runtime/BindingFlagSupport/Shared.cs | 9 +- .../RuntimeCustomAttributeData.cs | 3 +- .../Runtime/General/NamespaceChain.cs | 2 +- .../ReflectionCoreCallbacksImplementation.cs | 1 - .../RuntimePlainConstructorInfo.cs | 3 +- .../RuntimeFatMethodParameterInfo.cs | 2 +- .../TypeInfos/RuntimeTypeInfo.InvokeMember.cs | 3 +- ...EnvironmentImplementation.MappingTables.cs | 11 +- .../DiagnosticMappingTables.cs | 6 +- .../MissingMetadataExceptionCreator.cs | 2 +- .../StackTraceMetadata/MethodNameFormatter.cs | 14 +- ...ConverterThunk.CallConversionParameters.cs | 4 +- .../Runtime/TypeLoader/CallConverterThunk.cs | 9 +- .../Runtime/TypeLoader/CallingConventions.cs | 3 +- .../Runtime/TypeLoader/EETypeCreator.cs | 2 +- .../Internal/Runtime/TypeLoader/ModuleList.cs | 3 +- .../TypeLoader/NativeLayoutFieldAlgorithm.cs | 3 +- .../TypeLoader/NativeLayoutInfoLoadContext.cs | 6 +- .../Runtime/TypeLoader/TemplateLocator.cs | 3 +- .../Runtime/TypeLoader/TypeBuilder.cs | 8 +- .../Runtime/TypeLoader/TypeBuilderState.cs | 2 +- ...ronment.ConstructedGenericMethodsLookup.cs | 2 - .../TypeLoaderEnvironment.FieldAccess.cs | 4 +- .../TypeLoaderEnvironment.Metadata.cs | 5 +- ...derEnvironment.MetadataSignatureParsing.cs | 2 +- .../TypeLoaderEnvironment.NamedTypeLookup.cs | 3 +- .../TypeLoaderEnvironment.SignatureParsing.cs | 24 +- .../TypeLoader/TypeLoaderEnvironment.cs | 2 +- .../TypeSystem/RuntimeNoMetadataType.cs | 9 +- src/coreclr/pal/inc/pal.h | 30 +- src/coreclr/pal/inc/palprivate.h | 2 - src/coreclr/pal/inc/rt/sal.h | 4 + src/coreclr/pal/src/CMakeLists.txt | 4 - src/coreclr/pal/src/cruntime/path.cpp | 113 - src/coreclr/pal/src/cruntime/wchar.cpp | 49 - src/coreclr/pal/src/cruntime/wchartls.cpp | 125 - .../pal/src/exception/remote-unwind.cpp | 129 +- src/coreclr/pal/src/exception/seh-unwind.cpp | 2 +- src/coreclr/pal/src/exception/signal.cpp | 7 +- src/coreclr/pal/src/include/pal/modulename.h | 35 - src/coreclr/pal/src/include/pal/palinternal.h | 2 - src/coreclr/pal/src/loader/module.cpp | 12 +- src/coreclr/pal/src/loader/modulename.cpp | 68 - src/coreclr/pal/src/memory/local.cpp | 93 - src/coreclr/pal/src/misc/fmtmessage.cpp | 14 +- src/coreclr/pal/src/thread/process.cpp | 2 +- src/coreclr/pal/tests/palsuite/CMakeLists.txt | 4 - .../palsuite/c_runtime/wcstok/test1/test1.cpp | 113 - .../pal/tests/palsuite/compilableTests.txt | 4 - .../LocalAlloc/test1/LocalAlloc.cpp | 48 - .../LocalFree/test1/LocalFree.cpp | 48 - .../LocalFree/test2/LocalFree.cpp | 38 - .../LoadLibraryA/test6/loadlibrarya.cpp | 46 +- .../LoadLibraryA/test8/loadlibrarya.cpp | 57 +- .../FormatMessageW/test6/test.cpp | 20 +- .../pal/tests/palsuite/paltestlist.txt | 4 - src/coreclr/pal/tests/palsuite/runpaltests.sh | 23 +- src/coreclr/runtime-prereqs.proj | 2 +- src/coreclr/scripts/jitutil.py | 6 +- src/coreclr/scripts/superpmi.md | 2 +- src/coreclr/scripts/superpmi_benchmarks.py | 5 +- src/coreclr/scripts/superpmi_collect_setup.py | 31 +- src/coreclr/tools/CMakeLists.txt | 3 + .../NativeFormat/Generator/ReaderGen.cs | 1 + .../NativeFormat/NativeFormatReaderGen.cs | 1 + .../NativeFormat/NativeFormatReader.cs | 2 +- .../tools/Common/JitInterface/CorInfoBase.cs | 65 +- .../tools/Common/JitInterface/CorInfoImpl.cs | 2 - .../JitInterface/CorInfoInstructionSet.cs | 343 +- .../ThunkGenerator/InstructionSetDesc.txt | 7 +- .../ThunkGenerator/InstructionSetGenerator.cs | 64 +- .../ThunkGenerator/ThunkInput.txt | 1 - .../JitInterface/ThunkGenerator/gen.bat | 2 +- .../Common/JitInterface/ThunkGenerator/gen.sh | 2 +- .../Canon/TypeSystemContext.Canon.cs | 3 +- .../Common/ConstructedTypeRewritingHelpers.cs | 2 +- .../TypeSystem/Common/TypeSystemHelpers.cs | 4 +- .../Utilities/LockFreeReaderHashtable.cs | 6 +- .../LockFreeReaderHashtableOfPointers.cs | 6 +- .../Stubs/DelegateMarshallingMethodThunk.cs | 8 + .../TypeSystem/Interop/IL/MarshalHelpers.cs | 2 +- .../Common/TypeSystem/Interop/InteropTypes.cs | 10 + .../ILVerification/ILVerification.csproj | 1 + .../{ToolBox => tools}/SOS/CMakeLists.txt | 0 .../{ToolBox => tools}/SOS/DIALib/DIALib.il | 0 .../SOS/DIALib/DIALib.ilproj | 0 .../SOS/DacTableGen/DacTableGen.csproj | 0 .../SOS/DacTableGen/MapSymbolProvider.cs | 0 .../SOS/DacTableGen/cvconst.cs | 0 .../SOS/DacTableGen/diautil.cs | 0 .../SOS/DacTableGen/main.cs | 0 .../SOS/Directory.Build.props | 0 .../{ToolBox => tools}/SOS/SOS_README.md | 0 .../Dataflow/ReflectionMethodBodyScanner.cs | 4 +- .../GenericCompositionNode.cs | 1 + .../Compiler/FeatureSettings.cs | 52 + .../Compiler/FeatureSwitchManager.cs | 2 +- .../ManifestResourceBlockingPolicy.cs | 2 +- .../Compiler/ProcessLinkerXmlBase.cs | 661 ++- .../Compiler/ProcessXmlBase.cs | 404 ++ .../ReferenceSource/BodySubstitutionParser.cs | 174 + .../ReferenceSource/DescriptorMarker.cs | 292 ++ .../ReferenceSource/FeatureSettings.cs | 50 + .../ReferenceSource/LinkAttributesParser.cs | 578 ++ .../ReferenceSource/ProcessLinkerXmlBase.cs | 662 +++ .../Compiler/ReferenceSource/README.md | 1 + .../Compiler/UsageBasedInteropStubManager.cs | 39 +- .../Compiler/UsageBasedMetadataManager.cs | 2 +- .../ILCompiler.Compiler.csproj | 2 + .../ReadyToRun/ArgIterator.cs | 5 +- .../Compiler/ReadyToRunHashCode.cs | 4 +- src/coreclr/tools/aot/ILCompiler/Program.cs | 2 +- .../tools/aot/ILCompiler/repro/repro.csproj | 1 + .../tools/aot/ILLink.Shared/DiagnosticId.cs | 3 +- .../aot/ILLink.Shared/SharedStrings.resx | 3 + .../tools/aot/jitinterface/jitinterface.h | 10 - .../{ToolBox => tools}/superpmi/.clang-format | 0 .../superpmi/CMakeLists.txt | 0 .../superpmi/mcs/CMakeLists.txt | 0 .../superpmi/mcs/commandline.cpp | 0 .../superpmi/mcs/commandline.h | 0 .../{ToolBox => tools}/superpmi/mcs/mcs.cpp | 0 .../{ToolBox => tools}/superpmi/mcs/mcs.h | 0 .../superpmi/mcs/removedup.cpp | 0 .../superpmi/mcs/removedup.h | 0 .../superpmi/mcs/verbasmdump.cpp | 0 .../superpmi/mcs/verbasmdump.h | 0 .../superpmi/mcs/verbconcat.cpp | 0 .../superpmi/mcs/verbconcat.h | 0 .../superpmi/mcs/verbdump.cpp | 0 .../superpmi/mcs/verbdump.h | 0 .../superpmi/mcs/verbdumpmap.cpp | 0 .../superpmi/mcs/verbdumpmap.h | 0 .../superpmi/mcs/verbdumptoc.cpp | 0 .../superpmi/mcs/verbdumptoc.h | 0 .../superpmi/mcs/verbfracture.cpp | 0 .../superpmi/mcs/verbfracture.h | 0 .../superpmi/mcs/verbildump.cpp | 0 .../superpmi/mcs/verbildump.h | 0 .../superpmi/mcs/verbinteg.cpp | 0 .../superpmi/mcs/verbinteg.h | 0 .../superpmi/mcs/verbjitflags.cpp | 0 .../superpmi/mcs/verbjitflags.h | 0 .../superpmi/mcs/verbmerge.cpp | 0 .../superpmi/mcs/verbmerge.h | 0 .../superpmi/mcs/verbprintjiteeversion.cpp | 0 .../superpmi/mcs/verbprintjiteeversion.h | 0 .../superpmi/mcs/verbremovedup.cpp | 0 .../superpmi/mcs/verbremovedup.h | 0 .../superpmi/mcs/verbstat.cpp | 0 .../superpmi/mcs/verbstat.h | 0 .../superpmi/mcs/verbstrip.cpp | 0 .../superpmi/mcs/verbstrip.h | 0 .../superpmi/mcs/verbtoc.cpp | 0 .../{ToolBox => tools}/superpmi/mcs/verbtoc.h | 0 .../{ToolBox => tools}/superpmi/readme.md | 2 +- .../superpmi/superpmi-shared/agnostic.h | 0 .../superpmi/superpmi-shared/asmdumper.cpp | 0 .../superpmi/superpmi-shared/asmdumper.h | 0 .../superpmi/superpmi-shared/callutils.cpp | 0 .../superpmi/superpmi-shared/callutils.h | 0 .../superpmi-shared/compileresult.cpp | 0 .../superpmi/superpmi-shared/compileresult.h | 0 .../superpmi/superpmi-shared/crlwmlist.h | 0 .../superpmi-shared/errorhandling.cpp | 0 .../superpmi/superpmi-shared/errorhandling.h | 0 .../superpmi/superpmi-shared/hash.cpp | 0 .../superpmi/superpmi-shared/hash.h | 0 .../superpmi-shared/icorjitcompilerimpl.h | 0 .../superpmi-shared/icorjithostimpl.h | 0 .../superpmi-shared/icorjitinfoimpl.h | 0 .../superpmi/superpmi-shared/lightweightmap.h | 0 .../superpmi/superpmi-shared/logging.cpp | 0 .../superpmi/superpmi-shared/logging.h | 0 .../superpmi/superpmi-shared/lwmlist.h | 0 .../superpmi/superpmi-shared/mclist.cpp | 0 .../superpmi/superpmi-shared/mclist.h | 0 .../superpmi-shared/methodcontext.cpp | 0 .../superpmi/superpmi-shared/methodcontext.h | 0 .../superpmi-shared/methodcontextiterator.cpp | 0 .../superpmi-shared/methodcontextiterator.h | 0 .../superpmi-shared/methodcontextreader.cpp | 0 .../superpmi-shared/methodcontextreader.h | 0 .../superpmi/superpmi-shared/runtimedetails.h | 0 .../superpmi/superpmi-shared/simpletimer.cpp | 0 .../superpmi/superpmi-shared/simpletimer.h | 0 .../superpmi-shared/spmidumphelper.cpp | 0 .../superpmi/superpmi-shared/spmidumphelper.h | 0 .../superpmi-shared/spmirecordhelper.h | 0 .../superpmi/superpmi-shared/spmiutil.cpp | 0 .../superpmi/superpmi-shared/spmiutil.h | 0 .../superpmi/superpmi-shared/standardpch.h | 0 .../superpmi/superpmi-shared/tocfile.cpp | 0 .../superpmi/superpmi-shared/tocfile.h | 0 .../superpmi/superpmi-shared/typeutils.cpp | 0 .../superpmi/superpmi-shared/typeutils.h | 0 .../superpmi-shim-collector/CMakeLists.txt | 0 .../icorjitcompiler.cpp | 0 .../superpmi-shim-collector/icorjitcompiler.h | 0 .../superpmi-shim-collector/icorjitinfo.cpp | 7 - .../superpmi-shim-collector/icorjitinfo.h | 0 .../superpmi-shim-collector/jithost.cpp | 0 .../superpmi-shim-collector/jithost.h | 0 .../superpmi-shim-collector.cpp | 0 .../superpmi-shim-collector.def | 0 .../superpmi-shim-collector.h | 0 .../superpmi-shim-counter/CMakeLists.txt | 0 .../superpmi-shim-counter/icorjitcompiler.cpp | 0 .../superpmi-shim-counter/icorjitcompiler.h | 0 .../superpmi-shim-counter/icorjitinfo.cpp | 8 - .../superpmi-shim-counter/icorjitinfo.h | 0 .../superpmi-shim-counter/jithost.cpp | 0 .../superpmi/superpmi-shim-counter/jithost.h | 0 .../methodcallsummarizer.cpp | 0 .../methodcallsummarizer.h | 0 .../superpmi-shim-counter.cpp | 0 .../superpmi-shim-counter.def | 0 .../superpmi-shim-counter.h | 0 .../superpmi-shim-simple/CMakeLists.txt | 0 .../superpmi-shim-simple/icorjitcompiler.cpp | 0 .../superpmi-shim-simple/icorjitcompiler.h | 0 .../superpmi-shim-simple/icorjitinfo.cpp | 7 - .../superpmi-shim-simple/icorjitinfo.h | 0 .../superpmi/superpmi-shim-simple/jithost.cpp | 0 .../superpmi/superpmi-shim-simple/jithost.h | 0 .../superpmi-shim-simple.cpp | 0 .../superpmi-shim-simple.def | 0 .../superpmi-shim-simple.h | 0 .../superpmi/superpmi/CMakeLists.txt | 0 .../superpmi/superpmi/commandline.cpp | 0 .../superpmi/superpmi/commandline.h | 0 .../superpmi/superpmi/cycletimer.cpp | 0 .../superpmi/superpmi/cycletimer.h | 0 .../superpmi/superpmi/icorjitinfo.cpp | 8 - .../superpmi/superpmi/icorjitinfo.h | 0 .../superpmi/superpmi/jitdebugger.cpp | 0 .../superpmi/superpmi/jitdebugger.h | 0 .../superpmi/superpmi/jithost.cpp | 0 .../superpmi/superpmi/jithost.h | 0 .../superpmi/superpmi/jitinstance.cpp | 0 .../superpmi/superpmi/jitinstance.h | 0 .../superpmi/superpmi/methodstatsemitter.cpp | 0 .../superpmi/superpmi/methodstatsemitter.h | 0 .../superpmi/superpmi/metricssummary.cpp | 0 .../superpmi/superpmi/metricssummary.h | 0 .../superpmi/superpmi/neardiffer.cpp | 0 .../superpmi/superpmi/neardiffer.h | 0 .../superpmi/superpmi/parallelsuperpmi.cpp | 0 .../superpmi/superpmi/superpmi.cpp | 0 .../superpmi/superpmi/superpmi.h | 0 src/coreclr/utilcode/log.cpp | 4 +- src/coreclr/vm/CMakeLists.txt | 2 - src/coreclr/vm/amd64/cgencpu.h | 2 - src/coreclr/vm/arm64/asmhelpers.S | 179 - src/coreclr/vm/array.cpp | 2 +- src/coreclr/vm/callingconvention.h | 5 +- src/coreclr/vm/ceeload.cpp | 2 +- src/coreclr/vm/ceeload.h | 12 - src/coreclr/vm/ceemain.cpp | 1 - src/coreclr/vm/clrtocomcall.cpp | 2 +- src/coreclr/vm/codeman.cpp | 149 +- src/coreclr/vm/cominterfacemarshaler.cpp | 1 - src/coreclr/vm/comreflectioncache.hpp | 2 +- src/coreclr/vm/comtoclrcall.cpp | 1 - src/coreclr/vm/dacenumerablehash.inl | 6 +- src/coreclr/vm/debughelp.cpp | 2 +- src/coreclr/vm/dllimport.cpp | 2 +- src/coreclr/vm/dllimportcallback.cpp | 77 +- src/coreclr/vm/dllimportcallback.h | 16 +- src/coreclr/vm/dwreport.cpp | 22 +- src/coreclr/vm/ecalllist.h | 2 - src/coreclr/vm/excep.cpp | 4 +- src/coreclr/vm/frames.cpp | 44 +- src/coreclr/vm/frames.h | 90 +- src/coreclr/vm/h2inc.pl | 61 - src/coreclr/vm/h2inc.ps1 | 69 - src/coreclr/vm/i386/asmhelpers.asm | 38 +- src/coreclr/vm/i386/cgenx86.cpp | 52 - src/coreclr/vm/i386/excepx86.cpp | 65 +- src/coreclr/vm/i386/stublinkerx86.cpp | 194 +- src/coreclr/vm/i386/stublinkerx86.h | 35 +- src/coreclr/vm/ilmarshalers.cpp | 4 +- src/coreclr/vm/interoputil.cpp | 3 +- src/coreclr/vm/interpreter.h | 2 +- src/coreclr/vm/jithelpers.cpp | 2 +- src/coreclr/vm/jitinterface.cpp | 87 +- src/coreclr/vm/jitinterface.h | 18 - src/coreclr/vm/methodtablebuilder.cpp | 8 + src/coreclr/vm/mlinfo.cpp | 28 +- src/coreclr/vm/nativelibrary.cpp | 4 +- src/coreclr/vm/notifyexternals.cpp | 47 - src/coreclr/vm/notifyexternals.h | 19 - src/coreclr/vm/peimage.cpp | 5 +- src/coreclr/vm/prestub.cpp | 12 - src/coreclr/vm/proftoeeinterfaceimpl.cpp | 2 +- src/coreclr/vm/runtimecallablewrapper.cpp | 1 - src/coreclr/vm/sigformat.cpp | 4 +- src/coreclr/vm/siginfo.cpp | 2 +- src/coreclr/vm/syncblk.cpp | 4 +- src/coreclr/vm/threadsuspend.cpp | 4 +- src/coreclr/vm/typeparse.cpp | 52 - src/coreclr/vm/typeparse.h | 6 - src/coreclr/vm/virtualcallstub.cpp | 174 +- src/coreclr/vm/wks/CMakeLists.txt | 24 +- .../Interop.Ssl.cs | 3 +- .../Interop.Ssl.cs | 26 + .../Unix/System.Native/Interop.LChflags.cs | 6 + .../Interop.EvpPkey.cs | 22 +- .../Interop.OpenSsl.cs | 56 +- .../Interop.Ssl.cs | 78 +- .../Kernel32/Interop.GetConsoleMode.cs | 3 +- .../Windows/SspiCli/SecuritySafeHandles.cs | 14 +- .../Win32/SafeHandles/GssSafeHandles.cs | 11 +- .../Data/ProviderBase/DbConnectionFactory.cs | 16 +- .../Data/ProviderBase/DbConnectionInternal.cs | 2 +- .../Data/ProviderBase/DbMetaDataFactory.cs | 15 +- .../System/Diagnostics/NetFrameworkUtils.cs | 4 +- .../IO/FileSystem.Attributes.Windows.cs | 2 +- .../src/System/IO/TempFileCollection.cs | 4 +- .../src/System/Net/NTAuthentication.Common.cs | 6 +- .../Net/SocketProtocolSupportPal.Unix.cs | 4 +- .../src/System/Resources/ResourceWriter.cs | 2 +- .../EccSecurityTransforms.macOS.cs | 4 +- .../Security/Cryptography/RSAAndroid.cs | 2 +- .../Security/Cryptography/RSAOpenSsl.cs | 2 +- .../Cryptography/RSASecurityTransforms.cs | 2 +- .../RSASecurityTransforms.macOS.cs | 2 +- .../System/Collections/DebugView.Tests.cs | 4 +- .../System/IO/FileCleanupTestBase.cs | 28 + .../System/PlatformDetection.Unix.cs | 5 + .../TestUtilities/System/PlatformDetection.cs | 46 +- .../Common/tests/Tests/System/StringTests.cs | 1 + .../RuntimeBinder/DynamicDebuggerProxy.cs | 12 +- .../RuntimeBinder/Semantics/Conversion.cs | 4 +- .../src/MemoryCache.cs | 5 +- .../src/MemoryDistributedCache.cs | 2 +- ...Extensions.Configuration.FileExtensions.cs | 9 +- ...nsions.Configuration.FileExtensions.csproj | 2 + .../src/FileConfigurationExtensions.cs | 8 +- .../src/FileConfigurationProvider.cs | 10 +- .../src/FileConfigurationSource.cs | 17 +- .../src/FileLoadExceptionContext.cs | 4 +- ...nsions.Configuration.FileExtensions.csproj | 1 + .../Microsoft.Extensions.Configuration.Ini.cs | 6 +- ...rosoft.Extensions.Configuration.Ini.csproj | 1 + .../src/IniConfigurationExtensions.cs | 4 +- .../src/IniStreamConfigurationProvider.cs | 12 +- ...rosoft.Extensions.Configuration.Ini.csproj | 1 + .../tests/IniConfigurationTest.cs | 22 + ...Microsoft.Extensions.Configuration.Json.cs | 4 +- ...osoft.Extensions.Configuration.Json.csproj | 1 + .../src/JsonConfigurationExtensions.cs | 4 +- .../src/JsonConfigurationFileParser.cs | 6 +- ...osoft.Extensions.Configuration.Json.csproj | 1 + .../src/ConfigurationManager.cs | 110 +- .../InternalConfigurationRootExtensions.cs | 15 +- .../src/ReferenceCountedProviders.cs | 93 + .../src/ReferenceCountedProvidersManager.cs | 93 + .../tests/ConfigurationManagerTest.cs | 143 + .../src/PhysicalFilesWatcher.cs | 2 +- .../src/BackgroundService.cs | 1 + .../src/IHost.cs | 5 +- .../src/HostBuilder.cs | 1 + .../src/Logging/LoggingHttpMessageHandler.cs | 20 +- .../Logging/LoggingScopeHttpMessageHandler.cs | 15 +- .../Logging/LoggingUriOutputTests.cs | 103 + .../gen/LoggerMessageGenerator.Emitter.cs | 14 +- .../Baselines/.editorconfig | 4 + .../TestWithDefaultValues.generated.txt | 4 +- .../TestWithDynamicLogLevel.generated.txt | 4 +- .../TestWithMoreThan6Params.generated.txt | 6 +- .../src/AssemblyResolver.cs | 6 +- .../src/Extensions.cs | 2 +- .../src/GenerateRuntimeGraph.cs | 2 - .../Microsoft.NETCore.Platforms/src/RID.cs | 2 +- .../src/runtime.compatibility.json | 20 + .../src/runtime.json | 11 + .../src/runtimeGroups.props | 5 + .../Microsoft/Win32/RegistryKey.Windows.cs | 10 +- .../src/Microsoft/Win32/RegistryKey.cs | 6 +- .../src/Microsoft/Win32/SystemEvents.cs | 2 +- .../src/Sgen.cs | 4 +- .../System/CodeDom/Compiler/CodeCompiler.cs | 3 +- .../Specialized/FixedStringLookup.cs | 2 +- .../Immutable/ImmutableDictionary_2.cs | 9 +- .../Immutable/ImmutableExtensions.Minimal.cs | 2 +- .../Immutable/ImmutableHashSet_1.cs | 5 +- .../Immutable/ImmutableList_1.Node.cs | 4 +- .../ImmutableSortedDictionary_2.Node.cs | 6 +- .../Immutable/ImmutableSortedDictionary_2.cs | 10 +- .../Immutable/ImmutableSortedSet_1.Builder.cs | 6 +- .../Immutable/ImmutableSortedSet_1.Node.cs | 3 +- .../Immutable/ImmutableSortedSet_1.cs | 6 +- .../Immutable/SortedInt32KeyNode.cs | 3 +- .../System/Collections/Generic/SortedSet.cs | 7 +- .../tests/Generic/Comparers/Comparer.Tests.cs | 2 +- .../tests/System.Collections.Tests.csproj | 3 + .../System.Collections/tests/default.rd.xml | 154 + .../ValidationAttributeStore.cs | 3 +- .../Composition/Registration/PartBuilder.cs | 2 +- ...atalogExportProvider.ScopeFactoryExport.cs | 2 +- .../Composition/Hosting/DirectoryCatalog.cs | 2 +- .../Primitives/PrimitivesServices.cs | 2 +- .../ComponentResourceManager.cs | 6 +- .../ComponentModel/DateTimeOffsetConverter.cs | 2 +- .../Design/PropertyTabAttribute.cs | 2 +- .../System/ComponentModel/LicenseManager.cs | 25 +- .../ComponentModel/MaskedTextProvider.cs | 45 +- .../System/ComponentModel/MemberDescriptor.cs | 4 +- .../ReflectPropertyDescriptor.cs | 2 +- .../ReflectTypeDescriptionProvider.cs | 2 +- .../System/ComponentModel/TypeDescriptor.cs | 6 +- .../System/ComponentModel/UriTypeConverter.cs | 2 +- .../src/System/Drawing/ColorConverter.cs | 2 +- .../Configuration/BaseConfigurationRecord.cs | 9 +- .../Configuration/ConfigurationElement.cs | 5 +- .../Configuration/ConfigurationManager.cs | 4 +- .../Configuration/MgmtConfigurationRecord.cs | 6 +- .../NameValueFileSectionHandler.cs | 2 +- .../System/Configuration/SectionUpdates.cs | 4 +- .../src/System/ConsolePal.Unix.cs | 4 +- .../src/System/ConsolePal.Windows.cs | 27 +- .../src/System/IO/StdInReader.cs | 5 +- .../System/Data/Common/DataRecordInternal.cs | 2 +- .../Data/Common/DbConnectionStringBuilder.cs | 10 +- .../src/System/Data/Common/DbDataAdapter.cs | 2 +- .../src/System/Data/Common/ObjectStorage.cs | 2 +- .../src/System/Data/ConstraintCollection.cs | 3 +- .../src/System/Data/DataColumnCollection.cs | 5 +- .../src/System/Data/DataRelationCollection.cs | 3 +- .../src/System/Data/DataRow.cs | 3 +- .../src/System/Data/DataSet.cs | 16 +- .../src/System/Data/DataTable.cs | 10 +- .../src/System/Data/DataTableCollection.cs | 6 +- .../src/System/Data/Filter/BinaryNode.cs | 4 +- .../System/Data/Filter/ExpressionParser.cs | 6 +- .../src/System/Data/Filter/UnaryNode.cs | 2 +- .../src/System/Data/ForeignKeyConstraint.cs | 6 +- .../src/System/Data/Merger.cs | 2 - .../src/System/Data/RbTree.cs | 9 +- .../src/System/Data/RelationshipConverter.cs | 4 +- .../src/System/Data/SQLTypes/SQLBytes.cs | 2 +- .../src/System/Data/SQLTypes/SQLChars.cs | 4 +- .../src/System/Data/SQLTypes/SQLDecimal.cs | 8 +- .../src/System/Data/SQLTypes/SQLString.cs | 2 +- .../src/System/Data/Select.cs | 2 +- .../src/System/Data/XDRSchema.cs | 4 +- .../src/System/Data/XMLDiffLoader.cs | 7 +- .../src/System/Data/XMLSchema.cs | 18 +- .../src/System/Data/XmlDataLoader.cs | 5 +- .../src/System/Data/XmlToDatasetMap.cs | 2 +- .../src/System/Data/xmlsaver.cs | 10 +- .../src/System/Xml/DataPointer.cs | 2 +- .../src/System/Xml/XPathNodePointer.cs | 35 +- .../src/System/Xml/XmlBoundElement.cs | 2 +- .../src/System/Xml/XmlDataDocument.cs | 10 +- .../tests/System/Data/DataTableTest.cs | 16 +- .../System/Data/Common/DBConnectionString.cs | 4 +- .../System/Data/Common/DbConnectionOptions.cs | 2 +- .../Data/ProviderBase/DbConnectionPool.cs | 2 +- .../src/System/Data/Odbc/Odbc32.cs | 4 +- .../System/Data/Odbc/OdbcCommandBuilder.cs | 2 +- .../src/System/Data/Odbc/OdbcConnection.cs | 7 +- .../System/Data/Odbc/OdbcConnectionFactory.cs | 12 +- .../System/Data/Odbc/OdbcConnectionHandle.cs | 10 +- .../src/System/Data/Odbc/OdbcDataReader.cs | 41 +- .../System/Data/Odbc/OdbcEnvironmentHandle.cs | 2 +- .../src/System/Data/Odbc/OdbcHandle.cs | 4 +- .../System/Data/Odbc/OdbcMetaDataFactory.cs | 2 +- .../src/System/Data/Odbc/OdbcUtils.cs | 1 - .../src/DbConnectionOptions.cs | 2 +- .../System.Data.OleDb/src/DbPropSet.cs | 3 +- .../System.Data.OleDb/src/OleDbConnection.cs | 5 +- .../src/OleDbConnectionString.cs | 2 +- .../System.Data.OleDb/src/OleDbDataAdapter.cs | 7 +- .../System.Data.OleDb/src/OleDbDataReader.cs | 5 +- .../System.Data.OleDb/src/OleDbEnumerator.cs | 3 +- .../System.Data.OleDb/src/OleDbError.cs | 2 +- .../System.Data.OleDb/src/OleDbException.cs | 7 +- .../System.Data.OleDb/src/OleDbTransaction.cs | 3 +- .../System.Data.OleDb/src/RowBinding.cs | 9 +- .../System.Data.OleDb/src/SafeHandles.cs | 17 +- .../Data/ProviderBase/DbConnectionFactory.cs | 6 +- .../Data/ProviderBase/DbConnectionHelper.cs | 4 +- .../DbConnectionInternal.Shared.cs | 2 +- .../Data/ProviderBase/DbConnectionPool.cs | 2 +- .../ProviderBase/DbConnectionPoolCounters.cs | 4 +- .../ProviderBase/DbConnectionPoolIdentity.cs | 3 +- .../Data/ProviderBase/DbMetaDataFactory.cs | 17 +- ...em.Diagnostics.DiagnosticSourceActivity.cs | 2 + .../src/System/Diagnostics/Activity.cs | 31 +- .../src/System/Diagnostics/ActivityContext.cs | 15 +- .../DiagnosticSourceEventSource.cs | 2 +- .../Diagnostics/PassThroughPropagator.cs | 2 +- .../tests/ActivitySourceTests.cs | 19 + .../tests/ActivityTests.cs | 46 +- .../src/System/Diagnostics/EventLog.cs | 2 +- .../System/Diagnostics/EventLogInternal.cs | 12 +- .../Diagnostics/Reader/EventLogReader.cs | 9 +- .../Diagnostics/Reader/EventLogSession.cs | 2 - .../Diagnostics/Reader/NativeWrapper.cs | 2 +- .../Diagnostics/FileVersionInfo.Windows.cs | 15 +- .../System/Diagnostics/PerformanceCounter.cs | 3 +- .../Diagnostics/PerformanceCounterLib.cs | 22 +- .../Diagnostics/PerformanceDataRegistryKey.cs | 3 +- .../src/System/Diagnostics/Process.FreeBSD.cs | 3 +- .../src/System/Diagnostics/Process.Unix.cs | 3 +- .../Diagnostics/ProcessWaitState.Unix.cs | 6 +- .../tests/StackTraceTests.cs | 12 + ...System.Diagnostics.StackTrace.Tests.csproj | 1 + ...DirectoryServices.AccountManagement.csproj | 2 +- .../Protocols/common/BerConverter.Linux.cs | 3 +- .../Protocols/common/BerConverter.cs | 30 +- .../Protocols/common/DirectoryControl.cs | 2 +- .../Protocols/ldap/LdapConnection.Linux.cs | 2 +- .../Protocols/ldap/LdapConnection.cs | 20 +- .../Protocols/ldap/LdapSessionOptions.cs | 2 +- .../src/System.DirectoryServices.csproj | 2 +- .../ActiveDirectory/Domain.cs | 4 +- .../ref/System.Drawing.Common.netcoreapp.cs | 2 + .../src/System/Drawing/Bitmap.cs | 18 +- .../BufferedGraphicsContext.Windows.cs | 1 - .../System/Drawing/Drawing2D/HatchBrush.cs | 2 +- .../src/System/Drawing/Font.Unix.cs | 2 +- .../src/System/Drawing/FontConverter.cs | 2 +- .../src/System/Drawing/FontFamily.cs | 14 +- .../Drawing/GdiPlusStreamHelper.Unix.cs | 2 +- .../src/System/Drawing/Gdiplus.cs | 2 +- .../src/System/Drawing/GdiplusNative.Unix.cs | 2 +- .../src/System/Drawing/Graphics.cs | 32 +- .../src/System/Drawing/Icon.Unix.cs | 4 - .../src/System/Drawing/Icon.Windows.cs | 7 +- .../src/System/Drawing/Image.Unix.cs | 2 +- .../src/System/Drawing/Image.Windows.cs | 8 +- .../src/System/Drawing/Image.cs | 2 +- .../System/Drawing/Imaging/ImageAttributes.cs | 6 +- .../Drawing/Imaging/Metafile.Windows.cs | 4 +- .../src/System/Drawing/Pen.Unix.cs | 2 +- .../src/System/Drawing/Pen.Windows.cs | 4 +- .../src/System/Drawing/Pen.cs | 26 +- .../Printing/PrinterSettings.Windows.cs | 10 +- .../Drawing/Printing/PrintingServices.Unix.cs | 2 +- .../src/System/Drawing/Region.cs | 2 +- .../src/System/Drawing/SolidBrush.cs | 2 +- .../src/System/Drawing/StringFormat.cs | 16 +- .../src/System/Drawing/Text/FontCollection.cs | 4 +- .../src/System/Drawing/TextureBrush.cs | 14 +- .../System/Drawing/ToolboxBitmapAttribute.cs | 2 +- .../src/System/Drawing/macFunctions.cs | 4 +- .../tests/GraphicsTests.Core.cs | 149 + .../tests/GraphicsTests.cs | 93 +- .../NumberFormatInfo/NumberFormatInfoData.cs | 6 +- .../IO/Compression/enc/BrotliEncoder.cs | 2 +- ...System.IO.Compression.ZipFile.Tests.csproj | 9 + .../DeflateManaged/InflaterManaged.cs | 2 +- .../Compression/DeflateZLib/DeflateStream.cs | 6 +- .../System/IO/Compression/ZipArchiveEntry.cs | 4 +- .../tests/System.IO.Compression.Tests.csproj | 9 + .../AccessControl/DirectoryObjectSecurity.cs | 33 +- .../src/System/IO/DriveInfo.Unix.cs | 8 +- .../tests/DriveInfo.Unix.Tests.cs | 2 +- .../tests/Directory/Exists.cs | 1 + .../System.IO.FileSystem/tests/File/Exists.cs | 1 + .../tests/File/ReadWriteAllBytes.cs | 2 +- .../tests/File/ReadWriteAllBytesAsync.cs | 2 +- .../FileStreamConformanceTests.Windows.cs | 2 +- .../FileStream/FileStreamConformanceTests.cs | 2 +- .../tests/FileSystemTest.cs | 25 - .../tests/RandomAccess/NoBuffering.Windows.cs | 41 +- .../IO/MemoryMappedFiles/MemoryMappedFile.cs | 9 +- .../MemoryMappedView.Windows.cs | 2 +- .../MemoryMappedFile.CreateFromFile.Tests.cs | 52 + .../tests/MemoryMappedFile.CreateNew.Tests.cs | 1 + .../tests/MemoryMappedFilesTestsBase.Unix.cs | 3 + .../MemoryMappedFilesTestsBase.Windows.cs | 7 +- .../tests/MemoryMappedViewAccessor.Tests.cs | 1 + .../tests/MemoryMappedViewStream.Tests.cs | 1 + .../MemoryMappedViewStreamConformanceTests.cs | 1 + .../src/System/IO/Packaging/ContentType.cs | 2 +- .../src/System/IO/Packaging/PackUriHelper.cs | 2 +- .../Packaging/PartBasedPackageProperties.cs | 2 +- .../IO/Packaging/XmlCompatibilityReader.cs | 2 +- .../src/System/IO/Packaging/ZipPackage.cs | 4 +- .../IO/Pipes/AnonymousPipeClientStream.cs | 3 +- .../src/System/IO/Ports/SerialStream.Unix.cs | 2 +- .../System/IO/Ports/SerialStream.Windows.cs | 23 +- .../src/System.Management.csproj | 2 +- .../Management/ManagementObjectTests.cs | 38 +- .../src/System/Text/EncodingExtensions.cs | 8 +- .../Net/Http/Json/TranscodingReadStream.cs | 2 +- .../src/System/Net/Http/WinHttpAuthHelper.cs | 11 +- .../System/Net/Http/WinHttpChannelBinding.cs | 3 +- .../src/System/Net/Http/WinHttpHandler.cs | 2 +- .../Net/Http/WinHttpResponseHeaderReader.cs | 4 +- .../Http/Headers/AuthenticationHeaderValue.cs | 5 +- .../Net/Http/Headers/BaseHeaderParser.cs | 2 +- .../Http/Headers/CacheControlHeaderValue.cs | 3 +- .../Headers/ContentDispositionHeaderValue.cs | 2 +- .../Http/Headers/ContentRangeHeaderValue.cs | 8 +- .../Net/Http/Headers/EntityTagHeaderValue.cs | 5 +- .../Net/Http/Headers/GenericHeaderParser.cs | 4 +- .../Net/Http/Headers/HeaderUtilities.cs | 6 +- .../Net/Http/Headers/HttpRequestHeaders.cs | 2 +- .../Http/Headers/Int32NumberHeaderParser.cs | 2 +- .../Http/Headers/Int64NumberHeaderParser.cs | 2 +- .../Http/Headers/ProductInfoHeaderValue.cs | 6 +- .../Net/Http/Headers/RangeItemHeaderValue.cs | 5 +- .../Net/Http/Headers/TimeSpanHeaderParser.cs | 2 +- .../System/Net/Http/Headers/ViaHeaderValue.cs | 9 +- .../Net/Http/Headers/WarningHeaderValue.cs | 15 +- .../src/System/Net/Http/HttpContent.cs | 2 +- .../src/System/Net/Http/HttpRuleParser.cs | 15 +- .../AuthenticationHelper.Digest.cs | 25 +- .../SocketsHttpHandler/HttpWindowsProxy.cs | 3 +- .../tests/UnitTests/HttpRuleParserTest.cs | 11 +- .../src/System/Net/HttpListener.cs | 2 +- .../src/System/Net/HttpListenerRequest.cs | 4 +- .../Net/HttpListenerRequestUriBuilder.cs | 4 +- .../src/System/Net/Managed/ChunkStream.cs | 2 +- .../src/System/Net/Managed/HttpConnection.cs | 3 +- .../System/Net/Managed/HttpEndPointManager.cs | 4 +- .../Managed/HttpListenerContext.Managed.cs | 2 +- .../Net/Managed/HttpResponseStream.Managed.cs | 4 +- .../src/System/Net/ServiceNameStore.cs | 6 +- .../Net/Windows/HttpListener.Windows.cs | 10 +- .../Net/Windows/HttpRequestStream.Windows.cs | 2 +- .../Windows/HttpResponseStreamAsyncResult.cs | 2 +- .../WebSocketHttpListenerDuplexStream.cs | 7 +- .../WebSockets/WebSocketProtocolComponent.cs | 13 +- .../src/System/Net/BufferedReadStream.cs | 2 +- .../src/System/Net/Mail/Attachment.cs | 3 +- .../src/System/Net/Mail/MailAddress.cs | 2 +- .../src/System/Net/Mail/MailMessage.cs | 2 +- .../src/System/Net/Mail/MailPriority.cs | 2 +- .../tests/Functional/SmtpClientTest.cs | 4 +- .../ref/System.Net.NetworkInformation.cs | 43 + .../src/System.Net.NetworkInformation.csproj | 19 +- .../AndroidIPGlobalProperties.cs | 32 + .../AndroidIPGlobalStatistics.cs | 73 + .../AndroidIPInterfaceProperties.cs | 30 + .../AndroidIPv4InterfaceProperties.cs | 24 + .../AndroidIPv6InterfaceProperties.cs | 31 + .../AndroidNetworkInterface.cs | 54 + .../NetworkInformation/IPGlobalProperties.cs | 8 + .../IPGlobalPropertiesPal.Android.cs | 13 + .../NetworkInformation/IPGlobalStatistics.cs | 22 + .../IPInterfaceProperties.cs | 10 + .../IPv4InterfaceProperties.cs | 7 + .../NetworkAddressChange.UnknownUnix.cs | 12 +- .../NetworkInformation/NetworkInterface.cs | 2 + .../NetworkInterfacePal.Android.cs | 110 + .../SystemIPGlobalProperties.cs | 4 +- .../UnixIPGlobalProperties.cs | 2 + .../UnixNetworkInterface.cs | 2 +- .../FunctionalTests/IPGlobalPropertiesTest.cs | 68 +- .../IPInterfacePropertiesTest_Android.cs | 221 + .../NetworkInterfaceBasicTest.cs | 9 +- .../NetworkInterfaceIPv4Statistics.cs | 11 + .../Net/NetworkInformation/Ping.RawSocket.cs | 2 +- .../src/System/Net/CookieContainer.cs | 7 +- .../src/System/Net/CredentialCache.cs | 2 +- .../FunctionalTests/SocketAddressTest.cs | 2 +- .../Interop/SafeMsQuicConfigurationHandle.cs | 6 +- .../Implementations/MsQuic/MsQuicStream.cs | 2 +- .../src/System/Net/FtpControlStream.cs | 2 +- .../src/System/Net/FtpWebRequest.cs | 2 +- .../src/System/Net/FtpWebResponse.cs | 2 +- .../Net/CertificateValidationPal.OSX.cs | 5 + .../Security/NegotiateStreamPal.Windows.cs | 2 +- .../Security/Pal.OSX/SafeDeleteSslContext.cs | 2 +- .../Net/Security/SslStream.Implementation.cs | 2 +- .../System/Net/Security/SslStreamPal.OSX.cs | 38 + .../System/Net/Security/SslStreamPal.Unix.cs | 46 +- .../Net/Security/SslStreamPal.Windows.cs | 6 +- .../ServiceNameCollection.cs | 3 +- .../CertificateValidationClientServer.cs | 75 + .../Net/Sockets/DynamicWinsockMethods.cs | 5 +- .../src/System/Net/Sockets/Socket.cs | 14 +- .../Net/Sockets/SocketAsyncEventArgs.Unix.cs | 2 +- .../Net/Sockets/SocketAsyncEventArgs.cs | 2 +- .../src/System/Net/Sockets/SocketPal.Unix.cs | 4 +- .../System/Net/Sockets/SocketPal.Windows.cs | 7 +- .../tests/FunctionalTests/SendPacketsAsync.cs | 12 +- .../ref/System.Numerics.Vectors.cs | 36 + .../src/Internal/Win32/RegistryKey.cs | 10 +- .../Win32/SafeHandles/SafeFileHandle.Unix.cs | 11 + .../SafeHandles/SafeFileHandle.Windows.cs | 39 +- .../System.Private.CoreLib.Shared.projitems | 9 +- .../src/System/ArraySegment.cs | 4 +- .../src/System/Collections/Generic/List.cs | 2 +- .../System.Private.CoreLib/src/System/Enum.cs | 2 +- .../src/System/Environment.Unix.cs | 2 +- .../src/System/Environment.Win32.cs | 4 +- .../src/System/Environment.cs | 2 +- .../src/System/Environment.iOS.cs | 13 + .../System/Globalization/CalendarData.Icu.cs | 2 +- .../src/System/Globalization/CultureData.cs | 2 +- .../src/System/Globalization/DateTimeParse.cs | 2 +- .../System.Private.CoreLib/src/System/Guid.cs | 2 +- .../src/System/IO/BufferedStream.cs | 33 +- .../IO/Enumeration/FileSystemEntry.Unix.cs | 2 +- .../FileSystemEnumerableFactory.cs | 2 +- .../System/IO/Enumeration/FileSystemName.cs | 2 +- .../src/System/IO/File.cs | 4 +- .../src/System/IO/FileStatus.Unix.cs | 12 +- .../src/System/IO/FileSystem.Windows.cs | 1 - .../src/System/IO/MemoryStream.cs | 9 +- .../src/System/IO/Path.cs | 2 +- .../src/System/IO/RandomAccess.Unix.cs | 7 - .../src/System/IO/RandomAccess.Windows.cs | 30 +- .../src/System/IO/RandomAccess.cs | 3 +- .../Strategies/BufferedFileStreamStrategy.cs | 17 +- .../IO/Strategies/OSFileStreamStrategy.cs | 37 +- .../src/System/IO/UnmanagedMemoryStream.cs | 7 +- .../System.Private.CoreLib/src/System/Math.cs | 24 +- .../src/System/MemoryExtensions.cs | 191 +- .../src/System/Net/WebUtility.cs | 6 +- .../src/System/Numerics/Matrix3x2.cs | 4 +- .../src/System/Numerics/Matrix4x4.cs | 4 +- .../src/System/Numerics/Quaternion.cs | 5 +- .../src/System/Numerics/Vector.cs | 568 +- .../src/System/Numerics/Vector2.cs | 9 +- .../src/System/Numerics/Vector3.cs | 9 +- .../src/System/Numerics/Vector4.cs | 10 +- .../src/System/Numerics/Vector_1.cs | 12 +- .../src/System/ProbabilisticMap.cs | 94 + .../Reflection/NullabilityInfoContext.cs | 35 +- .../src/System/Resources/ResourceManager.cs | 2 +- .../CompilerServices/RuntimeHelpers.cs | 10 + .../InteropServices/RuntimeInformation.cs | 2 +- .../Runtime/InteropServices/SafeBuffer.cs | 2 + .../src/System/Runtime/Intrinsics/Scalar.cs | 206 + .../System/Runtime/Intrinsics/Vector128.cs | 902 +++- .../System/Runtime/Intrinsics/Vector128_1.cs | 14 +- .../System/Runtime/Intrinsics/Vector256.cs | 904 +++- .../System/Runtime/Intrinsics/Vector256_1.cs | 14 +- .../src/System/Runtime/Intrinsics/Vector64.cs | 874 ++- .../System/Runtime/Intrinsics/Vector64_1.cs | 14 +- .../Runtime/Loader/AssemblyLoadContext.cs | 2 +- .../Runtime/Versioning/FrameworkName.cs | 2 +- .../src/System/RuntimeType.cs | 2 +- .../System.Private.CoreLib/src/System/SR.cs | 2 +- .../src/System/Security/SecurityElement.cs | 40 +- .../src/System/SpanHelpers.Byte.cs | 4 +- .../src/System/SpanHelpers.Char.cs | 2 +- .../src/System/SpanHelpers.T.cs | 4 +- .../src/System/String.Comparison.cs | 21 +- .../src/System/String.Manipulation.cs | 9 +- .../src/System/String.Searching.cs | 229 +- .../src/System/Text/StringBuilder.cs | 11 +- .../LowLevelLifoSemaphore.Windows.cs | 2 +- .../PortableThreadPool.WaitThread.cs | 4 +- .../Tasks/CachedCompletedInt32Task.cs | 36 + .../src/System/Threading/Tasks/Task.cs | 2 +- .../System/Threading/ThreadPoolWorkQueue.cs | 4 +- .../src/System/ThrowHelper.cs | 5 +- .../System/TimeZoneInfo.Unix.NonAndroid.cs | 6 +- .../src/System/Version.cs | 4 +- .../Runtime/Serialization/CodeGenerator.cs | 4 +- .../Serialization/CollectionDataContract.cs | 20 +- .../Runtime/Serialization/DataContract.cs | 21 +- .../Serialization/DataContractSerializer.cs | 2 +- .../Runtime/Serialization/DataContractSet.cs | 2 +- .../Runtime/Serialization/EnumDataContract.cs | 2 +- .../Serialization/HybridObjectCache.cs | 3 +- .../Json/JsonFormatReaderGenerator.cs | 2 +- .../Json/JsonFormatWriterGenerator.cs | 2 +- .../Json/JsonObjectDataContract.cs | 3 +- .../Json/ReflectionJsonFormatWriter.cs | 2 +- .../Serialization/Json/XmlJsonReader.cs | 2 +- .../Runtime/Serialization/ObjectToIdCache.cs | 6 +- .../Runtime/Serialization/ReflectionReader.cs | 6 +- .../Runtime/Serialization/SchemaExporter.cs | 2 +- .../Runtime/Serialization/XmlDataContract.cs | 5 +- .../Serialization/XmlFormatReaderGenerator.cs | 2 +- .../Serialization/XmlFormatWriterGenerator.cs | 2 +- .../XmlObjectSerializerReadContext.cs | 2 +- .../XmlObjectSerializerReadContextComplex.cs | 7 +- .../Serialization/XmlReaderDelegator.cs | 18 +- .../src/System/Xml/ArrayHelper.cs | 2 +- .../src/System/Xml/EncodingStreamWrapper.cs | 2 +- .../src/System/Xml/XmlBaseWriter.cs | 8 +- .../src/System/Xml/XmlBinaryReader.cs | 11 +- .../src/System/Xml/XmlBinaryReaderSession.cs | 2 +- .../src/System/Xml/XmlBufferReader.cs | 6 +- .../src/System/Xml/XmlCanonicalWriter.cs | 4 +- .../src/System/Xml/XmlDictionaryWriter.cs | 2 +- .../src/System/Xml/XmlUTF8TextReader.cs | 14 +- .../JavaScript/JSObject.References.cs | 6 +- .../InteropServices/JavaScript/JSObject.cs | 2 +- .../Runtime/InteropServices/JavaScript/Map.cs | 3 +- .../InteropServices/JavaScript/Runtime.cs | 206 +- .../System.Private.Uri/src/System/Uri.cs | 2 +- .../System.Private.Uri/src/System/UriExt.cs | 1 - .../src/System/Xml/Linq/XContainer.cs | 2 - .../src/System/Xml/Linq/XHashtable.cs | 3 +- .../src/System/Xml/XPath/XNodeNavigator.cs | 4 +- .../src/System/Xml/BinHexDecoder.cs | 2 +- .../System/Xml/BinaryXml/XmlBinaryReader.cs | 7 +- .../System/Xml/Cache/XPathDocumentBuilder.cs | 2 + .../src/System/Xml/Cache/XPathNodeHelper.cs | 1 - .../Xml/Core/XmlEncodedRawTextWriter.cs | 9 +- .../Xml/Core/XmlEncodedRawTextWriterAsync.cs | 41 +- .../src/System/Xml/Core/XmlTextReaderImpl.cs | 58 +- .../System/Xml/Core/XmlTextReaderImplAsync.cs | 18 +- .../System/Xml/Core/XmlUtf8RawTextWriter.cs | 2 +- .../Xml/Core/XmlUtf8RawTextWriterAsync.cs | 34 +- .../System/Xml/Core/XsdValidatingReader.cs | 6 +- .../Xml/Core/XsdValidatingReaderAsync.cs | 2 +- .../System/Xml/Dom/DocumentSchemaValidator.cs | 13 +- .../src/System/Xml/Dom/XmlDeclaration.cs | 6 +- .../src/System/Xml/Dom/XmlDocument.cs | 16 +- .../src/System/Xml/Dom/XmlLoader.cs | 10 +- .../src/System/Xml/Dom/XmlNode.cs | 6 +- .../src/System/Xml/Dom/XmlNodeReader.cs | 12 +- .../Xml/Schema/DataTypeImplementation.cs | 12 +- .../src/System/Xml/Schema/DtdParser.cs | 6 +- .../src/System/Xml/Schema/DtdParserAsync.cs | 6 +- .../src/System/Xml/Schema/DtdValidator.cs | 2 +- .../src/System/Xml/Schema/FacetChecker.cs | 3 +- .../src/System/Xml/Schema/Inference/Infer.cs | 26 +- .../src/System/Xml/Schema/NamespaceList.cs | 3 +- .../src/System/Xml/Schema/Parser.cs | 2 +- .../src/System/Xml/Schema/Preprocessor.cs | 6 +- .../Xml/Schema/SchemaCollectionCompiler.cs | 16 +- .../Schema/SchemaCollectionpreProcessor.cs | 2 +- .../System/Xml/Schema/SchemaSetCompiler.cs | 16 +- .../src/System/Xml/Schema/XdrValidator.cs | 2 +- .../src/System/Xml/Schema/XmlSchema.cs | 4 +- .../System/Xml/Schema/XmlSchemaComplexType.cs | 2 +- .../System/Xml/Schema/XmlSchemaObjectTable.cs | 2 +- .../src/System/Xml/Schema/XmlSchemaSet.cs | 3 +- .../System/Xml/Schema/XmlSchemaValidator.cs | 12 +- .../src/System/Xml/Schema/XsdDuration.cs | 5 +- .../src/System/Xml/Schema/XsdValidator.cs | 4 +- .../System/Xml/Serialization/CodeGenerator.cs | 8 +- .../System/Xml/Serialization/Compilation.cs | 2 +- .../System/Xml/Serialization/ImportContext.cs | 3 +- .../src/System/Xml/Serialization/Mappings.cs | 5 +- .../ReflectionXmlSerializationWriter.cs | 4 +- .../src/System/Xml/Serialization/Types.cs | 4 +- .../Serialization/XmlReflectionImporter.cs | 2 +- .../Xml/Serialization/XmlSchemaImporter.cs | 4 +- .../System/Xml/Serialization/XmlSchemas.cs | 2 +- .../Serialization/XmlSerializationReader.cs | 17 +- .../XmlSerializationReaderILGen.cs | 5 +- .../Serialization/XmlSerializationWriter.cs | 16 +- .../XmlSerializationWriterILGen.cs | 2 +- .../System/Xml/Serialization/XmlSerializer.cs | 2 +- .../Xml/XPath/Internal/DescendantBaseQuery.cs | 2 +- .../Xml/XPath/Internal/FunctionQuery.cs | 2 +- .../System/Xml/XPath/Internal/QueryBuilder.cs | 7 +- .../System/Xml/XPath/Internal/SortQuery.cs | 2 +- .../System/Xml/XPath/Internal/UnionExpr.cs | 2 +- .../System/Xml/XPath/XPathNavigatorReader.cs | 4 +- .../src/System/Xml/XmlConvert.cs | 10 +- .../src/System/Xml/XmlEncoding.cs | 5 +- .../Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs | 8 - .../src/System/Xml/Xsl/QIL/QilXmlWriter.cs | 2 +- .../Xml/Xsl/Runtime/DecimalFormatter.cs | 2 +- .../System/Xml/Xsl/Runtime/XmlQueryRuntime.cs | 10 +- .../src/System/Xml/Xsl/Xslt/MatcherBuilder.cs | 2 - .../src/System/Xml/Xsl/Xslt/QilGenerator.cs | 18 +- .../src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs | 2 +- .../src/System/Xml/Xsl/Xslt/XsltLoader.cs | 20 +- .../System/Xml/Xsl/XsltOld/ChooseAction.cs | 2 +- .../src/System/Xml/Xsl/XsltOld/Compiler.cs | 3 +- .../System/Xml/Xsl/XsltOld/ContainerAction.cs | 5 +- .../System/Xml/Xsl/XsltOld/NumberAction.cs | 2 - .../Xml/Xsl/XsltOld/OutputScopeManager.cs | 5 +- .../src/System/Xml/Xsl/XsltOld/Processor.cs | 2 +- .../System/Xml/Xsl/XsltOld/RecordBuilder.cs | 8 +- .../src/System/Xml/Xsl/XsltOld/SortAction.cs | 4 +- .../Xml/Xsl/XsltOld/TemplateLookupAction.cs | 4 +- .../Xml/Xsl/XsltOld/XsltCompileContext.cs | 6 +- ...l.Xsl.XslCompiledTransformApi.Tests.csproj | 9 + ...ystem.Xml.Xsl.XslTransformApi.Tests.csproj | 9 + .../XsltCompiler/XsltCompiler.Tests.csproj | 9 + .../src/System.Reflection.Metadata.csproj | 2 +- .../Internal/Utilities/BlobUtilities.cs | 3 +- .../Internal/Utilities/MemoryBlock.cs | 15 +- .../Metadata/Internal/StringHeap.cs | 6 +- .../Metadata/MetadataReader.WinMD.cs | 3 +- .../Reflection/Metadata/MetadataReader.cs | 3 +- .../MetadataLoadContext.CoreAssembly.cs | 1 - .../MethodBase/Ecma/EcmaMethodBody.cs | 2 +- .../Parameters/Ecma/EcmaFatMethodParameter.cs | 1 - .../tests/System/EnvironmentTests.cs | 2 +- .../DllImportGenerator.csproj | 8 +- ...System.Runtime.InteropServices.Forwards.cs | 1 + .../ref/System.Runtime.InteropServices.cs | 55 - .../ObjectiveC/MessageSendTests.cs | 11 +- .../ObjectiveC/PendingExceptionTests.cs | 7 +- .../ref/System.Runtime.Intrinsics.cs | 171 + .../tests/Vectors/Vector128Tests.cs | 3811 +++++++++++++- .../tests/Vectors/Vector256Tests.cs | 4667 ++++++++++++++++- .../tests/Vectors/Vector64Tests.cs | 3415 +++++++++++- .../AddLambdaCapturingThis.cs | 22 +- .../AddLambdaCapturingThis_v1.cs | 28 +- .../AddNestedClass.cs | 20 + .../AddNestedClass_v1.cs | 29 + ...ata.ApplyUpdate.Test.AddNestedClass.csproj | 11 + .../deltascript.json | 6 + .../AddStaticField.cs | 22 + .../AddStaticField_v1.cs | 25 + ...ata.ApplyUpdate.Test.AddStaticField.csproj | 11 + .../deltascript.json | 6 + .../AddStaticLambda.cs | 18 + .../AddStaticLambda_v1.cs | 18 + ...ta.ApplyUpdate.Test.AddStaticLambda.csproj | 11 + .../deltascript.json | 6 + .../tests/ApplyUpdateTest.cs | 96 +- .../tests/ApplyUpdateUtil.cs | 2 +- .../tests/System.Runtime.Loader.Tests.csproj | 3 + .../src/System/Numerics/BigInteger.cs | 6 +- .../Binary/BinaryFormatterWriter.cs | 12 +- .../Formatters/Binary/BinaryObjectInfo.cs | 15 +- .../Formatters/Binary/BinaryObjectReader.cs | 11 +- .../Formatters/Binary/BinaryObjectWriter.cs | 13 +- .../Formatters/Binary/BinaryParser.cs | 2 +- .../Formatters/Binary/BinaryTypeConverter.cs | 2 +- .../Formatters/Binary/ObjectMap.cs | 5 +- .../Runtime/Serialization/ObjectManager.cs | 4 +- .../System.Runtime/ref/System.Runtime.cs | 55 + .../tests/System.Runtime.Tests.csproj | 3 + .../tests/System/ActivatorTests.cs | 9 +- .../tests/System/AttributeTests.cs | 1 + .../System.Runtime/tests/System/Attributes.cs | 1 + .../StackTraceHiddenAttributeTests.cs | 1 + .../System/PseudoCustomAttributeTests.cs | 1 + .../Reflection/CustomAttributeDataTests.cs | 1 + .../Reflection/InvokeWithRefLikeArgs.cs | 3 + .../System/Reflection/MethodBaseTests.cs | 2 +- .../System/Reflection/MethodBodyTests.cs | 2 +- .../tests/System/Reflection/ModuleTests.cs | 22 +- .../Reflection/NullabilityInfoContextTests.cs | 38 + .../System/Reflection/ReflectionCacheTests.cs | 4 +- .../Reflection/TypeTests.Get.CornerCases.cs | 1 + .../CompilerServices/RuntimeFeatureTests.cs | 12 +- .../CompilerServices/RuntimeHelpersTests.cs | 37 +- .../tests/System/Runtime/JitInfoTests.cs | 4 +- .../tests/System/Type/TypePropertyTests.cs | 1 + .../tests/System/Type/TypeTests.cs | 13 +- .../System.Runtime/tests/default.rd.xml | 505 ++ .../src/System/Security/AccessControl/ACL.cs | 12 +- .../AccessControl/CommonObjectSecurity.cs | 33 +- .../AccessControl/SecurityDescriptor.cs | 1 - .../System/Security/Claims/ClaimsIdentity.cs | 2 +- .../src/Internal/Cryptography/Helpers.cs | 3 +- .../Security/Cryptography/CngKey.Import.cs | 2 +- .../Cryptography/CngKey.Properties.cs | 3 +- .../Cryptography/ECDiffieHellmanCng.Key.cs | 5 +- .../Security/Cryptography/ECDsaCng.Key.cs | 9 +- .../Cryptography/Unix/HashAlgorithmNames.cs | 2 +- .../Cryptography/CapiHelper.DSA.Shared.cs | 2 +- .../Cryptography/CapiHelper.Windows.cs | 2 +- .../Cryptography/MD5CryptoServiceProvider.cs | 5 +- .../Cryptography/SHA1CryptoServiceProvider.cs | 5 +- .../SHA256CryptoServiceProvider.cs | 5 +- .../SHA384CryptoServiceProvider.cs | 5 +- .../SHA512CryptoServiceProvider.cs | 5 +- .../Pal/AnyOS/ManagedPal.Decrypt.cs | 1 - .../Pal/Windows/HelpersWindows.cs | 2 +- .../Internal/Cryptography/Pal.OSX/ChainPal.cs | 1 - .../Cryptography/Pal.Unix/CrlCache.cs | 2 +- .../Cryptography/Pal.Unix/PkcsFormatReader.cs | 40 +- .../Pal.Unix/UnixExportProvider.cs | 11 +- .../Pal.Windows/CertificatePal.PrivateKey.cs | 4 +- .../Pal.Windows/CertificatePal.cs | 3 +- .../Pal.Windows/X509Pal.PublicKey.cs | 2 +- .../Pal.iOS/ApplePkcs12CertLoader.cs | 1 - .../Xml/AncestralNamespaceContextManager.cs | 4 +- .../C14NAncestralNamespaceContextManager.cs | 2 +- .../Security/Cryptography/Xml/EncryptedXml.cs | 10 +- .../ExcAncestralNamespaceContextManager.cs | 3 +- .../Cryptography/Xml/KeyInfoX509Data.cs | 4 +- .../Security/Cryptography/Xml/SignedXml.cs | 9 +- .../Cryptography/Xml/SignedXmlDebugLog.cs | 4 +- .../System/Security/Cryptography/Xml/Utils.cs | 2 +- .../Xml/XmlDsigBase64Transform.cs | 4 +- .../Cryptography/Xml/XmlLicenseTransform.cs | 26 +- .../ref/System.Security.Cryptography.cs | 20 + .../Security/Cryptography/CryptoStream.cs | 1 - .../System/Security/Cryptography/ECCngKey.cs | 2 +- .../System/Security/Cryptography/HMACMD5.cs | 19 +- .../System/Security/Cryptography/HMACSHA1.cs | 19 +- .../Security/Cryptography/HMACSHA256.cs | 19 +- .../Security/Cryptography/HMACSHA384.cs | 19 +- .../Security/Cryptography/HMACSHA512.cs | 17 +- .../src/System/Security/Cryptography/MD5.cs | 19 +- .../Security/Cryptography/PemEncoding.cs | 1 - .../Cryptography/RC2Implementation.cs | 15 +- .../src/System/Security/Cryptography/SHA1.cs | 19 +- .../System/Security/Cryptography/SHA256.cs | 19 +- .../System/Security/Cryptography/SHA384.cs | 19 +- .../System/Security/Cryptography/SHA512.cs | 19 +- .../tests/AsnEncodedDataTests.cs | 5 +- .../tests/HmacMD5Tests.cs | 2 +- .../tests/HmacSha1Tests.cs | 2 +- .../tests/HmacSha256Tests.cs | 2 +- .../tests/HmacSha384Tests.cs | 2 +- .../tests/HmacSha512Tests.cs | 2 +- .../Security/Principal/WindowsIdentity.cs | 14 +- .../System.Speech/src/System.Speech.csproj | 2 +- .../ref/System.Text.Encodings.Web.cs | 1 + .../Text/Unicode/UnicodeRanges.generated.cs | 9 + .../tests/UnicodeRangesTests.generated.cs | 1 + .../Common/ReflectionExtensions.cs | 4 - .../gen/JsonSourceGenerator.Parser.cs | 6 +- .../src/System/Text/Json/BitStack.cs | 2 +- .../src/System/Text/Json/JsonHelpers.Date.cs | 6 + .../Text/Json/JsonPropertyDictionary.cs | 2 +- .../src/System/Text/Json/Nodes/JsonObject.cs | 4 +- .../System/Text/Json/Nodes/JsonValueOfT.cs | 2 +- .../Text/Json/Reader/JsonReaderHelper.cs | 4 +- .../Reader/Utf8JsonReader.MultiSegment.cs | 4 +- .../System/Text/Json/Reader/Utf8JsonReader.cs | 4 +- .../Object/ObjectDefaultConverter.cs | 2 - .../src/System/Text/Json/ThrowHelper.cs | 6 + .../System/Text/Json/Writer/Utf8JsonWriter.cs | 2 +- .../tests/Common/PropertyVisibilityTests.cs | 1 + .../ContextClasses.cs | 3 +- .../JsonSerializerContextTests.cs | 1 + .../MetadataAndSerializationContextTests.cs | 2 + .../MetadataContextTests.cs | 3 + .../MixedModeContextTests.cs | 2 + .../Serialization/PropertyVisibilityTests.cs | 4 + .../SerializationContextTests.cs | 4 + ...m.Text.Json.SourceGeneration.Tests.targets | 13 +- .../CompilationHelper.cs | 6 +- .../JsonSourceGeneratorTests.cs | 2 + ...t.Json.SourceGeneration.Unit.Tests.targets | 6 +- .../JsonDocumentTests.cs | 25 + .../JsonNode/JsonObjectTests.cs | 36 + .../Utf8JsonReaderTests.TryGet.Date.cs | 18 + .../gen/RegexGenerator.Emitter.cs | 363 +- .../gen/RegexGenerator.Parser.cs | 8 +- .../gen/Resources/xlf/Strings.cs.xlf | 4 +- .../gen/Resources/xlf/Strings.de.xlf | 4 +- .../gen/Resources/xlf/Strings.es.xlf | 4 +- .../gen/Resources/xlf/Strings.fr.xlf | 4 +- .../gen/Resources/xlf/Strings.it.xlf | 4 +- .../gen/Resources/xlf/Strings.ja.xlf | 4 +- .../gen/Resources/xlf/Strings.ko.xlf | 4 +- .../gen/Resources/xlf/Strings.pl.xlf | 4 +- .../gen/Resources/xlf/Strings.pt-BR.xlf | 4 +- .../gen/Resources/xlf/Strings.ru.xlf | 4 +- .../gen/Resources/xlf/Strings.tr.xlf | 4 +- .../gen/Resources/xlf/Strings.zh-Hans.xlf | 4 +- .../gen/Resources/xlf/Strings.zh-Hant.xlf | 4 +- ...m.Text.RegularExpressions.Generator.csproj | 1 + .../System/Text/RegularExpressions/Regex.cs | 13 +- .../Text/RegularExpressions/RegexCharClass.cs | 5 +- .../Text/RegularExpressions/RegexCompiler.cs | 317 +- .../RegexFindOptimizations.cs | 76 +- .../RegularExpressions/RegexInterpreter.cs | 15 +- .../Text/RegularExpressions/RegexNode.cs | 602 ++- .../Text/RegularExpressions/RegexParser.cs | 26 +- .../RegularExpressions/RegexPrefixAnalyzer.cs | 145 +- .../Symbolic/SymbolicNFA.cs | 2 +- .../tests/Regex.KnownPattern.Tests.cs | 216 +- .../tests/Regex.Match.Tests.cs | 209 +- .../tests/RegexReductionTests.cs | 72 +- .../RegexGeneratorParserTests.cs | 24 + .../RateLimiting/ConcurrencyLimiter.cs | 23 +- .../RateLimiting/TokenBucketRateLimiter.cs | 23 +- .../tests/BaseRateLimiterTests.cs | 14 +- .../tests/ConcurrencyLimiterTests.cs | 91 +- .../tests/TokenBucketRateLimiterTests.cs | 97 +- .../src/Internal/SourceCore.cs | 2 +- .../src/Internal/SpscTargetCore.cs | 3 +- .../src/Internal/TargetCore.cs | 2 +- .../src/Internal/TargetRegistry.cs | 4 +- .../src/System/Threading/Barrier.cs | 2 +- .../src/System/Transactions/Transaction.cs | 5 +- .../System/Transactions/TransactionManager.cs | 2 +- .../System/Transactions/TransactionState.cs | 2 +- .../System/Transactions/TransactionTable.cs | 11 +- .../src/System/Web/Util/UriUtil.cs | 6 +- .../src/System/Media/SoundPlayer.cs | 2 +- .../X509Certificates/X509Utils.cs | 2 +- src/libraries/externals.csproj | 5 +- src/libraries/sendtohelix-mobile.targets | 143 + src/libraries/sendtohelix-wasm.targets | 221 + src/libraries/sendtohelixhelp.proj | 442 +- src/libraries/tests.proj | 46 +- src/mono/Directory.Build.props | 2 +- .../System.Private.CoreLib.csproj | 1 + .../src/ILLink/ILLink.Descriptors.xml | 3 + .../src/Mono/HotReload.cs | 114 + .../src/System/Math.Mono.cs | 6 - .../Reflection/Metadata/MetadataUpdater.cs | 3 +- .../src/System/Reflection/RuntimeAssembly.cs | 150 +- src/mono/cmake/config.h.in | 3 + src/mono/mono/component/CMakeLists.txt | 1 + src/mono/mono/component/debugger-agent.c | 60 +- src/mono/mono/component/debugger-engine.c | 4 +- src/mono/mono/component/debugger-stub.c | 4 +- src/mono/mono/component/debugger.h | 4 +- .../mono/component/hot_reload-internals.h | 53 + src/mono/mono/component/hot_reload-stub.c | 65 +- src/mono/mono/component/hot_reload.c | 663 ++- src/mono/mono/component/hot_reload.h | 9 +- src/mono/mono/component/mini-wasm-debugger.c | 6 +- src/mono/mono/metadata/class-accessors.c | 68 +- src/mono/mono/metadata/class-init.c | 61 +- src/mono/mono/metadata/class-inlines.h | 14 + src/mono/mono/metadata/class-internals.h | 46 +- src/mono/mono/metadata/class.c | 36 +- src/mono/mono/metadata/custom-attrs.c | 19 +- src/mono/mono/metadata/icall-decl.h | 2 - src/mono/mono/metadata/icall-def-netcore.h | 26 +- src/mono/mono/metadata/icall.c | 380 +- src/mono/mono/metadata/loader-internals.h | 12 + src/mono/mono/metadata/loader.c | 6 + src/mono/mono/metadata/metadata-update.c | 35 + src/mono/mono/metadata/metadata-update.h | 16 + src/mono/mono/metadata/metadata.c | 30 +- src/mono/mono/metadata/object-internals.h | 2 +- src/mono/mono/metadata/object.c | 8 +- src/mono/mono/metadata/sysmath.c | 50 +- src/mono/mono/mini/interp/interp.c | 24 +- src/mono/mono/mini/interp/mintops.def | 2 - src/mono/mono/mini/interp/transform.c | 69 +- src/mono/mono/mini/mini-generic-sharing.c | 28 +- src/mono/mono/mini/mini-runtime.c | 2 +- src/mono/mono/tests/bug-81673-interface.cs | 2 +- src/mono/mono/tests/bug-81673.cs | 4 +- src/mono/mono/utils/mono-error-internals.h | 1 + src/mono/nuget/mono-packages.proj | 2 +- src/mono/sample/wasm/Directory.Build.targets | 5 +- .../browser-nextjs/components/deepThought.js | 4 +- src/mono/sample/wasm/browser-webpack/app.js | 1 - src/mono/sample/wasm/browser/main.js | 16 +- .../sample/wasm/console-node-es6/main.mjs | 9 - src/mono/sample/wasm/console-node-ts/main.ts | 9 - src/mono/wasm/build/README.md | 10 + .../debugger/BrowserDebugProxy/DebugStore.cs | 31 +- .../BrowserDebugProxy/DevToolsHelper.cs | 5 +- .../BrowserDebugProxy/DevToolsProxy.cs | 2 - .../MemberReferenceResolver.cs | 3 +- .../debugger/BrowserDebugProxy/MonoProxy.cs | 127 +- .../BrowserDebugProxy/MonoSDBHelper.cs | 48 +- .../DebuggerTestSuite/BreakpointTests.cs | 253 +- .../DebuggerTestSuite/DebuggerTestBase.cs | 8 + .../EvaluateOnCallFrameTests.cs | 22 + .../debugger/DebuggerTestSuite/MiscTests.cs | 2 +- .../tests/debugger-test/debugger-driver.html | 5 +- .../debugger-test/debugger-evaluate-test.cs | 13 + .../tests/debugger-test/debugger-test.cs | 64 + .../tests/debugger-test/debugger-test.csproj | 1 + .../wasm-page-without-assets.html | 21 + src/mono/wasm/runtime/cjs/dotnet.cjs.lib.js | 14 +- src/mono/wasm/runtime/cs-to-js.ts | 45 +- src/mono/wasm/runtime/cwraps.ts | 2 +- src/mono/wasm/runtime/debug.ts | 2 +- src/mono/wasm/runtime/dotnet.d.ts | 14 +- src/mono/wasm/runtime/driver.c | 25 +- src/mono/wasm/runtime/es6/dotnet.es6.lib.js | 39 +- src/mono/wasm/runtime/exports.ts | 76 +- src/mono/wasm/runtime/imports.ts | 8 +- src/mono/wasm/runtime/memory.ts | 46 +- src/mono/wasm/runtime/method-binding.ts | 4 +- src/mono/wasm/runtime/polyfills.ts | 14 +- src/mono/wasm/runtime/roots.ts | 96 +- src/mono/wasm/runtime/startup.ts | 238 +- src/mono/wasm/runtime/types.ts | 54 +- src/mono/wasm/test-main.js | 12 +- src/native/corehost/fxr/host_context.cpp | 4 +- src/native/libs/Common/pal_config.h.in | 1 + src/native/libs/Common/pal_utilities.h | 4 + src/native/libs/System.Native/entrypoints.c | 1 + .../System.Native/pal_interfaceaddresses.c | 77 +- src/native/libs/System.Native/pal_io.c | 11 +- src/native/libs/System.Native/pal_io.h | 7 + .../pal_sslstream.c | 7 +- .../entrypoints.c | 1 + .../pal_ssl.c | 10 + .../pal_ssl.h | 12 + .../entrypoints.c | 4 + .../opensslshim.h | 8 + .../pal_evp_pkey.c | 45 +- .../pal_evp_pkey.h | 8 +- .../pal_ssl.c | 39 +- .../pal_ssl.h | 32 +- src/native/libs/build-native.sh | 9 +- src/native/libs/configure.cmake | 16 +- src/tasks/AndroidAppBuilder/ApkBuilder.cs | 2 +- .../ResolveReadyToRunCompilers.cs | 2 +- .../WasmAppBuilder/IcallTableGenerator.cs | 3 - .../installer.tasks/GenerateRunScript.cs | 4 +- .../Common/XUnitWrapperGenerator/ITestInfo.cs | 11 +- .../XUnitWrapperGenerator/TestPlatforms.cs | 2 +- .../XUnitWrapperGenerator.cs | 12 +- .../XUnitWrapperLibrary/TestOutputRecorder.cs | 34 + .../Common/XUnitWrapperLibrary/TestSummary.cs | 16 +- src/tests/Common/testenvironment.proj | 2 + src/tests/GC/API/Frozen/Frozen.cs | 188 + src/tests/GC/API/Frozen/Frozen.csproj | 16 + .../NativeClients/windows_version_helpers.h | 27 +- .../Interop/PInvoke/BestFitMapping/Test.cs | 6 +- .../UnmanagedCallersOnly/InvalidCallbacks.il | 205 +- .../UnmanagedCallersOnlyTest.cs | 3 + src/tests/JIT/Methodical/Coverage/b433189.cs | 2 +- .../Invoke/hfa_params/hfa_params.cs | 2 +- .../JIT/Methodical/NaN/arithm32_cs_r.csproj | 13 - .../JIT/Methodical/NaN/arithm32_r.csproj | 4 +- .../JIT/Methodical/NaN/arithm32_ro.csproj | 2 +- .../JIT/Methodical/NaN/arithm64_r.csproj | 5 +- .../JIT/Methodical/NaN/arithm64_ro.csproj | 1 - .../Overflow/FloatInfinitiesToInt.cs | 30 +- .../JIT/Methodical/Overflow/FloatOvfToInt2.cs | 32 +- .../JIT/Methodical/eh/basics/emptyfinally.il | 20 +- .../eh/basics/emptyfinally_il_d.ilproj | 2 +- .../eh/basics/emptyfinally_il_r.ilproj | 2 +- .../JIT/Methodical/eh/basics/multihandler.cs | 2 +- .../eh/basics/multihandler_d.csproj | 2 +- .../eh/basics/multihandler_do.csproj | 2 +- .../eh/basics/multihandler_r.csproj | 2 +- .../eh/basics/multihandler_ro.csproj | 2 +- .../JIT/Methodical/eh/basics/throwincatch.cs | 2 +- .../eh/basics/throwincatch_d.csproj | 2 +- .../eh/basics/throwincatch_do.csproj | 2 +- .../eh/basics/throwincatch_r.csproj | 2 +- .../eh/basics/throwincatch_ro.csproj | 2 +- .../basics/throwinclassconstructor_d.csproj | 2 +- .../basics/throwinclassconstructor_do.csproj | 2 +- .../basics/throwinclassconstructor_r.csproj | 2 +- .../basics/throwinclassconstructor_ro.csproj | 2 +- .../JIT/Methodical/eh/basics/throwinexcept.il | 12 +- .../eh/basics/throwinexcept_il_d.ilproj | 2 +- .../eh/basics/throwinexcept_il_r.ilproj | 2 +- .../JIT/Methodical/eh/basics/throwinfault.il | 12 +- .../eh/basics/throwinfault_il_d.ilproj | 2 +- .../eh/basics/throwinfault_il_r.ilproj | 2 +- .../JIT/Methodical/eh/basics/throwinfilter.il | 12 +- .../eh/basics/throwinfilter_il_d.ilproj | 2 +- .../eh/basics/throwinfilter_il_r.ilproj | 2 +- .../Methodical/eh/basics/throwinfinally.cs | 2 +- .../eh/basics/throwinfinally_d.csproj | 2 +- .../eh/basics/throwinfinally_do.csproj | 2 +- .../eh/basics/throwinfinally_r.csproj | 2 +- .../eh/basics/throwinfinally_ro.csproj | 2 +- .../eh/basics/throwinfinallyerrpath.cs | 2 +- .../eh/basics/throwinfinallyerrpath_d.csproj | 2 +- .../eh/basics/throwinfinallyerrpath_do.csproj | 2 +- .../eh/basics/throwinfinallyerrpath_r.csproj | 2 +- .../eh/basics/throwinfinallyerrpath_ro.csproj | 2 +- .../eh/basics/throwinfinallyerrpathfn.cs | 2 +- .../basics/throwinfinallyerrpathfn_d.csproj | 2 +- .../basics/throwinfinallyerrpathfn_do.csproj | 2 +- .../basics/throwinfinallyerrpathfn_r.csproj | 2 +- .../basics/throwinfinallyerrpathfn_ro.csproj | 2 +- .../eh/basics/throwinfinallyintryfilter1.il | 12 +- .../throwinfinallyintryfilter1_il_d.ilproj | 2 +- .../throwinfinallyintryfilter1_il_r.ilproj | 2 +- .../eh/basics/throwinfinallyintryfilter2.il | 12 +- .../throwinfinallyintryfilter2_il_d.ilproj | 2 +- .../throwinfinallyintryfilter2_il_r.ilproj | 2 +- .../eh/basics/throwinfinallyintryfilter3.il | 12 +- .../throwinfinallyintryfilter3_il_d.ilproj | 2 +- .../throwinfinallyintryfilter3_il_r.ilproj | 2 +- .../eh/basics/throwisfirstinstruction.il | 20 +- .../throwisfirstinstruction_il_d.ilproj | 2 +- .../throwisfirstinstruction_il_r.ilproj | 2 +- .../JIT/Methodical/eh/basics/throwoutside.cs | 2 +- .../eh/basics/throwoutside_d.csproj | 2 +- .../eh/basics/throwoutside_do.csproj | 2 +- .../eh/basics/throwoutside_r.csproj | 2 +- .../eh/basics/throwoutside_ro.csproj | 2 +- .../JIT/Methodical/eh/basics/trycatch.cs | 2 +- .../Methodical/eh/basics/trycatch_d.csproj | 2 +- .../Methodical/eh/basics/trycatch_do.csproj | 2 +- .../Methodical/eh/basics/trycatch_r.csproj | 2 +- .../Methodical/eh/basics/trycatch_ro.csproj | 2 +- .../Methodical/eh/basics/trycatchtrycatch.cs | 2 +- .../eh/basics/trycatchtrycatch_d.csproj | 2 +- .../eh/basics/trycatchtrycatch_do.csproj | 2 +- .../eh/basics/trycatchtrycatch_r.csproj | 2 +- .../eh/basics/trycatchtrycatch_ro.csproj | 2 +- .../JIT/Methodical/eh/basics/tryexcept.il | 12 +- .../eh/basics/tryexcept_il_d.ilproj | 2 +- .../eh/basics/tryexcept_il_r.ilproj | 2 +- .../JIT/Methodical/eh/basics/tryfault.il | 12 +- .../Methodical/eh/basics/tryfault_il_d.ilproj | 2 +- .../Methodical/eh/basics/tryfault_il_r.ilproj | 2 +- .../Methodical/eh/basics/tryfaulttrycatch.il | 12 +- .../eh/basics/tryfaulttrycatch_il_d.ilproj | 2 +- .../eh/basics/tryfaulttrycatch_il_r.ilproj | 2 +- .../eh/basics/tryfaulttrycatchfn.il | 12 +- .../eh/basics/tryfaulttrycatchfn_il_d.ilproj | 2 +- .../eh/basics/tryfaulttrycatchfn_il_r.ilproj | 2 +- .../JIT/Methodical/eh/basics/tryfinally.cs | 2 +- .../Methodical/eh/basics/tryfinally_d.csproj | 2 +- .../Methodical/eh/basics/tryfinally_do.csproj | 2 +- .../Methodical/eh/basics/tryfinally_r.csproj | 2 +- .../Methodical/eh/basics/tryfinally_ro.csproj | 2 +- .../eh/basics/tryfinallytrycatch.cs | 2 +- .../eh/basics/tryfinallytrycatch_d.csproj | 2 +- .../eh/basics/tryfinallytrycatch_do.csproj | 2 +- .../eh/basics/tryfinallytrycatch_r.csproj | 2 +- .../eh/basics/tryfinallytrycatch_ro.csproj | 2 +- .../eh/basics/tryfinallytryfinally.cs | 2 +- .../eh/basics/tryfinallytryfinally_d.csproj | 2 +- .../eh/basics/tryfinallytryfinally_do.csproj | 2 +- .../eh/basics/tryfinallytryfinally_r.csproj | 2 +- .../eh/basics/tryfinallytryfinally_ro.csproj | 2 +- .../eh/basics/tryfinallywith2endfinally.il | 20 +- .../tryfinallywith2endfinally_il_d.ilproj | 2 +- .../tryfinallywith2endfinally_il_r.ilproj | 2 +- .../tryfinallywith2reachableendfinally.il | 20 +- ...inallywith2reachableendfinally_il_d.ilproj | 2 +- ...inallywith2reachableendfinally_il_r.ilproj | 2 +- .../JIT/Methodical/eh/basics/trythrowcatch.cs | 2 +- .../eh/basics/trythrowcatch_d.csproj | 2 +- .../eh/basics/trythrowcatch_do.csproj | 2 +- .../eh/basics/trythrowcatch_r.csproj | 2 +- .../eh/basics/trythrowcatch_ro.csproj | 2 +- .../eh/basics/trythrowcatchfinally_d.csproj | 2 +- .../eh/basics/trythrowcatchfinally_do.csproj | 2 +- .../eh/basics/trythrowcatchfinally_r.csproj | 2 +- .../eh/basics/trythrowcatchfinally_ro.csproj | 2 +- .../Methodical/eh/basics/trythrowexcept.il | 12 +- .../eh/basics/trythrowexcept_il_d.ilproj | 2 +- .../eh/basics/trythrowexcept_il_r.ilproj | 2 +- .../JIT/Methodical/eh/common/common.csproj | 15 - src/tests/JIT/Methodical/eh/cs/unsafe.cs | 2 +- .../JIT/Methodical/eh/cs/unsafe_d.csproj | 2 +- .../JIT/Methodical/eh/cs/unsafe_do.csproj | 2 +- .../JIT/Methodical/eh/cs/unsafe_r.csproj | 2 +- .../JIT/Methodical/eh/cs/unsafe_ro.csproj | 2 +- .../eh/deadcode/badcodeaftercatch.il | 12 +- .../eh/deadcode/badcodeaftercatch_il_d.ilproj | 2 +- .../eh/deadcode/badcodeaftercatch_il_r.ilproj | 2 +- .../eh/deadcode/badcodeafterfault.il | 12 +- .../eh/deadcode/badcodeafterfault_il_d.ilproj | 2 +- .../eh/deadcode/badcodeafterfault_il_r.ilproj | 2 +- .../eh/deadcode/badcodeafterfilter.il | 12 +- .../deadcode/badcodeafterfilter_il_d.ilproj | 2 +- .../deadcode/badcodeafterfilter_il_r.ilproj | 2 +- .../eh/deadcode/badcodeafterfinally.il | 12 +- .../deadcode/badcodeafterfinally_il_d.ilproj | 2 +- .../deadcode/badcodeafterfinally_il_r.ilproj | 2 +- .../Methodical/eh/deadcode/badcodeaftertry.il | 12 +- .../eh/deadcode/badcodeaftertry_il_d.ilproj | 2 +- .../eh/deadcode/badcodeaftertry_il_r.ilproj | 2 +- .../eh/deadcode/badcodeinsidefinally.il | 12 +- .../deadcode/badcodeinsidefinally_il_d.ilproj | 2 +- .../deadcode/badcodeinsidefinally_il_r.ilproj | 2 +- .../eh/deadcode/branchoverendfinally.il | 20 +- .../deadcode/branchoverendfinally_il_d.ilproj | 2 +- .../deadcode/branchoverendfinally_il_r.ilproj | 2 +- .../eh/deadcode/deadEHregionacrossBB.il | 20 +- .../deadcode/deadEHregionacrossBB_il_d.ilproj | 2 +- .../deadcode/deadEHregionacrossBB_il_r.ilproj | 2 +- .../Methodical/eh/deadcode/deadcodeincatch.il | 20 +- .../eh/deadcode/deadcodeincatch_il_d.ilproj | 2 +- .../eh/deadcode/deadcodeincatch_il_r.ilproj | 2 +- .../eh/deadcode/deadnonlocalexit.il | 12 +- .../eh/deadcode/deadnonlocalexit_il_d.ilproj | 2 +- .../eh/deadcode/deadnonlocalexit_il_r.ilproj | 2 +- .../Methodical/eh/deadcode/deadoponerror.il | 12 +- .../eh/deadcode/deadoponerror_il_d.ilproj | 2 +- .../eh/deadcode/deadoponerror_il_r.ilproj | 2 +- .../eh/deadcode/deadoponerrorinfunclet.il | 20 +- .../deadoponerrorinfunclet_il_d.ilproj | 2 +- .../deadoponerrorinfunclet_il_r.ilproj | 2 +- .../eh/deadcode/deadrgninfunclet.il | 12 +- .../eh/deadcode/deadrgninfunclet_il_d.ilproj | 2 +- .../eh/deadcode/deadrgninfunclet_il_r.ilproj | 2 +- .../Methodical/eh/deadcode/deadtrycatch.il | 12 +- .../eh/deadcode/deadtrycatch_il_d.ilproj | 2 +- .../eh/deadcode/deadtrycatch_il_r.ilproj | 2 +- .../Methodical/eh/deadcode/deadtryfinally.il | 12 +- .../eh/deadcode/deadtryfinally_il_d.ilproj | 2 +- .../eh/deadcode/deadtryfinally_il_r.ilproj | 2 +- .../eh/deadcode/deadtryfinallythrow.il | 12 +- .../deadcode/deadtryfinallythrow_il_d.ilproj | 2 +- .../deadcode/deadtryfinallythrow_il_r.ilproj | 2 +- .../eh/deadcode/endfinallyinloop.il | 12 +- .../eh/deadcode/endfinallyinloop_il_d.ilproj | 2 +- .../eh/deadcode/endfinallyinloop_il_r.ilproj | 2 +- .../eh/deadcode/loopstrswitchgoto.cs | 2 +- .../eh/deadcode/loopstrswitchgoto_d.csproj | 2 +- .../eh/deadcode/loopstrswitchgoto_do.csproj | 2 +- .../eh/deadcode/loopstrswitchgoto_r.csproj | 2 +- .../eh/deadcode/loopstrswitchgoto_ro.csproj | 2 +- .../eh/deadcode/severaldeadehregions.il | 12 +- .../deadcode/severaldeadehregions_il_d.ilproj | 2 +- .../deadcode/severaldeadehregions_il_r.ilproj | 2 +- .../eh/deadcode/severalnesteddeadehregions.il | 12 +- .../severalnesteddeadehregions_il_d.ilproj | 2 +- .../severalnesteddeadehregions_il_r.ilproj | 2 +- .../eh/deadcode/simpledeadehregion.il | 12 +- .../deadcode/simpledeadehregion_il_d.ilproj | 2 +- .../deadcode/simpledeadehregion_il_r.ilproj | 2 +- .../eh/disconnected/backwardleave.il | 12 +- .../eh/disconnected/backwardleave_il_d.ilproj | 2 +- .../eh/disconnected/backwardleave_il_r.ilproj | 2 +- .../eh/disconnected/catchbeforetrybody.il | 12 +- .../catchbeforetrybody_il_d.ilproj | 2 +- .../catchbeforetrybody_il_r.ilproj | 2 +- .../eh/disconnected/catchtryintryfinally.il | 12 +- .../catchtryintryfinally_il_d.ilproj | 2 +- .../catchtryintryfinally_il_r.ilproj | 2 +- .../eh/disconnected/faultbeforetrybody.il | 12 +- .../faultbeforetrybody_il_d.ilproj | 2 +- .../faultbeforetrybody_il_r.ilproj | 2 +- .../eh/disconnected/finallybeforetrybody.il | 12 +- .../finallybeforetrybody_il_d.ilproj | 2 +- .../finallybeforetrybody_il_r.ilproj | 2 +- .../eh/disconnected/finallytryintryfinally.il | 12 +- .../finallytryintryfinally_il_d.ilproj | 2 +- .../finallytryintryfinally_il_r.ilproj | 2 +- .../eh/disconnected/reversedhandlers.il | 12 +- .../disconnected/reversedhandlers_il_d.ilproj | 2 +- .../disconnected/reversedhandlers_il_r.ilproj | 2 +- .../eh/disconnected/reversedtryblock.il | 12 +- .../disconnected/reversedtryblock_il_d.ilproj | 2 +- .../disconnected/reversedtryblock_il_r.ilproj | 2 +- .../eh/disconnected/sehhandlerbeforetry.il | 12 +- .../sehhandlerbeforetry_il_d.ilproj | 2 +- .../sehhandlerbeforetry_il_r.ilproj | 2 +- .../JIT/Methodical/eh/disconnected/testeit.il | 12 +- .../eh/disconnected/testeit_il_d.ilproj | 2 +- .../eh/disconnected/testeit_il_r.ilproj | 2 +- .../trybodyinbetweencatchhandlers.il | 12 +- .../trybodyinbetweencatchhandlers_il_d.ilproj | 2 +- .../trybodyinbetweencatchhandlers_il_r.ilproj | 2 +- .../eh/disconnected/tryfinallyincatchtry.il | 12 +- .../tryfinallyincatchtry_il_d.ilproj | 2 +- .../tryfinallyincatchtry_il_r.ilproj | 2 +- .../eh/finallyexec/catchrettoinnertry.cs | 2 +- .../eh/finallyexec/catchrettoinnertry.il | 20 +- .../catchrettoinnertry_cs_d.csproj | 2 +- .../catchrettoinnertry_cs_do.csproj | 2 +- .../catchrettoinnertry_cs_r.csproj | 2 +- .../catchrettoinnertry_cs_ro.csproj | 2 +- .../catchrettoinnertry_il_d.ilproj | 2 +- .../catchrettoinnertry_il_r.ilproj | 2 +- .../finallyexec/localgotoinahandler_d.csproj | 2 +- .../finallyexec/localgotoinahandler_do.csproj | 2 +- .../finallyexec/localgotoinahandler_r.csproj | 2 +- .../finallyexec/localgotoinahandler_ro.csproj | 2 +- .../eh/finallyexec/loopinfinally.cs | 2 +- .../eh/finallyexec/loopinfinally_d.csproj | 2 +- .../eh/finallyexec/loopinfinally_do.csproj | 2 +- .../eh/finallyexec/loopinfinally_r.csproj | 2 +- .../eh/finallyexec/loopinfinally_ro.csproj | 2 +- .../eh/finallyexec/nestedfinallycall.il | 20 +- .../finallyexec/nestedfinallycall_il_d.ilproj | 2 +- .../finallyexec/nestedfinallycall_il_r.ilproj | 2 +- .../nonlocalexittobeginningoftry.cs | 9 +- .../nonlocalexittobeginningoftry_d.csproj | 2 +- .../nonlocalexittobeginningoftry_do.csproj | 2 +- .../nonlocalexittobeginningoftry_r.csproj | 2 +- .../nonlocalexittobeginningoftry_ro.csproj | 2 +- .../nonlocalexittonestedsibling.il | 20 +- .../nonlocalexittonestedsibling_il_d.ilproj | 2 +- .../nonlocalexittonestedsibling_il_r.ilproj | 2 +- ...nonlocalgotoinatryblockinahandler_d.csproj | 2 +- ...onlocalgotoinatryblockinahandler_do.csproj | 2 +- ...nonlocalgotoinatryblockinahandler_r.csproj | 2 +- ...onlocalgotoinatryblockinahandler_ro.csproj | 2 +- .../eh/finallyexec/simplenonlocalexit.cs | 4 +- .../finallyexec/simplenonlocalexit_d.csproj | 2 +- .../finallyexec/simplenonlocalexit_do.csproj | 2 +- .../finallyexec/simplenonlocalexit_r.csproj | 2 +- .../finallyexec/simplenonlocalexit_ro.csproj | 2 +- .../simplenonlocalexitnestedintrycatch.cs | 4 +- ...implenonlocalexitnestedintrycatch_d.csproj | 2 +- ...mplenonlocalexitnestedintrycatch_do.csproj | 2 +- ...implenonlocalexitnestedintrycatch_r.csproj | 2 +- ...mplenonlocalexitnestedintrycatch_ro.csproj | 2 +- .../eh/finallyexec/switchincatch.cs | 2 +- .../eh/finallyexec/switchincatch_d.csproj | 2 +- .../eh/finallyexec/switchincatch_do.csproj | 2 +- .../eh/finallyexec/switchincatch_r.csproj | 2 +- .../eh/finallyexec/switchincatch_ro.csproj | 2 +- .../tryCatchFinallyThrow_nonlocalexit1.cs | 2 +- ...ryCatchFinallyThrow_nonlocalexit1_d.csproj | 2 +- ...yCatchFinallyThrow_nonlocalexit1_do.csproj | 2 +- ...ryCatchFinallyThrow_nonlocalexit1_r.csproj | 2 +- ...yCatchFinallyThrow_nonlocalexit1_ro.csproj | 2 +- .../tryCatchFinallyThrow_nonlocalexit2.cs | 2 +- ...ryCatchFinallyThrow_nonlocalexit2_d.csproj | 2 +- ...yCatchFinallyThrow_nonlocalexit2_do.csproj | 2 +- ...ryCatchFinallyThrow_nonlocalexit2_r.csproj | 2 +- ...yCatchFinallyThrow_nonlocalexit2_ro.csproj | 2 +- .../tryCatchFinallyThrow_nonlocalexit3.cs | 2 +- ...ryCatchFinallyThrow_nonlocalexit3_d.csproj | 2 +- ...yCatchFinallyThrow_nonlocalexit3_do.csproj | 2 +- ...ryCatchFinallyThrow_nonlocalexit3_r.csproj | 2 +- ...yCatchFinallyThrow_nonlocalexit3_ro.csproj | 2 +- .../tryCatchFinallyThrow_nonlocalexit4.cs | 2 +- ...ryCatchFinallyThrow_nonlocalexit4_d.csproj | 2 +- ...yCatchFinallyThrow_nonlocalexit4_do.csproj | 2 +- ...ryCatchFinallyThrow_nonlocalexit4_r.csproj | 2 +- ...yCatchFinallyThrow_nonlocalexit4_ro.csproj | 2 +- .../tryfinallythrow_nonlocalexit.cs | 4 +- .../tryfinallythrow_nonlocalexit_d.csproj | 2 +- .../tryfinallythrow_nonlocalexit_do.csproj | 2 +- .../tryfinallythrow_nonlocalexit_r.csproj | 2 +- .../tryfinallythrow_nonlocalexit_ro.csproj | 2 +- .../eh/generics/throwincatch_d.csproj | 2 +- .../eh/generics/throwincatch_do.csproj | 2 +- .../eh/generics/throwincatch_r.csproj | 2 +- .../eh/generics/throwincatch_ro.csproj | 2 +- .../eh/generics/trycatchnestedtype_d.csproj | 2 +- .../eh/generics/trycatchnestedtype_do.csproj | 2 +- .../eh/generics/trycatchnestedtype_r.csproj | 2 +- .../eh/generics/trycatchnestedtype_ro.csproj | 2 +- .../eh/generics/trycatchsimpletype_d.csproj | 2 +- .../eh/generics/trycatchsimpletype_do.csproj | 2 +- .../eh/generics/trycatchsimpletype_r.csproj | 2 +- .../eh/generics/trycatchsimpletype_ro.csproj | 2 +- .../Methodical/eh/interactions/gcincatch.cs | 9 +- .../eh/interactions/gcincatch_d.csproj | 2 +- .../eh/interactions/gcincatch_do.csproj | 2 +- .../eh/interactions/gcincatch_r.csproj | 2 +- .../eh/interactions/gcincatch_ro.csproj | 2 +- .../eh/interactions/rangecheckinfinally.cs | 2 +- .../interactions/rangecheckinfinally_d.csproj | 2 +- .../rangecheckinfinally_do.csproj | 2 +- .../interactions/rangecheckinfinally_r.csproj | 2 +- .../rangecheckinfinally_ro.csproj | 2 +- .../eh/interactions/strswitchfinal.cs | 2 +- .../eh/interactions/strswitchfinal_d.csproj | 2 +- .../eh/interactions/strswitchfinal_do.csproj | 2 +- .../eh/interactions/strswitchfinal_r.csproj | 2 +- .../eh/interactions/strswitchfinal_ro.csproj | 2 +- .../eh/interactions/switchinfinally.cs | 4 +- .../eh/interactions/switchinfinally_d.csproj | 2 +- .../eh/interactions/switchinfinally_do.csproj | 2 +- .../eh/interactions/switchinfinally_r.csproj | 2 +- .../eh/interactions/switchinfinally_ro.csproj | 2 +- .../eh/interactions/throw1dimarray.il | 12 +- .../interactions/throw1dimarray_il_d.ilproj | 2 +- .../interactions/throw1dimarray_il_r.ilproj | 2 +- .../eh/interactions/throw2dimarray.il | 12 +- .../interactions/throw2dimarray_il_d.ilproj | 2 +- .../interactions/throw2dimarray_il_r.ilproj | 2 +- .../eh/interactions/volatileFromFinally.cs | 2 +- .../Methodical/eh/leaves/2branchesoutoftry.il | 12 +- .../eh/leaves/2branchesoutoftry_il_d.ilproj | 2 +- .../eh/leaves/2branchesoutoftry_il_r.ilproj | 2 +- .../eh/leaves/backwardleaveincatch.il | 12 +- .../leaves/backwardleaveincatch_il_d.ilproj | 2 +- .../leaves/backwardleaveincatch_il_r.ilproj | 2 +- .../eh/leaves/branchbackwardswithcatch.il | 12 +- .../branchbackwardswithcatch_il_d.ilproj | 2 +- .../branchbackwardswithcatch_il_r.ilproj | 2 +- .../eh/leaves/branchbackwardswithfinally.il | 12 +- .../branchbackwardswithfinally_il_d.ilproj | 2 +- .../branchbackwardswithfinally_il_r.ilproj | 2 +- .../eh/leaves/branchoutofnestedtryfinally.il | 12 +- .../branchoutofnestedtryfinally_il_d.ilproj | 2 +- .../branchoutofnestedtryfinally_il_r.ilproj | 2 +- .../eh/leaves/branchoutoftryfinally.il | 12 +- .../leaves/branchoutoftryfinally_il_d.ilproj | 2 +- .../leaves/branchoutoftryfinally_il_r.ilproj | 2 +- .../leaves/catchretnonlocalexitinfunclet.cs | 2 +- .../catchretnonlocalexitinfunclet_d.csproj | 2 +- .../catchretnonlocalexitinfunclet_do.csproj | 2 +- .../catchretnonlocalexitinfunclet_r.csproj | 2 +- .../catchretnonlocalexitinfunclet_ro.csproj | 2 +- .../eh/leaves/forwardleaveincatch.il | 12 +- .../eh/leaves/forwardleaveincatch_il_d.ilproj | 2 +- .../eh/leaves/forwardleaveincatch_il_r.ilproj | 2 +- .../eh/leaves/labelbeforefinally.il | 12 +- .../eh/leaves/labelbeforefinally_il_d.ilproj | 2 +- .../eh/leaves/labelbeforefinally_il_r.ilproj | 2 +- .../eh/leaves/labelbeginningfinally.il | 12 +- .../leaves/labelbeginningfinally_il_d.ilproj | 2 +- .../leaves/labelbeginningfinally_il_r.ilproj | 2 +- .../Methodical/eh/leaves/leaveinsameregion.il | 12 +- .../eh/leaves/leaveinsameregion_il_d.ilproj | 2 +- .../eh/leaves/leaveinsameregion_il_r.ilproj | 2 +- .../Methodical/eh/leaves/leaveintotrybody.il | 12 +- .../eh/leaves/leaveintotrybody_il_d.ilproj | 2 +- .../eh/leaves/leaveintotrybody_il_r.ilproj | 2 +- .../nonlocalexitfromnestedcatch_d.csproj | 2 +- .../nonlocalexitfromnestedcatch_do.csproj | 2 +- .../nonlocalexitfromnestedcatch_r.csproj | 2 +- .../nonlocalexitfromnestedcatch_ro.csproj | 2 +- .../JIT/Methodical/eh/leaves/oponerror.cs | 2 +- .../Methodical/eh/leaves/oponerror_d.csproj | 2 +- .../Methodical/eh/leaves/oponerror_do.csproj | 2 +- .../Methodical/eh/leaves/oponerror_r.csproj | 2 +- .../Methodical/eh/leaves/oponerror_ro.csproj | 2 +- .../tryfinallyintrycatchwithleaveintotry.il | 12 +- ...allyintrycatchwithleaveintotry_il_d.ilproj | 2 +- ...allyintrycatchwithleaveintotry_il_r.ilproj | 2 +- .../Methodical/eh/leaves/tryfinallyloop.cs | 2 +- .../eh/leaves/tryfinallyloop_d.csproj | 2 +- .../eh/leaves/tryfinallyloop_do.csproj | 2 +- .../eh/leaves/tryfinallyloop_r.csproj | 2 +- .../eh/leaves/tryfinallyloop_ro.csproj | 2 +- .../eh/mixedhandler/catchfiltercatch.il | 12 +- .../mixedhandler/catchfiltercatch_il_d.ilproj | 2 +- .../mixedhandler/catchfiltercatch_il_r.ilproj | 2 +- .../eh/mixedhandler/filterfiltercatchcatch.il | 12 +- .../filterfiltercatchcatch_il_d.ilproj | 2 +- .../filterfiltercatchcatch_il_r.ilproj | 2 +- .../nested/cascadedcatchret/cascadedcatch.il | 12 +- .../cascadedcatch_il_d.ilproj | 2 +- .../cascadedcatch_il_r.ilproj | 2 +- .../nested/cascadedcatchret/cascadedexcept.il | 12 +- .../cascadedexcept_il_d.ilproj | 2 +- .../cascadedexcept_il_r.ilproj | 2 +- .../cascadedcatchret/throwincascadedcatch.il | 12 +- .../throwincascadedcatch_il_d.ilproj | 2 +- .../throwincascadedcatch_il_r.ilproj | 2 +- .../throwincascadedcatchnofin.il | 12 +- .../throwincascadedcatchnofin_il_d.ilproj | 2 +- .../throwincascadedcatchnofin_il_r.ilproj | 2 +- .../cascadedcatchret/throwincascadedexcept.il | 12 +- .../throwincascadedexcept_il_d.ilproj | 2 +- .../throwincascadedexcept_il_r.ilproj | 2 +- .../throwincascadedexceptnofin.il | 12 +- .../throwincascadedexceptnofin_il_d.ilproj | 2 +- .../throwincascadedexceptnofin_il_r.ilproj | 2 +- .../eh/nested/general/cascadedcatch.cs | 4 +- .../eh/nested/general/cascadedcatch_d.csproj | 2 +- .../eh/nested/general/cascadedcatch_do.csproj | 2 +- .../eh/nested/general/cascadedcatch_r.csproj | 2 +- .../eh/nested/general/cascadedcatch_ro.csproj | 2 +- .../eh/nested/general/localvarincatch.il | 12 +- .../general/localvarincatch_il_d.ilproj | 2 +- .../general/localvarincatch_il_r.ilproj | 2 +- .../nested/general/methodthrowsinfinally.cs | 2 +- .../general/methodthrowsinfinally_d.csproj | 2 +- .../general/methodthrowsinfinally_do.csproj | 2 +- .../general/methodthrowsinfinally_r.csproj | 2 +- .../general/methodthrowsinfinally_ro.csproj | 2 +- .../general/rethrowincatchnestedinfinally.cs | 2 +- .../rethrowincatchnestedinfinally_d.csproj | 2 +- .../rethrowincatchnestedinfinally_do.csproj | 2 +- .../rethrowincatchnestedinfinally_r.csproj | 2 +- .../rethrowincatchnestedinfinally_ro.csproj | 2 +- .../eh/nested/general/throwinfinally.cs | 2 +- .../eh/nested/general/throwinfinally_d.csproj | 2 +- .../nested/general/throwinfinally_do.csproj | 2 +- .../eh/nested/general/throwinfinally_r.csproj | 2 +- .../nested/general/throwinfinally_ro.csproj | 2 +- .../general/throwinfinallynestedintry.cs | 2 +- .../throwinfinallynestedintry_d.csproj | 2 +- .../throwinfinallynestedintry_do.csproj | 2 +- .../throwinfinallynestedintry_r.csproj | 2 +- .../throwinfinallynestedintry_ro.csproj | 2 +- .../eh/nested/general/throwinnestedcatch.il | 20 +- .../general/throwinnestedcatch_il_d.ilproj | 2 +- .../general/throwinnestedcatch_il_r.ilproj | 2 +- .../eh/nested/general/throwinnestedfinally.cs | 2 +- .../general/throwinnestedfinally_d.csproj | 2 +- .../general/throwinnestedfinally_do.csproj | 2 +- .../general/throwinnestedfinally_r.csproj | 2 +- .../general/throwinnestedfinally_ro.csproj | 2 +- .../eh/nested/general/trycatchintryfinally.cs | 2 +- .../general/trycatchintryfinally_d.csproj | 2 +- .../general/trycatchintryfinally_do.csproj | 2 +- .../general/trycatchintryfinally_r.csproj | 2 +- .../general/trycatchintryfinally_ro.csproj | 2 +- .../eh/nested/nestedtry/nestedtrycatch.il | 12 +- .../nestedtry/nestedtrycatch_il_d.ilproj | 2 +- .../nestedtry/nestedtrycatch_il_r.ilproj | 2 +- .../eh/nested/nestedtry/nestedtryexcept.il | 12 +- .../nestedtry/nestedtryexcept_il_d.ilproj | 2 +- .../nestedtry/nestedtryexcept_il_r.ilproj | 2 +- .../eh/nested/nestedtry/nestedtryfault.il | 12 +- .../nestedtry/nestedtryfault_il_d.ilproj | 2 +- .../nestedtry/nestedtryfault_il_r.ilproj | 2 +- .../eh/nested/nestedtry/nestedtryfinally.il | 12 +- .../nestedtry/nestedtryfinally_il_d.ilproj | 2 +- .../nestedtry/nestedtryfinally_il_r.ilproj | 2 +- .../nested/nestedtry/throwinnestedtrycatch.il | 12 +- .../throwinnestedtrycatch_il_d.ilproj | 2 +- .../throwinnestedtrycatch_il_r.ilproj | 2 +- .../nestedtry/throwinnestedtryexcept.il | 12 +- .../throwinnestedtryexcept_il_d.ilproj | 2 +- .../throwinnestedtryexcept_il_r.ilproj | 2 +- .../nested/nestedtry/throwinnestedtryfault.il | 12 +- .../throwinnestedtryfault_il_d.ilproj | 2 +- .../throwinnestedtryfault_il_r.ilproj | 2 +- .../nestedtry/throwinnestedtryfinally.il | 12 +- .../throwinnestedtryfinally_il_d.ilproj | 2 +- .../throwinnestedtryfinally_il_r.ilproj | 2 +- .../nested/nonlocalexit/throwinfinally_50.cs | 2 +- .../nonlocalexit/throwinfinally_50_d.csproj | 2 +- .../nonlocalexit/throwinfinally_50_do.csproj | 2 +- .../nonlocalexit/throwinfinally_50_r.csproj | 2 +- .../nonlocalexit/throwinfinally_50_ro.csproj | 2 +- .../throwinfinallynestedintry_30.cs | 2 +- .../throwinfinallynestedintry_30_d.csproj | 2 +- .../throwinfinallynestedintry_30_do.csproj | 2 +- .../throwinfinallynestedintry_30_r.csproj | 2 +- .../throwinfinallynestedintry_30_ro.csproj | 2 +- .../throwinfinallyrecursive_20.cs | 2 +- .../throwinfinallyrecursive_20_d.csproj | 2 +- .../throwinfinallyrecursive_20_do.csproj | 2 +- .../throwinfinallyrecursive_20_r.csproj | 2 +- .../throwinfinallyrecursive_20_ro.csproj | 2 +- .../regress/asurt/122239/outermostFinally.cs | 2 +- .../asurt/122239/outermostFinally.csproj | 2 +- .../eh/regress/asurt/140713/innerFinally.cs | 2 +- .../asurt/140713/innerFinally_d.csproj | 2 +- .../asurt/140713/innerFinally_do.csproj | 2 +- .../asurt/140713/innerFinally_r.csproj | 2 +- .../asurt/140713/innerFinally_ro.csproj | 2 +- .../asurt/141358/uncaughtException_d.csproj | 2 +- .../asurt/141358/uncaughtException_do.csproj | 2 +- .../asurt/141358/uncaughtException_r.csproj | 2 +- .../asurt/141358/uncaughtException_ro.csproj | 2 +- .../regress/vswhidbey/148190/baduwinfo.csproj | 2 +- .../vswhidbey/148190/baduwinfo1.csproj | 2 +- .../eh/rethrow/rethrowinfinallyaftercatch.cs | 2 +- .../rethrowinfinallyaftercatch_d.csproj | 2 +- .../rethrowinfinallyaftercatch_do.csproj | 2 +- .../rethrowinfinallyaftercatch_r.csproj | 2 +- .../rethrowinfinallyaftercatch_ro.csproj | 2 +- .../eh/rethrow/rethrowinfinallyinsidecatch.il | 20 +- .../rethrowinfinallyinsidecatch_il_d.ilproj | 2 +- .../rethrowinfinallyinsidecatch_il_r.ilproj | 32 +- .../rethrowwithhandlerscatchingbase.cs | 2 +- .../rethrowwithhandlerscatchingbase_d.csproj | 2 +- .../rethrowwithhandlerscatchingbase_do.csproj | 2 +- .../rethrowwithhandlerscatchingbase_r.csproj | 2 +- .../rethrowwithhandlerscatchingbase_ro.csproj | 2 +- .../Methodical/eh/rethrow/samerethrowtwice.cs | 2 +- .../eh/rethrow/samerethrowtwice_d.csproj | 2 +- .../eh/rethrow/samerethrowtwice_do.csproj | 2 +- .../eh/rethrow/samerethrowtwice_r.csproj | 2 +- .../eh/rethrow/samerethrowtwice_ro.csproj | 2 +- .../Methodical/eh/rethrow/samethrowtwice.cs | 2 +- .../eh/rethrow/samethrowtwice_d.csproj | 2 +- .../eh/rethrow/samethrowtwice_do.csproj | 2 +- .../eh/rethrow/samethrowtwice_r.csproj | 2 +- .../eh/rethrow/samethrowtwice_ro.csproj | 2 +- .../Methodical/eh/rethrow/simplerethrow.cs | 2 +- .../eh/rethrow/simplerethrow_d.csproj | 2 +- .../eh/rethrow/simplerethrow_do.csproj | 2 +- .../eh/rethrow/simplerethrow_r.csproj | 2 +- .../eh/rethrow/simplerethrow_ro.csproj | 2 +- .../rethrow/throwwithhandlerscatchingbase.cs | 2 +- .../throwwithhandlerscatchingbase_d.csproj | 2 +- .../throwwithhandlerscatchingbase_do.csproj | 2 +- .../throwwithhandlerscatchingbase_r.csproj | 2 +- .../throwwithhandlerscatchingbase_ro.csproj | 2 +- .../flowgraph/bug614098/intToByte.cs | 2 +- .../flowgraph/bug619534/finallyclone.cs | 2 +- .../flowgraph/bug619534/twoEndFinallys.cs | 4 +- .../dev10_bug675304/osrAddovershot.cs | 2 +- .../flowgraph/dev10_bug723489/qMarkColon.cs | 7 +- .../JIT/Methodical/fp/apps/BouncingBall.cs | 14 +- .../Methodical/inlining/boolean/InlineBool.cs | 2 +- .../localloc/call/call01_small.csproj | 2 +- .../JIT/Methodical/nonvirtualcall/classic.cs | 2 +- .../JIT/Methodical/nonvirtualcall/classic.il | 18 +- .../JIT/Methodical/nonvirtualcall/delegate.cs | 2 +- .../JIT/Methodical/nonvirtualcall/delegate.il | 20 +- .../JIT/Methodical/nonvirtualcall/generics.cs | 2 +- .../JIT/Methodical/nonvirtualcall/generics.il | 18 +- .../Methodical/nonvirtualcall/generics2.cs | 2 +- .../Methodical/nonvirtualcall/generics2.il | 20 +- .../JIT/Methodical/nonvirtualcall/tailcall.cs | 2 +- .../JIT/Methodical/nonvirtualcall/tailcall.il | 18 +- .../Methodical/nonvirtualcall/valuetype.cs | 2 +- .../Methodical/nonvirtualcall/valuetype.il | 17 +- .../JIT/Methodical/stringintern/test1.cs | 110 +- .../JIT/Methodical/stringintern/test2.cs | 125 +- .../JIT/Methodical/stringintern/test4.cs | 264 +- .../structs/StructWithSingleFloat.cs | 2 +- .../JitBlue/Runtime_33972/Runtime_33972.cs | 559 ++ .../Runtime_33972/Runtime_33972.csproj} | 4 +- .../JitBlue/Runtime_34587/Runtime_34587.cs | 130 + .../JitBlue/Runtime_60035/Runtime_60035.cs | 19 + .../Runtime_60035/Runtime_60035.csproj} | 7 +- .../JitBlue/Runtime_62108/Runtime_62108.cs | 43 + .../Runtime_62108/Runtime_62108.csproj | 17 + .../JitBlue/Runtime_63610/Runtime_63610.cs | 42 + .../Runtime_63610/Runtime_63610.csproj | 9 + .../JitBlue/Runtime_63942/Runtime_63942.cs | 13 + .../Runtime_63942/Runtime_63942.csproj | 21 + .../VS-ia64-JIT/V1.2-M01/b14324/b14324.ilproj | 2 +- .../VS-ia64-JIT/V1.2-M01/b14324/repro.il | 6 +- .../VS-ia64-JIT/V1.2-M02/b14355/b14355.ilproj | 2 +- .../VS-ia64-JIT/V1.2-M02/b14355/call01.il | 36 +- src/tests/JIT/Stress/ABI/Callee.cs | 14 +- src/tests/JIT/Stress/ABI/Config.cs | 2 +- src/tests/JIT/Stress/ABI/Program.cs | 8 +- src/tests/JIT/Stress/ABI/Stubs.cs | 6 +- .../common/common.cs => common/eh_common.cs} | 36 +- src/tests/JIT/common/eh_common.csproj | 9 + .../common.il => common/localloc_common.il} | 3 +- .../localloc_common.ilproj} | 0 src/tests/JIT/jit64/eh/Common/common.cs | 279 - src/tests/JIT/jit64/eh/Common/common.csproj | 14 - .../nestedTryRegionsWithSameOffset1.csproj | 2 +- .../nestedTryRegionsWithSameOffset1_o.csproj | 2 +- .../nestedTryRegionsWithSameOffset2.csproj | 2 +- .../nestedTryRegionsWithSameOffset2_o.csproj | 2 +- .../nestedTryRegionsWithSameOffset3.csproj | 2 +- .../nestedTryRegionsWithSameOffset3_o.csproj | 2 +- .../eh/FinallyExec/nonlocalexitincatch.il | 12 +- .../eh/FinallyExec/nonlocalexitincatch.ilproj | 2 +- .../eh/FinallyExec/nonlocalexitinfinally.il | 12 +- .../FinallyExec/nonlocalexitinfinally.ilproj | 2 +- .../eh/FinallyExec/nonlocalexitinhandler.il | 12 +- .../FinallyExec/nonlocalexitinhandler.ilproj | 2 +- .../eh/FinallyExec/nonlocalexitinroot.il | 12 +- .../eh/FinallyExec/nonlocalexitinroot.ilproj | 2 +- .../jit64/eh/FinallyExec/nonlocalexitintry.il | 12 +- .../eh/FinallyExec/nonlocalexitintry.ilproj | 2 +- .../nonlocalgotoinatryblockinahandler.csproj | 2 +- .../Leaves/nonlocalexitfromnestedcatch.csproj | 2 +- .../eh/basics/throwinfinallyintryfilter1.il | 12 +- .../basics/throwinfinallyintryfilter1.ilproj | 2 +- .../eh/basics/throwinfinallyintryfilter2.il | 12 +- .../basics/throwinfinallyintryfilter2.ilproj | 2 +- .../eh/basics/throwinfinallyintryfilter3.il | 12 +- .../basics/throwinfinallyintryfilter3.ilproj | 2 +- .../eh/basics/throwisfirstinstruction.il | 20 +- .../eh/basics/throwisfirstinstruction.ilproj | 2 +- .../JIT/jit64/localloc/call/call05_dynamic.il | 28 +- .../jit64/localloc/call/call05_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/call/call05_large.il | 18 +- .../jit64/localloc/call/call05_large.ilproj | 2 +- .../JIT/jit64/localloc/call/call05_small.il | 18 +- .../jit64/localloc/call/call05_small.ilproj | 2 +- .../JIT/jit64/localloc/call/call07_dynamic.il | 52 +- .../jit64/localloc/call/call07_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/call/call07_small.il | 40 +- .../jit64/localloc/call/call07_small.ilproj | 2 +- .../JIT/jit64/localloc/eh/eh01_dynamic.csproj | 2 +- .../JIT/jit64/localloc/eh/eh01_large.csproj | 2 +- .../JIT/jit64/localloc/eh/eh01_small.csproj | 2 +- .../JIT/jit64/localloc/eh/eh02_dynamic.csproj | 2 +- .../JIT/jit64/localloc/eh/eh02_large.csproj | 2 +- .../JIT/jit64/localloc/eh/eh02_small.csproj | 2 +- .../JIT/jit64/localloc/eh/eh03_dynamic.il | 28 +- .../JIT/jit64/localloc/eh/eh03_dynamic.ilproj | 2 +- src/tests/JIT/jit64/localloc/eh/eh03_large.il | 22 +- .../JIT/jit64/localloc/eh/eh03_large.ilproj | 2 +- src/tests/JIT/jit64/localloc/eh/eh03_small.il | 22 +- .../JIT/jit64/localloc/eh/eh03_small.ilproj | 2 +- .../JIT/jit64/localloc/eh/eh04_dynamic.il | 24 +- .../JIT/jit64/localloc/eh/eh04_dynamic.ilproj | 2 +- src/tests/JIT/jit64/localloc/eh/eh04_large.il | 18 +- .../JIT/jit64/localloc/eh/eh04_large.ilproj | 2 +- src/tests/JIT/jit64/localloc/eh/eh04_small.il | 18 +- .../JIT/jit64/localloc/eh/eh04_small.ilproj | 2 +- .../JIT/jit64/localloc/eh/eh05_dynamic.csproj | 2 +- .../JIT/jit64/localloc/eh/eh05_large.csproj | 2 +- .../JIT/jit64/localloc/eh/eh05_small.csproj | 2 +- .../jit64/localloc/ehverify/eh05_dynamic.il | 4 +- .../localloc/ehverify/eh05_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh05_large.il | 2 +- .../JIT/jit64/localloc/ehverify/eh05_small.il | 2 +- .../jit64/localloc/ehverify/eh06_dynamic.il | 4 +- .../localloc/ehverify/eh06_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh06_large.il | 2 +- .../JIT/jit64/localloc/ehverify/eh06_small.il | 2 +- .../jit64/localloc/ehverify/eh07_dynamic.il | 4 +- .../localloc/ehverify/eh07_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh07_large.il | 2 +- .../jit64/localloc/ehverify/eh07_large.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh07_small.il | 2 +- .../jit64/localloc/ehverify/eh07_small.ilproj | 2 +- .../jit64/localloc/ehverify/eh08_dynamic.il | 4 +- .../localloc/ehverify/eh08_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh08_large.il | 2 +- .../JIT/jit64/localloc/ehverify/eh08_small.il | 2 +- .../localloc/ehverify/eh09_dynamic.csproj | 2 +- .../jit64/localloc/ehverify/eh09_large.csproj | 2 +- .../jit64/localloc/ehverify/eh09_small.csproj | 2 +- .../jit64/localloc/ehverify/eh11_dynamic.il | 24 +- .../localloc/ehverify/eh11_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh11_large.il | 18 +- .../jit64/localloc/ehverify/eh11_large.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh11_small.il | 18 +- .../jit64/localloc/ehverify/eh11_small.ilproj | 2 +- .../jit64/localloc/ehverify/eh12_dynamic.il | 24 +- .../localloc/ehverify/eh12_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh12_large.il | 18 +- .../jit64/localloc/ehverify/eh12_large.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh12_small.il | 18 +- .../jit64/localloc/ehverify/eh12_small.ilproj | 2 +- .../jit64/localloc/ehverify/eh13_dynamic.il | 24 +- .../localloc/ehverify/eh13_dynamic.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh13_large.il | 18 +- .../jit64/localloc/ehverify/eh13_large.ilproj | 2 +- .../JIT/jit64/localloc/ehverify/eh13_small.il | 18 +- .../jit64/localloc/ehverify/eh13_small.ilproj | 2 +- .../localloc/unwind/unwind01_dynamic.csproj | 2 +- .../localloc/unwind/unwind01_large.csproj | 2 +- .../localloc/unwind/unwind01_small.csproj | 2 +- .../localloc/unwind/unwind02_dynamic.csproj | 2 +- .../localloc/unwind/unwind02_large.csproj | 2 +- .../localloc/unwind/unwind02_small.csproj | 2 +- .../localloc/unwind/unwind03_dynamic.csproj | 2 +- .../localloc/unwind/unwind03_large.csproj | 2 +- .../localloc/unwind/unwind03_small.csproj | 2 +- .../jit64/localloc/unwind/unwind04_dynamic.il | 26 +- .../localloc/unwind/unwind04_dynamic.ilproj | 2 +- .../jit64/localloc/unwind/unwind04_large.il | 18 +- .../localloc/unwind/unwind04_large.ilproj | 2 +- .../jit64/localloc/unwind/unwind04_small.il | 18 +- .../localloc/unwind/unwind04_small.ilproj | 2 +- .../jit64/localloc/unwind/unwind05_dynamic.il | 26 +- .../localloc/unwind/unwind05_dynamic.ilproj | 2 +- .../jit64/localloc/unwind/unwind05_large.il | 18 +- .../localloc/unwind/unwind05_large.ilproj | 2 +- .../jit64/localloc/unwind/unwind05_small.il | 18 +- .../localloc/unwind/unwind05_small.ilproj | 2 +- .../jit64/localloc/unwind/unwind06_dynamic.il | 26 +- .../localloc/unwind/unwind06_dynamic.ilproj | 2 +- .../jit64/localloc/unwind/unwind06_large.il | 18 +- .../localloc/unwind/unwind06_large.ilproj | 2 +- .../jit64/localloc/unwind/unwind06_small.il | 18 +- .../localloc/unwind/unwind06_small.ilproj | 2 +- .../JIT/opt/IsKnownConstant/StringEquals.cs | 99 + .../IsKnownConstant/StringEquals.csproj} | 7 +- .../Regressions/empty/explicitStruct_empty.cs | 60 + .../empty/explicitStruct_empty.csproj | 5 + .../coreclr/GitHub_61104/test61104.cs | 12 + .../coreclr/GitHub_61104/test61104.csproj | 17 + src/tests/issues.targets | 3 + .../nativeaot/SmokeTests/PInvoke/PInvoke.cs | 32 + .../SmokeTests/PInvoke/PInvokeNative.cpp | 11 + .../profiler/native/gcprofiler/gcprofiler.cpp | 18 + .../profiler/native/gcprofiler/gcprofiler.h | 3 + 2116 files changed, 38346 insertions(+), 14127 deletions(-) create mode 100644 docs/pr-builds.md create mode 100644 docs/workflow/debugging/coreclr/debuging-compiler-dependency-analysis.md delete mode 100644 eng/common/generate-graph-files.ps1 delete mode 100644 eng/common/templates/job/generate-graph-files.yml create mode 100644 eng/common/templates/jobs/codeql-build.yml delete mode 100644 eng/common/templates/post-build/channels/generic-internal-channel.yml delete mode 100644 eng/common/templates/post-build/channels/generic-public-channel.yml create mode 100644 eng/common/templates/steps/execute-codeql.yml rename eng/pipelines/{runtime-manual.yml => runtime-extra-platforms.yml} (59%) create mode 100644 eng/testing/default.rd.xml delete mode 100644 src/coreclr/ToolBox/CMakeLists.txt delete mode 100644 src/coreclr/pal/src/cruntime/path.cpp delete mode 100644 src/coreclr/pal/src/cruntime/wchartls.cpp delete mode 100644 src/coreclr/pal/src/include/pal/modulename.h delete mode 100644 src/coreclr/pal/src/loader/modulename.cpp delete mode 100644 src/coreclr/pal/src/memory/local.cpp delete mode 100644 src/coreclr/pal/tests/palsuite/c_runtime/wcstok/test1/test1.cpp delete mode 100644 src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalAlloc/test1/LocalAlloc.cpp delete mode 100644 src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalFree/test1/LocalFree.cpp delete mode 100644 src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalFree/test2/LocalFree.cpp rename src/coreclr/{ToolBox => tools}/SOS/CMakeLists.txt (100%) rename src/coreclr/{ToolBox => tools}/SOS/DIALib/DIALib.il (100%) rename src/coreclr/{ToolBox => tools}/SOS/DIALib/DIALib.ilproj (100%) rename src/coreclr/{ToolBox => tools}/SOS/DacTableGen/DacTableGen.csproj (100%) rename src/coreclr/{ToolBox => tools}/SOS/DacTableGen/MapSymbolProvider.cs (100%) rename src/coreclr/{ToolBox => tools}/SOS/DacTableGen/cvconst.cs (100%) rename src/coreclr/{ToolBox => tools}/SOS/DacTableGen/diautil.cs (100%) rename src/coreclr/{ToolBox => tools}/SOS/DacTableGen/main.cs (100%) rename src/coreclr/{ToolBox => tools}/SOS/Directory.Build.props (100%) rename src/coreclr/{ToolBox => tools}/SOS/SOS_README.md (100%) create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSettings.cs create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessXmlBase.cs create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/BodySubstitutionParser.cs create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/DescriptorMarker.cs create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/FeatureSettings.cs create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/LinkAttributesParser.cs create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/ProcessLinkerXmlBase.cs create mode 100644 src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/README.md rename src/coreclr/{ToolBox => tools}/superpmi/.clang-format (100%) rename src/coreclr/{ToolBox => tools}/superpmi/CMakeLists.txt (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/CMakeLists.txt (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/commandline.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/commandline.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/mcs.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/mcs.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/removedup.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/removedup.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbasmdump.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbasmdump.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbconcat.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbconcat.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbdump.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbdump.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbdumpmap.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbdumpmap.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbdumptoc.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbdumptoc.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbfracture.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbfracture.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbildump.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbildump.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbinteg.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbinteg.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbjitflags.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbjitflags.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbmerge.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbmerge.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbprintjiteeversion.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbprintjiteeversion.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbremovedup.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbremovedup.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbstat.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbstat.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbstrip.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbstrip.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbtoc.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/mcs/verbtoc.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/readme.md (99%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/agnostic.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/asmdumper.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/asmdumper.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/callutils.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/callutils.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/compileresult.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/compileresult.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/crlwmlist.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/errorhandling.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/errorhandling.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/hash.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/hash.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/icorjitcompilerimpl.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/icorjithostimpl.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/icorjitinfoimpl.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/lightweightmap.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/logging.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/logging.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/lwmlist.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/mclist.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/mclist.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/methodcontext.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/methodcontext.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/methodcontextiterator.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/methodcontextiterator.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/methodcontextreader.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/methodcontextreader.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/runtimedetails.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/simpletimer.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/simpletimer.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/spmidumphelper.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/spmidumphelper.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/spmirecordhelper.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/spmiutil.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/spmiutil.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/standardpch.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/tocfile.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/tocfile.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/typeutils.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shared/typeutils.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/CMakeLists.txt (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/icorjitcompiler.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/icorjitcompiler.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/icorjitinfo.cpp (99%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/icorjitinfo.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/jithost.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/jithost.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/superpmi-shim-collector.def (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-collector/superpmi-shim-collector.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/CMakeLists.txt (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/icorjitcompiler.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/icorjitcompiler.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/icorjitinfo.cpp (99%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/icorjitinfo.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/jithost.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/jithost.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/methodcallsummarizer.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/methodcallsummarizer.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/superpmi-shim-counter.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/superpmi-shim-counter.def (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-counter/superpmi-shim-counter.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/CMakeLists.txt (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/icorjitcompiler.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/icorjitcompiler.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/icorjitinfo.cpp (99%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/icorjitinfo.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/jithost.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/jithost.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/superpmi-shim-simple.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/superpmi-shim-simple.def (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi-shim-simple/superpmi-shim-simple.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/CMakeLists.txt (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/commandline.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/commandline.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/cycletimer.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/cycletimer.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/icorjitinfo.cpp (99%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/icorjitinfo.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/jitdebugger.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/jitdebugger.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/jithost.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/jithost.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/jitinstance.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/jitinstance.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/methodstatsemitter.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/methodstatsemitter.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/metricssummary.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/metricssummary.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/neardiffer.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/neardiffer.h (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/parallelsuperpmi.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/superpmi.cpp (100%) rename src/coreclr/{ToolBox => tools}/superpmi/superpmi/superpmi.h (100%) delete mode 100644 src/coreclr/vm/h2inc.pl delete mode 100644 src/coreclr/vm/h2inc.ps1 delete mode 100644 src/coreclr/vm/notifyexternals.cpp delete mode 100644 src/coreclr/vm/notifyexternals.h create mode 100644 src/libraries/Microsoft.Extensions.Configuration/src/ReferenceCountedProviders.cs create mode 100644 src/libraries/Microsoft.Extensions.Configuration/src/ReferenceCountedProvidersManager.cs create mode 100644 src/libraries/Microsoft.Extensions.Http/tests/Microsoft.Extensions.Http.Tests/Logging/LoggingUriOutputTests.cs create mode 100644 src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/.editorconfig create mode 100644 src/libraries/System.Collections/tests/default.rd.xml create mode 100644 src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPGlobalProperties.cs create mode 100644 src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPGlobalStatistics.cs create mode 100644 src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPInterfaceProperties.cs create mode 100644 src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPv4InterfaceProperties.cs create mode 100644 src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPv6InterfaceProperties.cs create mode 100644 src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidNetworkInterface.cs create mode 100644 src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalPropertiesPal.Android.cs create mode 100644 src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkInterfacePal.Android.cs create mode 100644 src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/IPInterfacePropertiesTest_Android.cs create mode 100644 src/libraries/System.Private.CoreLib/src/System/Environment.iOS.cs create mode 100644 src/libraries/System.Private.CoreLib/src/System/ProbabilisticMap.cs create mode 100644 src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/CachedCompletedInt32Task.cs create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/AddNestedClass.cs create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/AddNestedClass_v1.cs create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass.csproj create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/deltascript.json create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/AddStaticField.cs create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/AddStaticField_v1.cs create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField.csproj create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/deltascript.json create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/AddStaticLambda.cs create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/AddStaticLambda_v1.cs create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda.csproj create mode 100644 src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/deltascript.json create mode 100644 src/libraries/System.Runtime/tests/default.rd.xml create mode 100644 src/libraries/sendtohelix-mobile.targets create mode 100644 src/libraries/sendtohelix-wasm.targets create mode 100644 src/mono/System.Private.CoreLib/src/Mono/HotReload.cs create mode 100644 src/mono/mono/component/hot_reload-internals.h create mode 100644 src/mono/wasm/debugger/tests/debugger-test/wasm-page-without-assets.html create mode 100644 src/tests/Common/XUnitWrapperLibrary/TestOutputRecorder.cs create mode 100644 src/tests/GC/API/Frozen/Frozen.cs create mode 100644 src/tests/GC/API/Frozen/Frozen.csproj delete mode 100644 src/tests/JIT/Methodical/NaN/arithm32_cs_r.csproj delete mode 100644 src/tests/JIT/Methodical/eh/common/common.csproj create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_33972/Runtime_33972.cs rename src/tests/JIT/{Methodical/NaN/arithm32_cs_ro.csproj => Regression/JitBlue/Runtime_33972/Runtime_33972.csproj} (71%) create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.cs rename src/tests/JIT/{Methodical/NaN/arithm64_cs_ro.csproj => Regression/JitBlue/Runtime_60035/Runtime_60035.csproj} (67%) create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_62108/Runtime_62108.cs create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_62108/Runtime_62108.csproj create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_63610/Runtime_63610.cs create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_63610/Runtime_63610.csproj create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_63942/Runtime_63942.cs create mode 100644 src/tests/JIT/Regression/JitBlue/Runtime_63942/Runtime_63942.csproj rename src/tests/JIT/{Methodical/eh/common/common.cs => common/eh_common.cs} (89%) create mode 100644 src/tests/JIT/common/eh_common.csproj rename src/tests/JIT/{jit64/localloc/common/common.il => common/localloc_common.il} (99%) rename src/tests/JIT/{jit64/localloc/common/common.ilproj => common/localloc_common.ilproj} (100%) delete mode 100644 src/tests/JIT/jit64/eh/Common/common.cs delete mode 100644 src/tests/JIT/jit64/eh/Common/common.csproj create mode 100644 src/tests/JIT/opt/IsKnownConstant/StringEquals.cs rename src/tests/JIT/{Methodical/NaN/arithm64_cs_r.csproj => opt/IsKnownConstant/StringEquals.csproj} (51%) create mode 100644 src/tests/Loader/classloader/explicitlayout/Regressions/empty/explicitStruct_empty.cs create mode 100644 src/tests/Loader/classloader/explicitlayout/Regressions/empty/explicitStruct_empty.csproj create mode 100644 src/tests/Regressions/coreclr/GitHub_61104/test61104.cs create mode 100644 src/tests/Regressions/coreclr/GitHub_61104/test61104.csproj diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 978b716216ae9..0e5219042b700 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -15,7 +15,7 @@ ] }, "microsoft.dotnet.xharness.cli": { - "version": "1.0.0-prerelease.22053.2", + "version": "1.0.0-prerelease.22067.1", "commands": [ "xharness" ] diff --git a/.github/fabricbot.json b/.github/fabricbot.json index 72acfd8440a06..723e3f5c493f2 100644 --- a/.github/fabricbot.json +++ b/.github/fabricbot.json @@ -996,7 +996,7 @@ "subCapability": "IssueCommentResponder", "version": "1.0", "config": { - "taskName": "Replace `needs more info` label with `needs further triage` label when the author comments on an issue", + "taskName": "Replace `needs-author-action` label with `needs further triage` label when the author comments on an issue", "conditions": { "operator": "and", "operands": [ @@ -1017,7 +1017,7 @@ { "name": "hasLabel", "parameters": { - "label": "needs more info" + "label": "needs-author-action" } }, { @@ -1036,7 +1036,7 @@ { "name": "removeLabel", "parameters": { - "label": "needs more info" + "label": "needs-author-action" } } ], @@ -1575,7 +1575,7 @@ { "name": "hasLabel", "parameters": { - "label": "needs more info" + "label": "needs-author-action" } }, { @@ -5416,7 +5416,7 @@ { "name": "labelAdded", "parameters": { - "label": "needs more info" + "label": "needs-author-action" } } ] @@ -5426,12 +5426,12 @@ "issues", "project_card" ], - "taskName": "Needs more info notification", + "taskName": "Needs-author-action notification", "actions": [ { "name": "addReply", "parameters": { - "comment": "This issue has been marked `needs more info` since it may be missing important information. Please refer to our [contribution guidelines](https://github.com/dotnet/runtime/blob/main/CONTRIBUTING.md#writing-a-good-bug-report) for tips on how to report issues effectively." + "comment": "This issue has been marked `needs-author-action` since it may be missing important information. Please refer to our [contribution guidelines](https://github.com/dotnet/runtime/blob/main/CONTRIBUTING.md#writing-a-good-bug-report) for tips on how to report issues effectively." } } ] @@ -5951,7 +5951,7 @@ { "name": "labelAdded", "parameters": { - "label": "needs more info" + "label": "needs-author-action" } }, { @@ -6003,25 +6003,7 @@ { "name": "hasLabel", "parameters": { - "label": "area-System.Collections" - } - }, - { - "name": "hasLabel", - "parameters": { - "label": "area-System.Linq" - } - }, - { - "name": "hasLabel", - "parameters": { - "label": "area-System.Text.Json" - } - }, - { - "name": "hasLabel", - "parameters": { - "label": "area-System.Xml" + "label": "area-Meta" } } ] @@ -6032,7 +6014,7 @@ { "name": "isInProject", "parameters": { - "projectName": "Area Pod: Eirik / Krzysztof / Layomi - PRs", + "projectName": "Area Pod: Eric / Jeff - PRs", "isOrgProject": true } } @@ -6046,12 +6028,12 @@ "issues", "project_card" ], - "taskName": "[Area Pod: Eirik / Krzysztof / Layomi - PRs] Add new PR to Board", + "taskName": "[Area Pod: Eric / Jeff - PRs] Add new PR to Board", "actions": [ { "name": "addToProject", "parameters": { - "projectName": "Area Pod: Eirik / Krzysztof / Layomi - PRs", + "projectName": "Area Pod: Eric / Jeff - PRs", "columnName": "Needs Champion", "isOrgProject": true } @@ -6686,7 +6668,7 @@ { "name": "labelAdded", "parameters": { - "label": "needs more info" + "label": "needs-author-action" } }, { @@ -6723,6 +6705,119 @@ ] } }, + { + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "PullRequestResponder", + "version": "1.0", + "config": { + "conditions": { + "operator": "and", + "operands": [ + { + "operator": "or", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.CodeDom" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Configuration" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Reflection" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Reflection.Emit" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Reflection.Metadata" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Resources" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Runtime.CompilerServices" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Text.RegularExpressions" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Threading.Channels" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Threading.Tasks" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.DirectoryServices" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "isInProject", + "parameters": { + "projectName": "Area Pod: Buyaa / Jose / Steve - PRs", + "isOrgProject": true + } + } + ] + } + ] + }, + "eventType": "pull_request", + "eventNames": [ + "pull_request", + "issues", + "project_card" + ], + "taskName": "[Area Pod: Buyaa / Jose / Steve - PRs] Add new PR to Board", + "actions": [ + { + "name": "addToProject", + "parameters": { + "projectName": "Area Pod: Buyaa / Jose / Steve - PRs", + "columnName": "Needs Champion", + "isOrgProject": true + } + } + ] + } + }, { "taskType": "trigger", "capabilityId": "IssueResponder", @@ -7257,7 +7352,7 @@ { "name": "labelAdded", "parameters": { - "label": "needs more info" + "label": "needs-author-action" } }, { @@ -7294,6 +7389,77 @@ ] } }, + { + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "PullRequestResponder", + "version": "1.0", + "config": { + "conditions": { + "operator": "and", + "operands": [ + { + "operator": "or", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Collections" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Linq" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Text.Json" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Xml" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "isInProject", + "parameters": { + "projectName": "Area Pod: Eirik / Krzysztof / Layomi - PRs", + "isOrgProject": true + } + } + ] + } + ] + }, + "eventType": "pull_request", + "eventNames": [ + "pull_request", + "issues", + "project_card" + ], + "taskName": "[Area Pod: Eirik / Krzysztof / Layomi - PRs] Add new PR to Board", + "actions": [ + { + "name": "addToProject", + "parameters": { + "projectName": "Area Pod: Eirik / Krzysztof / Layomi - PRs", + "columnName": "Needs Champion", + "isOrgProject": true + } + } + ] + } + }, { "taskType": "trigger", "capabilityId": "IssueResponder", @@ -7379,5 +7545,984 @@ } ] } + }, + { + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "IssuesOnlyResponder", + "version": "1.0", + "config": { + "conditions": { + "operator": "and", + "operands": [ + { + "operator": "or", + "operands": [ + { + "operator": "and", + "operands": [ + { + "operator": "or", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-DependencyModel" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Caching" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Configuration" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-DependencyInjection" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Hosting" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Logging" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Options" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Primitives" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel.Composition" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Composition" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Diagnostics.Activity" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Globalization" + } + } + ] + }, + { + "operator": "or", + "operands": [ + { + "name": "isAction", + "parameters": { + "action": "reopened" + } + }, + { + "operator": "not", + "operands": [ + { + "name": "isInMilestone", + "parameters": {} + } + ] + } + ] + } + ] + }, + { + "operator": "or", + "operands": [ + { + "name": "labelAdded", + "parameters": { + "label": "area-DependencyModel" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-Extensions-Caching" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-Extensions-Configuration" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-Extensions-DependencyInjection" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-Extensions-Hosting" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-Extensions-Logging" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-Extensions-Options" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-Extensions-Primitives" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-System.ComponentModel" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-System.ComponentModel.Composition" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-System.Composition" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-System.Diagnostics.Activity" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "area-System.Globalization" + } + } + ] + } + ] + }, + { + "name": "isOpen", + "parameters": {} + }, + { + "operator": "or", + "operands": [ + { + "operator": "not", + "operands": [ + { + "name": "isInProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "isOrgProject": true + } + } + ] + }, + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "isOrgProject": true, + "columnName": "Triaged" + } + } + ] + } + ] + }, + "eventType": "issue", + "eventNames": [ + "issues", + "project_card" + ], + "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Add new issue to Board", + "actions": [ + { + "name": "addToProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "columnName": "Needs Triage", + "isOrgProject": true + } + } + ] + } + }, + { + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "IssueCommentResponder", + "version": "1.0", + "config": { + "conditions": { + "operator": "and", + "operands": [ + { + "operator": "or", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-DependencyModel" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Caching" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Configuration" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-DependencyInjection" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Hosting" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Logging" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Options" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Primitives" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel.Composition" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Composition" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Diagnostics.Activity" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Globalization" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "isCloseAndComment", + "parameters": {} + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "activitySenderHasPermissions", + "parameters": { + "permissions": "write" + } + } + ] + }, + { + "operator": "or", + "operands": [ + { + "operator": "not", + "operands": [ + { + "name": "isInProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "isOrgProject": true + } + } + ] + }, + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "columnName": "Triaged", + "isOrgProject": true + } + } + ] + } + ] + }, + "eventType": "issue", + "eventNames": [ + "issue_comment" + ], + "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Needs Further Triage", + "actions": [ + { + "name": "addToProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "columnName": "Needs Triage", + "isOrgProject": true + } + } + ] + } + }, + { + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "IssuesOnlyResponder", + "version": "1.0", + "config": { + "conditions": { + "operator": "and", + "operands": [ + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "columnName": "Needs Triage", + "isOrgProject": true + } + }, + { + "operator": "and", + "operands": [ + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-DependencyModel" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Caching" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Configuration" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-DependencyInjection" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Hosting" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Logging" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Options" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Primitives" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel.Composition" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Composition" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Diagnostics.Activity" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Globalization" + } + } + ] + } + ] + } + ] + }, + "eventType": "issue", + "eventNames": [ + "issues", + "project_card" + ], + "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Remove relabeled issues", + "actions": [ + { + "name": "removeFromProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "isOrgProject": true + } + } + ] + } + }, + { + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "IssuesOnlyResponder", + "version": "1.0", + "config": { + "conditions": { + "operator": "and", + "operands": [ + { + "name": "isInProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "isOrgProject": true + } + }, + { + "operator": "not", + "operands": [ + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "columnName": "Triaged" + } + } + ] + }, + { + "operator": "or", + "operands": [ + { + "name": "addedToMilestone", + "parameters": {} + }, + { + "name": "labelAdded", + "parameters": { + "label": "needs more info" + } + }, + { + "name": "labelAdded", + "parameters": { + "label": "api-ready-for-review" + } + }, + { + "name": "isAction", + "parameters": { + "action": "closed" + } + } + ] + } + ] + }, + "eventType": "issue", + "eventNames": [ + "issues", + "project_card" + ], + "taskName": "[Area Pod: Eric / Maryam / Tarek - Issue Triage] Move to Triaged Column", + "actions": [ + { + "name": "addToProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - Issue Triage", + "columnName": "Triaged", + "isOrgProject": true + } + } + ] + } + }, + { + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "PullRequestResponder", + "version": "1.0", + "config": { + "conditions": { + "operator": "and", + "operands": [ + { + "operator": "or", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-DependencyModel" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Caching" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Configuration" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-DependencyInjection" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Hosting" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Logging" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Options" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Primitives" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel.Composition" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Composition" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Diagnostics.Activity" + } + }, + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Globalization" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "isInProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "isOrgProject": true + } + } + ] + } + ] + }, + "eventType": "pull_request", + "eventNames": [ + "pull_request", + "issues", + "project_card" + ], + "taskName": "[Area Pod: Eric / Maryam / Tarek - PRs] Add new PR to Board", + "actions": [ + { + "name": "addToProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "columnName": "Needs Champion", + "isOrgProject": true + } + } + ] + } + }, + { + "taskType": "trigger", + "capabilityId": "IssueResponder", + "subCapability": "PullRequestResponder", + "version": "1.0", + "config": { + "conditions": { + "operator": "and", + "operands": [ + { + "name": "isInProjectColumn", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "columnName": "Needs Champion", + "isOrgProject": true + } + }, + { + "operator": "and", + "operands": [ + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-DependencyModel" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Caching" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Configuration" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-DependencyInjection" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Hosting" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Logging" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Options" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-Extensions-Primitives" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.ComponentModel.Composition" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Composition" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Diagnostics.Activity" + } + } + ] + }, + { + "operator": "not", + "operands": [ + { + "name": "hasLabel", + "parameters": { + "label": "area-System.Globalization" + } + } + ] + } + ] + } + ] + }, + "eventType": "pull_request", + "eventNames": [ + "pull_request", + "issues", + "project_card" + ], + "taskName": "[Area Pod: Eric / Maryam / Tarek - PRs] Remove relabeled PRs", + "actions": [ + { + "name": "removeFromProject", + "parameters": { + "projectName": "Area Pod: Eric / Maryam / Tarek - PRs", + "isOrgProject": true + } + } + ] + } } ] \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props index 0b45be5eca24a..e9e6fc4e36234 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -31,6 +31,7 @@ arm armel arm64 + loongarch64 s390x wasm x64 diff --git a/docs/coding-guidelines/project-guidelines.md b/docs/coding-guidelines/project-guidelines.md index 5f27836900e25..2e3e47dec4724 100644 --- a/docs/coding-guidelines/project-guidelines.md +++ b/docs/coding-guidelines/project-guidelines.md @@ -52,7 +52,7 @@ Pure netstandard configuration: All supported targets with unique windows/unix build for netcoreapp: ``` - $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetFrameworkCurrent) + $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetFrameworkMinimum) ``` diff --git a/docs/design/features/standalone-gc-loading.md b/docs/design/features/standalone-gc-loading.md index 3373bf5559f55..ed7440002e8da 100644 --- a/docs/design/features/standalone-gc-loading.md +++ b/docs/design/features/standalone-gc-loading.md @@ -47,7 +47,7 @@ Worth noting is that the JIT (both RyuJIT and the legacy JIT(s) before it) can b and have realized these same benefits. The existence of an interface and an implementation loadable from shared libraries has enabled RyuJIT in particular to be used as the code generator for both the CoreRT compiler and crossgen, while still being flexible enough to be tested using tools that implement -very non-standard execution engines such as [SuperPMI](https://github.com/dotnet/runtime/blob/main/src/coreclr/ToolBox/superpmi/readme.txt). +very non-standard execution engines such as [SuperPMI](https://github.com/dotnet/runtime/blob/main/src/coreclr/tools/superpmi/readme.md). The below loading protocol is inspired directly by the JIT loader and many aspects of the GC loader are identical to what the JIT does when loading dynamic shared libraries. diff --git a/docs/design/libraries/DllImportGenerator/StructMarshalling.md b/docs/design/libraries/DllImportGenerator/StructMarshalling.md index ab332616b7413..63781d6d77dbb 100644 --- a/docs/design/libraries/DllImportGenerator/StructMarshalling.md +++ b/docs/design/libraries/DllImportGenerator/StructMarshalling.md @@ -6,10 +6,11 @@ These types pose an interesting problem for a number of reasons listed below. Wi ## Problems -- Unmanaged vs Blittable - - The C# language (and Roslyn) do not have a concept of "blittable types". It only has the concept of "unmanaged types", which is similar to blittable, but differs for `bool`s and `char`s. `bool` and `char` types are "unmanaged", but are never (in the case of `bool`), or only sometimes (in the case of `char`) blittable. As a result, we cannot use the "is this type unmanaged" check in Roslyn for structures. +- What types require marshalling and what types can be passed as-is to native code? + - Unmanaged vs Blittable + - The C# language (and Roslyn) do not have a concept of "blittable types". It only has the concept of "unmanaged types", which is similar to blittable, but differs for `bool`s and `char`s. `bool` and `char` types are "unmanaged", but are never (in the case of `bool`), or only sometimes (in the case of `char`) blittable. As a result, we cannot use the "is this type unmanaged" check in Roslyn for structures without an additional mechanism provided by the runtime. - Limited type information in ref assemblies. - - In the ref assemblies generated by dotnet/runtime, we save space and prevent users from relying on private implementation details of structures by emitting limited information about their fields. Structures that have at least one non-object field are given a private `int` field, and structures that have at least one field that transitively contains an object are given one private `object`-typed field. As a result, we do not have full type information at code-generation time for any structures defined in the BCL when compiling a library that uses the ref assemblies. + - In the ref assemblies generated by dotnet/arcade's GenAPI (used in dotnet/runtime), we save space and prevent users from relying on private implementation details of structures by emitting limited information about their fields. Structures that have at least one non-object field are given a private `int` field, and structures that have at least one field that transitively contains an object are given one private `object`-typed field. As a result, we do not have full type information at code-generation time for any structures defined in the BCL when compiling a library that uses the ref assemblies. - Private reflection - Even when we do have information about all of the fields, we can't emit code that references them if they are private, so we would have to emit unsafe code and calculate offsets manually to support marshaling them. @@ -19,16 +20,13 @@ We've been working around another problem for a while in the runtime-integrated I propose an opt-in design where the owner of a struct has to explicitly opt-in to usage for interop. This enables our team to add special support as desired for various types such as `Span` while also avoiding the private reflection and limited type information issues mentioned above. -This design would use these attributes: +All design options would use these attributes: ```csharp [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class)] public class GeneratedMarshallingAttribute : Attribute {} -[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class)] -public class BlittableTypeAttribute : Attribute {} - [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class)] public class NativeMarshallingAttribute : Attribute { @@ -42,7 +40,7 @@ public class MarshalUsingAttribute : Attribute } ``` -The `NativeMarshallingAttribute` and `MarshalUsingAttribute` attributes would require that the provided native type `TNative` is a blittable `struct` and has a subset of three methods with the following names and shapes (with the managed type named TManaged): +The `NativeMarshallingAttribute` and `MarshalUsingAttribute` attributes would require that the provided native type `TNative` is a `struct` that does not require any marshalling and has a subset of three methods with the following names and shapes (with the managed type named TManaged): ```csharp partial struct TNative @@ -59,7 +57,7 @@ The analyzer will report an error if neither the constructor nor the `ToManaged` > :question: Does this API surface and shape work for all marshalling scenarios we plan on supporting? It may have issues with the current "layout class" by-value `[Out]` parameter marshalling where the runtime updates a `class` typed object in place. We already recommend against using classes for interop for performance reasons and a struct value passed via `ref` or `out` with the same members would cover this scenario. -If the native type `TNative` also has a public `Value` property, then the value of the `Value` property will be passed to native code instead of the `TNative` value itself. As a result, the type `TNative` will be allowed to be non-blittable and the type of the `Value` property will be required to be blittable. If the `Value` property is settable, then when marshalling in the native-to-managed direction, a default value of `TNative` will have its `Value` property set to the native value. If `Value` does not have a setter, then marshalling from native to managed is not supported. +If the native type `TNative` also has a public `Value` property, then the value of the `Value` property will be passed to native code instead of the `TNative` value itself. As a result, the type `TNative` will be allowed to require marshalling and the type of the `Value` property will be required be passable to native code without any additional marshalling. If the `Value` property is settable, then when marshalling in the native-to-managed direction, a default value of `TNative` will have its `Value` property set to the native value. If `Value` does not have a setter, then marshalling from native to managed is not supported. If a `Value` property is provided, the developer may also provide a ref-returning or readonly-ref-returning `GetPinnableReference` method. The `GetPinnableReference` method will be called before the `Value` property getter is called. The ref returned by `GetPinnableReference` will be pinned with a `fixed` statement, but the pinned value will not be used (it acts exclusively as a side-effect). @@ -90,7 +88,7 @@ public struct TMarshaler #### Pinning -Since C# 7.3 added a feature to enable custom pinning logic for user types, we should also add support for custom pinning logic. If the user provides a `GetPinnableReference` method on the managed type that matches the requirements to be used in a `fixed` statement and the pointed-to type is blittable, then we will support using pinning to marshal the managed value when possible. The analyzer should issue a warning when the pointed-to type would not match the final native type, accounting for the `Value` property on the native type. Since `MarshalUsingAttribute` is applied at usage time instead of at type authoring time, we will not enable the pinning feature since the implementation of `GetPinnableReference` is likely designed to match the default marshalling rules provided by the type author, not the rules provided by the marshaller provided by the `MarshalUsingAttribute`. +Since C# 7.3 added a feature to enable custom pinning logic for user types, we should also add support for custom pinning logic. If the user provides a `GetPinnableReference` method on the managed type that matches the requirements to be used in a `fixed` statement and the pointed-to type would not require any additional marshalling, then we will support using pinning to marshal the managed value when possible. The analyzer should issue a warning when the pointed-to type would not match the final native type, accounting for the `Value` property on the native type. Since `MarshalUsingAttribute` is applied at usage time instead of at type authoring time, we will not enable the pinning feature since the implementation of `GetPinnableReference` is likely designed to match the default marshalling rules provided by the type author, not the rules provided by the marshaller provided by the `MarshalUsingAttribute`. #### Caller-allocated memory @@ -111,27 +109,18 @@ When these members are present, the source generator will call the two-parameter Type authors can pass down the `buffer` pointer to native code by defining a `Value` property that returns a pointer to the first element, generally through code using `MemoryMarshal.GetReference()` and `Unsafe.AsPointer`. If `RequiresStackBuffer` is not provided or set to `false`, the `buffer` span must be pinned to be used safely. The `buffer` span can be pinned by defining a `GetPinnableReference()` method on the native type that returns a reference to the first element of the span. -### Usage - -There are 2 usage mechanisms of these attributes. - -#### Usage 1, Source-generated interop - -The user can apply the `GeneratedMarshallingAttribute` to their structure `S`. The source generator will determine if the type is blittable. If it is blittable, the source generator will generate a partial definition and apply the `BlittableTypeAttribute` to the struct type `S`. Otherwise, it will generate a blittable representation of the struct with the aformentioned required shape and apply the `NativeMarshallingAttribute` and point it to the blittable representation. The blittable representation can either be generated as a separate top-level type or as a nested type on `S`. +### Determining if a type is doesn't need marshalling -#### Usage 2, Manual interop - -The user may want to manually mark their types as marshalable in this system due to specific restrictions in their code base around marshaling specific types that the source generator does not account for. We could also use this internally to support custom types in source instead of in the code generator. In this scenario, the user would apply either the `BlittableTypeAttribute` or the `NativeMarshallingAttribute` attribute to their struct type. An analyzer would validate that the struct is blittable if the `BlittableTypeAttribute` is applied or validate that the native struct type is blittable and has marshalling methods of the required shape when the `NativeMarshallingAttribute` is applied. - -The P/Invoke source generator (as well as the struct source generator when nested struct types are used) would use the `BlittableTypeAttribute` and `NativeMarshallingAttribute` to determine how to marshal a value type parameter or field instead of looking at the fields of the struct directly. +For this design, we need to decide how to determine a type doesn't need to be marshalled and already has a representation we can pass directly to native code - that is, we need a definition for "does not require marshalling". We have two designs that we have experimented with below, and we have decided to go with design 2. -If a structure type does not have either the `BlittableTypeAttribute` or the `NativeMarshallingAttribute` applied at the type definition, the user can supply a `MarshalUsingAttribute` at the marshalling location (field, parameter, or return value) with a native type matching the same requirements as `NativeMarshallingAttribute`'s native type. - -All generated stubs will be marked with [`SkipLocalsInitAttribute`](https://docs.microsoft.com/dotnet/api/system.runtime.compilerservices.skiplocalsinitattribute) on supported frameworks. This does require attention when performing custom marshalling as the state of stub allocated memory will be in an undefined state. +#### Design 1: Introducing `BlittableTypeAttribute` -### Why do we need `BlittableTypeAttribute`? +Traditionally, the concept of "does not require marshalling" is referred to as "blittable". The built-in runtime marshalling system has an issue as mentioned above that the concept of `unmanaged` is not the same as the concept of `blittable`. Additionally, due to the ref assembly issue above, we cannot rely on ref assemblies to have accurate information in terms of fields of a type. To solve these issues in combination with the desire to enable manual interop, we need to provide a way for users to signal that a given type should be blittable and that the source generator should not generate marshalling code. We'll introduce a new attribute, the `BlittableTypeAttribute`: -Based on the design above, it seems that we wouldn't need `BlittableTypeAttribute`. However, due to the ref assembly issue above in combination with the desire to enable manual interop, we need to provide a way for users to signal that a given type should be blittable and that the source generator should not generate marshalling code. +```csharp +[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class)] +public class BlittableTypeAttribute : Attribute {} +``` I'll give a specific example for where we need the `BlittableTypeAttribute` below. Let's take a scenario where we don't have `BlittableTypeAttribute`. @@ -210,7 +199,7 @@ When the source generator (either Struct, P/Invoke, Reverse P/Invoke, etc.) enco If someone actively disables the analyzer or writes their types in IL, then they have stepped out of the supported scenarios and marshalling code generated for their types may be inaccurate. -#### Exception: Generics +##### Exception: Generics Because the Roslyn compiler needs to be able to validate that there are not recursive struct definitions, reference assemblies have to contain a field of a type parameter type in the reference assembly if they do in the runtime assembly. As a result, we can inspect private generic fields reliably. @@ -221,6 +210,32 @@ To enable blittable generics support in this struct marshalling model, we extend Since all fields typed with non-parameterized types are validated to be blittable at type definition time, we know that they are all blittable at type usage time. So, we only need to validate that the generic fields are instantiated with blittable types. +#### Design 2: [`DisableRuntimeMarshallingAttribute`](https://github.com/dotnet/runtime/issues/60639) + +As an alternative design, we can use a different definition of "does not require marshalling". This design proposes changing the definition from "the runtime's definition of blittable" to "types considered `unmanaged` in C#". The `DisableRuntimeMarshallingAttribute` attribute helps us solve this problem. When applied to an assembly, this attribute causes the runtime to not do any marshalling for any types that are `unmanaged` types and do not have any auto-layout fields for all P/Invokes in the assembly; this includes when the types do not fit the runtime's definition of "blittable". This definition of "does not require marshalling" will work for all of our scenarios, with one issue listed below. + +For the auto-layout clause, we have one small issue; today, our ref-assemblies do not expose if a value type is marked as `[StructLayout(LayoutKind.Auto)]`, so we'd still have some cases where we might have runtime failures. However, we can update the tooling used in dotnet/runtime, GenAPI, to expose this information if we so desire. Once that case is handled, we have a mechanism that we can safely use to determine, at compile time, which types will not require marshalling. If we decide to not cover this case (as cases where users mark types as `LayoutKind.Auto` manually are exceptionally rare), we still have a solid design as Roslyn will automatically determine for us if a type is `unmanaged`, so we don't need to do any additional work. + +As `unmanaged` is a C# language concept, we can use Roslyn's APIs to determine if a type is `unmanaged` to determine if it does not require marshalling without needing to define any new attributes and reshape the ecosystem. However, to enable this work, the DllImportGenerator, as well as any other source generators that generate calls to native code using the interop team's infrastructure, will need to require that the user applies the `DisableRuntimeMarshallingAttribute` to their assembly when custom user-defined types are used. As we believe that users should be able to move over their assemblies to the new source-generated interop world as a whole assembly, we do not believe that this will cause any serious issues in adoption. To help support users in this case, the interop team will provide a code-fix that will generate the `DisableRuntimeMarshallingAttribute` for users when they use the source generator. + +### Usage + +There are 2 usage mechanisms of these attributes. + +#### Usage 1, Source-generated interop + +The user can apply the `GeneratedMarshallingAttribute` to their structure `S`. The source generator will determine if the type requires marshalling. If it does, it will generate a representation of the struct that does not require marshalling with the aformentioned required shape and apply the `NativeMarshallingAttribute` and point it to that new type. This generated representation can either be generated as a separate top-level type or as a nested type on `S`. + +#### Usage 2, Manual interop + +The user may want to manually mark their types as marshalable with custom marshalling rules in this system due to specific restrictions in their code base around marshaling specific types that the source generator does not account for. We could also use this internally to support custom types in source instead of in the code generator. In this scenario, the user would apply either the `NativeMarshallingAttribute` attribute to their struct type. An analyzer would validate that the native struct type does not require marshalling and has marshalling methods of the required shape when the `NativeMarshallingAttribute` is applied. + +The P/Invoke source generator (as well as the struct source generator when nested struct types are used) would use the `NativeMarshallingAttribute` to determine how to marshal a parameter or field with an unknown type. + +If a structure type does not meet the requirements to not require marshalling or does not have the `NativeMarshallingAttribute` applied at the type definition, the user can supply a `MarshalUsingAttribute` at the marshalling location (field, parameter, or return value) with a native type matching the same requirements as `NativeMarshallingAttribute`'s native type. + +All generated stubs will be marked with [`SkipLocalsInitAttribute`](https://docs.microsoft.com/dotnet/api/system.runtime.compilerservices.skiplocalsinitattribute) on supported frameworks. This does require attention when performing custom marshalling as the state of stub allocated memory will be in an undefined state. + ### Special case: Transparent Structures There has been discussion about Transparent Structures, structure types that are treated as their underlying types when passed to native code. The support for a `Value` property on a generated marshalling type supports the transparent struct support. For example, we could support strongly typed `HRESULT` returns with this model as shown below: @@ -250,7 +265,7 @@ struct HRESULT In this case, the underlying native type would actually be an `int`, but the user could use the strongly-typed `HResult` type as the public surface area. -> :question: Should we support transparent structures on manually annotated blittable types? If we do, we should do so in an opt-in manner to make it possible to have a `Value` property on the blittable type. +> :question: Should we support transparent structures on manually annotated types that wouldn't need marshalling otherwise? If we do, we should do so in an opt-in manner to make it possible to have a `Value` property on the type without assuming that it is for interop in all cases. #### Example: ComWrappers marshalling with Transparent Structures diff --git a/docs/pr-builds.md b/docs/pr-builds.md new file mode 100644 index 0000000000000..1d098b5c1b9da --- /dev/null +++ b/docs/pr-builds.md @@ -0,0 +1,94 @@ +## PR Builds +When submitting a PR to the `dotnet/runtime` repository various builds will run validation in many areas to ensure we keep productivity and quality high. + +The `dotnet/runtime` validation system can become overwhelming as we need to cover a lot of build scenarios and test in all the platforms that we support. In order to try to make this more reliable and spend the least amount of time testing what the PR change need we have various pipelines, required and optional that are covered in this document. + +Most of the repository pipelines use a custom mechanism to evaluate paths based on the changes contained in the PR to try and build/test the least that we can without compromising quality. This is the initial step on every pipeline that depends on this infrastructure, called "Evalute Paths". In this step you can see the result of the evaluation for each subset of the repository. For more details on which subsets we have based on paths see [here](https://github.com/dotnet/runtime/blob/513fe2863ad5ec6dc453d223d4b60f787a0ffa78/eng/pipelines/common/evaluate-default-paths.yml). Also to understand how this mechanism you can read this [comment](https://github.com/dotnet/runtime/blob/513fe2863ad5ec6dc453d223d4b60f787a0ffa78/eng/pipelines/evaluate-changed-paths.sh#L3-L12). + +### Runtime pipeline +This is the "main" pipeline for the runtime product. In this pipeline we include the most critical tests and platforms where we have enough test resources in order to deliver test results in a reasonable amount of time. The tests executed in this pipeline for runtime and libraries are considered innerloop, are the tests that are executed locally when one runs tests locally. + +For mobile platforms and wasm we run some smoke tests that aim to protect the quality of these platforms. We had to move to a smoke test approach given the hardware and time limitations that we encountered and contributors were affected by this with unstability and long wait times for their PRs to finish validation. + +### Runtime-dev-innerloop pipeline +This pipeline is also required, and its intent is to cover a developer innerloop scenarios that could be affected by any change, like running a specific build command or running tests inside Visual Studio, etc. + +### Dotnet-linker-tests +This is also a required pipeline. The purpose of this pipeline is to test that the libraries code is linker friendly. Meaning that when we trim our libraries using the ILLink, we don't have any trimming bugs, like a required method on a specific scenario is trimmed away by accident. + +### Runtime-staging +This pipeline runs on every change, however it behaves a little different than the other pipelines. This pipeline, will not fail if there are test failures, however it will fail if there is a timeout or a build failure. The reason why we fail on build failures is because we want to protect the developer innerloop (building the repository) for this platform. + +The tests will not fail because the intent of this platform is to stage new platforms where the test infrastructure is new and we need to test if we have enough capacity to include that new platform on the "main" runtime pipeline without causing flakiness. Once we analyze data and a platform is stable when running on PRs in this pipeline for at least a weak it can be promoted either to the `runtime-extra-platforms` pipeline or to the `runtime` pipeline. + +### Runtime-extra-platforms +This pipeline does not run by default as it is not required for a PR, but it runs twice a day, and it can also be invoked in specific PRs by commenting `/azp run runtime-extra-platforms` However, this pipeline is still an important part of our testing. + +This pipeline runs innerloop tests on platforms where we don't have enough hardware capacity to run tests (mobile, browser) or on platforms where we believe tests should organically pass based on the coverage we have in the "main" runtime pipeline. For example, in the "main" pipeline we run tests on Ubuntu 21.10 but since we also support Ubuntu 18.04 which is an LTS release, we run tests on Ubuntu 18.04 of this pipeline just to make sure we have healthy tests on those platforms which we are releasing a product for. + +Another concrete scenario would be windows arm64 for libraries tests. Where we don't have enough hardware, but the JIT is the most important piece to test as that is what generates the native code to run on that platform, so we run JIT tests on arm64 in the "main" pipeline, but our libraries tests are only run on the `runtime-extra-platforms` pipeline. + +### Outerloop pipelines +We have various pipelines that their names contain `Outerloop` on them. These pipelines will not run by default on every PR, they can also be invoked using the `/azp run` comment and will run on a daily basis to analyze test results. + +These pipelines will run tests that take very long, that are not very stable (i.e some networking tests), or that modify machine state. Such tests are called `Outerloop` tests rather than `innerloop`. + +## Rerunning Validation + +Validation may fail for several reasons: + +### Option 1: You have a defect in your PR + +* Simply push the fix to your PR branch, and validation will start over. + +### Option 2: There is a flaky test that is not related to your PR + +* Your assumption should be that a failed test indicates a problem in your PR. (If we don't operate this way, chaos ensues.) If the test fails when run again, it is almost surely a failure caused by your PR. However, there are occasions where unrelated failures occur. Here's some ways to know: + * Perhaps you see the same failure in CI results for unrelated active PR's. + * It's a known issue listed in our [big tracking issue](https://github.com/dotnet/runtime/issues/702) or tagged `blocking-clean-ci` [(query here)](https://github.com/dotnet/runtime/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3Ablocking-clean-ci+) + * Its otherwise beyond any reasonable doubt that your code changes could not have caused this. + * If the tests pass on rerun, that may suggest it's not related. +* In this situation, you want to re-run but not necessarily rebase on main. + * To rerun just the failed leg(s): + * Click on any leg. Navigate through the Azure DevOps UI, find the "..." button and choose "Retry failed legs" + * Or, on the GitHub Checks tab choose "re-run failed checks". This will not rebase your change. + * To rerun all validation: + * Add a comment `/azp run runtime` + * Or, click on "re-run all checks" in the GitHub Checks tab + * Or, simply close and reopen the PR. +* If you have established that it is an unrelated failure, please ensure we have an active issue for it. See the [unrelated failure](#what-to-do-if-you-determine-the-failure-is-unrelated) section below. +* Whoever merges the PR should be satisfied that the failure is unrelated, is not introduced by the change, and that we are appropriately tracking it. + +### Option 3: The state of the main branch HEAD is bad. + +* This is the very rare case where there was a build break in main, and you got unlucky. Hopefully the break has been fixed, and you want CI to rebase your change and rerun validation. +* To rebase and rerun all validation: + * Add a comment `/azp run runtime` + * Or, click on "re-run all checks" in the GitHub Checks tab + * Or, simply close and reopen the PR. + * Or, ammend your commit with `--amend --no-edit` and force push to your branch. + +### Additional information: + * You can list the available pipelines by adding a comment like `/azp list` or get the available commands by adding a comment like `azp help`. + * In the rare case the license/cla check fails to register a response, it can be rerun by issuing a GET request to `https://cla.dotnetfoundation.org/check/dotnet/runtime?pullRequest={pr_number}`. A successful response may be a redirect to `https://github.com`. + * Reach out to the infrastructure team for assistance on [Teams channel](https://teams.microsoft.com/l/channel/19%3ab27b36ecd10a46398da76b02f0411de7%40thread.skype/Infrastructure?groupId=014ca51d-be57-47fa-9628-a15efcc3c376&tenantId=72f988bf-86f1-41af-91ab-2d7cd011db47) (for corpnet users) or on [Gitter](https://gitter.im/dotnet/community) in other cases. + +## What to do if you determine the failure is unrelated + +If you have determined the failure is definitely not caused by changes in your PR, please do this: + +* Search for an [existing issue](https://github.com/dotnet/runtime/issues). Usually the test method name or (if a crash/hang) the test assembly name are good search parameters. + * If there's an existing issue, add a comment with + * a) the link to the build + * b) the affected configuration (ie `net6.0-windows-Release-x64-Windows.81.Amd64.Open`) + * c) all console output including the error message and stack trace from the Azure DevOps tab (This is necessary as retention policies are in place that recycle old builds.) + * d) if there's a dump file (see Attachments tab in Azure DevOps) include that + * If the issue is already closed, reopen it and update the labels to reflect the current failure state. + * If there's no existing issue, create an issue with the same information listed above. + * Update the original pull request with a comment linking to the new or existing issue. +* In a follow-up Pull Request, disable the failing test(s) with the corresponding issue link tracking the disable. + * Update the tracking issue with the label `disabled-test`. + * For libraries tests add a [`[ActiveIssue(link)]`](https://github.com/dotnet/arcade/blob/master/src/Microsoft.DotNet.XUnitExtensions/src/Attributes/ActiveIssueAttribute.cs) attribute on the test method. You can narrow the disabling down to runtime variant, flavor, and platform. For an example see [File_AppendAllLinesAsync_Encoded](https://github.com/dotnet/runtime/blob/a259ec2e967d502f82163beba6b84da5319c5e08/src/libraries/System.IO.FileSystem/tests/File/AppendAsync.cs#L899) + * For runtime tests found under `src/tests`, please edit [`issues.targets`](https://github.com/dotnet/runtime/blob/main/src/tests/issues.targets). There are several groups for different types of disable (mono vs. coreclr, different platforms, different scenarios). Add the folder containing the test and issue mimicking any of the samples in the file. + +There are plenty of possible bugs, e.g. race conditions, where a failure might highlight a real problem and it won't manifest again on a retry. Therefore these steps should be followed for every iteration of the PR build, e.g. before retrying/rebuilding. \ No newline at end of file diff --git a/docs/pr-guide.md b/docs/pr-guide.md index b250efd6e12dd..eb7dea7a01ba7 100644 --- a/docs/pr-guide.md +++ b/docs/pr-guide.md @@ -24,71 +24,10 @@ Anyone with write access can merge a pull request manually or by setting the [au * The PR has been approved by at least one reviewer and any other objections are addressed. * You can request another review from the original reviewer. -* The PR successfully builds and passes all tests in the Continuous Integration (CI) system. - * Depending on your change, you may need to re-run validation. See [rerunning validation](#rerunning-validation) below. +* The PR successfully builds and passes all tests in the Continuous Integration (CI) system. For more information please read to our [PR Builds](pr-builds.md) doc. Typically, PRs are merged as one commit. It creates a simpler history than a Merge Commit. "Special circumstances" are rare, and typically mean that there are a series of cleanly separated changes that will be too hard to understand if squashed together, or for some reason we want to preserve the ability to bisect them. -## Rerunning Validation - -Validation may fail for several reasons: - -### Option 1: You have a defect in your PR - -* Simply push the fix to your PR branch, and validation will start over. - -### Option 2: There is a flaky test that is not related to your PR - -* Your assumption should be that a failed test indicates a problem in your PR. (If we don't operate this way, chaos ensues.) If the test fails when run again, it is almost surely a failure caused by your PR. However, there are occasions where unrelated failures occur. Here's some ways to know: - * Perhaps you see the same failure in CI results for unrelated active PR's. - * It's a known issue listed in our [big tracking issue](https://github.com/dotnet/runtime/issues/702) or tagged `blocking-clean-ci` [(query here)](https://github.com/dotnet/runtime/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3Ablocking-clean-ci+) - * Its otherwise beyond any reasonable doubt that your code changes could not have caused this. - * If the tests pass on rerun, that may suggest it's not related. -* In this situation, you want to re-run but not necessarily rebase on main. - * To rerun just the failed leg(s): - * Click on any leg. Navigate through the Azure DevOps UI, find the "..." button and choose "Retry failed legs" - * Or, on the GitHub Checks tab choose "re-run failed checks". This will not rebase your change. - * To rerun all validation: - * Add a comment `/azp run runtime` - * Or, click on "re-run all checks" in the GitHub Checks tab - * Or, simply close and reopen the PR. -* If you have established that it is an unrelated failure, please ensure we have an active issue for it. See the [unrelated failure](#what-to-do-if-you-determine-the-failure-is-unrelated) section below. -* Whoever merges the PR should be satisfied that the failure is unrelated, is not introduced by the change, and that we are appropriately tracking it. - -### Option 3: The state of the main branch HEAD is bad. - -* This is the very rare case where there was a build break in main, and you got unlucky. Hopefully the break has been fixed, and you want CI to rebase your change and rerun validation. -* To rebase and rerun all validation: - * Add a comment `/azp run runtime` - * Or, click on "re-run all checks" in the GitHub Checks tab - * Or, simply close and reopen the PR. - * Or, ammend your commit with `--amend --no-edit` and force push to your branch. - -### Additional information: - * You can list the available pipelines by adding a comment like `/azp list` or get the available commands by adding a comment like `azp help`. - * In the rare case the license/cla check fails to register a response, it can be rerun by issuing a GET request to `https://cla.dotnetfoundation.org/check/dotnet/runtime?pullRequest={pr_number}`. A successful response may be a redirect to `https://github.com`. - * Reach out to the infrastructure team for assistance on [Teams channel](https://teams.microsoft.com/l/channel/19%3ab27b36ecd10a46398da76b02f0411de7%40thread.skype/Infrastructure?groupId=014ca51d-be57-47fa-9628-a15efcc3c376&tenantId=72f988bf-86f1-41af-91ab-2d7cd011db47) (for corpnet users) or on [Gitter](https://gitter.im/dotnet/community) in other cases. - -## What to do if you determine the failure is unrelated - -If you have determined the failure is definitely not caused by changes in your PR, please do this: - -* Search for an [existing issue](https://github.com/dotnet/runtime/issues). Usually the test method name or (if a crash/hang) the test assembly name are good search parameters. - * If there's an existing issue, add a comment with - * a) the link to the build - * b) the affected configuration (ie `net6.0-windows-Release-x64-Windows.81.Amd64.Open`) - * c) all console output including the error message and stack trace from the Azure DevOps tab (This is necessary as retention policies are in place that recycle old builds.) - * d) if there's a dump file (see Attachments tab in Azure DevOps) include that - * If the issue is already closed, reopen it and update the labels to reflect the current failure state. - * If there's no existing issue, create an issue with the same information listed above. - * Update the original pull request with a comment linking to the new or existing issue. -* In a follow-up Pull Request, disable the failing test(s) with the corresponding issue link tracking the disable. - * Update the tracking issue with the label `disabled-test`. - * For libraries tests add a [`[ActiveIssue(link)]`](https://github.com/dotnet/arcade/blob/master/src/Microsoft.DotNet.XUnitExtensions/src/Attributes/ActiveIssueAttribute.cs) attribute on the test method. You can narrow the disabling down to runtime variant, flavor, and platform. For an example see [File_AppendAllLinesAsync_Encoded](https://github.com/dotnet/runtime/blob/a259ec2e967d502f82163beba6b84da5319c5e08/src/libraries/System.IO.FileSystem/tests/File/AppendAsync.cs#L899) - * For runtime tests found under `src/tests`, please edit [`issues.targets`](https://github.com/dotnet/runtime/blob/main/src/tests/issues.targets). There are several groups for different types of disable (mono vs. coreclr, different platforms, different scenarios). Add the folder containing the test and issue mimicking any of the samples in the file. - -There are plenty of possible bugs, e.g. race conditions, where a failure might highlight a real problem and it won't manifest again on a retry. Therefore these steps should be followed for every iteration of the PR build, e.g. before retrying/rebuilding. - ## Blocking Pull Request Merging If for whatever reason you would like to move your pull request back to an in-progress status to avoid merging it in the current form, you can do that by adding [WIP] prefix to the pull request title. diff --git a/docs/project/glossary.md b/docs/project/glossary.md index cb7e0b21538b8..9104049e947ec 100644 --- a/docs/project/glossary.md +++ b/docs/project/glossary.md @@ -43,7 +43,7 @@ terminology. | SDK | Software Development Kit. The [.NET SDK](https://docs.microsoft.com/dotnet/core/sdk) contains the .NET CLI, .NET libraries and runtime, and the dotnet driver. | | SEH | [Structured Exception Handling](https://docs.microsoft.com/windows/win32/debug/structured-exception-handling). Unified mechanism for handling hardware and software exceptions on Windows. | | SOS | [Son of Strike](https://docs.microsoft.com/archive/blogs/jasonz/sos-debugging-of-the-clr-part-1). The debugging extension for DbgEng based debuggers. Uses the DAC as an abstraction layer for its operation. | -| SuperPMI | JIT component test framework (super fast JIT testing - it mocks/replays EE in EE-JIT interface) - see [SuperPMI details](https://github.com/dotnet/runtime/blob/main/src/coreclr/ToolBox/superpmi/readme.txt). | +| SuperPMI | JIT component test framework (super fast JIT testing - it mocks/replays EE in EE-JIT interface) - see [SuperPMI details](https://github.com/dotnet/runtime/blob/main/src/coreclr/tools/superpmi/readme.md). | | SVR | The CLR used to be built as two variants, with one called "mscorsvr.dll", to mean the "server" version. In particular, it contained the server GC implementation, which was intended for multi-threaded apps capable of taking advantage of multiple processors. In the .NET Framework 2 release, the two variants were merged into "mscorwks.dll". The WKS version was the default, however the SVR version remained available. | | TFM | [Target Framework Moniker](https://docs.microsoft.com/dotnet/standard/frameworks) such as `net6.0` or `netstandard2.0`. | | TPA | Trusted Platform Assemblies used to be a special set of assemblies that comprised the platform assemblies, when it was originally designed. As of today, it is simply the set of assemblies known to constitute the application. | diff --git a/docs/workflow/debugging/coreclr/debugging-aot-compilers.md b/docs/workflow/debugging/coreclr/debugging-aot-compilers.md index 0a216b7320100..d21fa21a5cb77 100644 --- a/docs/workflow/debugging/coreclr/debugging-aot-compilers.md +++ b/docs/workflow/debugging/coreclr/debugging-aot-compilers.md @@ -172,3 +172,7 @@ devenv /debugexe C:\git2\runtime\.dotnet\dotnet.exe "c:\git2\runtime\artifacts\t ``` This will launch the Visual Studio debugger, with a solution setup for debugging the dotnet.exe process. By default this solution will debug the native code of the process only. To debug the managed components, edit the properties on the solution and set the `Debugger Type` to `Managed (.NET Core, .NET 5+)` or `Mixed (.NET Core, .NET 5+)`. + +# Debugging compilation graph + +The AOT compilation is driven by a dependency graph. If you need to troubleshoot the dependency graph (to figure out why something was or wasn't generated) you can follow [this guide](debuging-compiler-dependency-analysis.md) diff --git a/docs/workflow/debugging/coreclr/debuging-compiler-dependency-analysis.md b/docs/workflow/debugging/coreclr/debuging-compiler-dependency-analysis.md new file mode 100644 index 0000000000000..cc918c391f62a --- /dev/null +++ b/docs/workflow/debugging/coreclr/debuging-compiler-dependency-analysis.md @@ -0,0 +1,47 @@ +Debugging Compiler Dependency Analysis +============================ + +The general technique is to identify what node is missing from the graph or is erroneously present in the graph, and change the dependency analysis logic to adjust the graph. This document describes the various ways of debugging to identify what's happening. + +Analysis techniques for the dependency graph. +1. Use the DependencyGraphViewer tool (if running on Windows). This tool is located in `src/coreclr/tools/aot/DependencyGraphViewer` + - This is the only convenient way to examine the graph while also simultaneously debugging the compiler. + - While this is currently Windows only due to use of WinForms, it would be fairly straightforward to make a command line based tool. + - Dependency graph does not support multiple simultaneous logging facilities, so make sure that you do not set IlcGenerateDgmlFile or invoke ILCompiler with the DGML generation turned on. +2. Pass command line switches to the compiler to generate a dependency graph dgml file. This will produce the same data as is viewable in the viewer tool, but in a textual xml format. + - Future efforts may make the xml file loadable by the viewer tool. +3. Instrument the compiler dependency analysis. (This may be necessary in cases where the viewer is unable to provide sufficient information about why the graph is structured as it is.) + +DependencyGraphViewer +==================================== + +This application allows viewing the dependency graph produced by the AOT compilation. + +Usage instructions: +1. Launch the process as an administrator +2. Run the compiler +- The compiler can be run to completion, or stopped. +3. Explore through the graph + +# Graphs View # +- Choose one of the graphs that appears in the Dependency Graphs view to explore. As compilers execute, new graphs will automatically appear here. +- The set of graphs loaded into the process is limited by available memory space. To clear the used memory, close all windows of the application. + +# Graph View # +- In the Dependency Graph view, enter a regular expression in the text box, and then press ""Filter"". This will display a list of the nodes in the graph which have names which match the regular expression. +- Commonly, if there is a object file symbol associated with the node it should be used as part of the regular expression. See the various implementations of GetName in the compiler for naming behavior. +- Additionally, the event source marking mode assigns an Id to each node, and that is found as the mark object on the node, so if a specific id is known, just type that in, and it will appear in the window. (This is for use when using this tool in parallel with debugging the compiler. + +# Single Node Exploration # +Once the interesting node(s) have been identified in the dependency graph window, select one of them, and then press Explore. + - In the Node Explorer window, the Dependent nodes (the ones which dependend on the current node are the nodes displayed above, and the Dependee nodes (the nodes that this node depends on) are displayed below. Each node in the list is paired with a textual reason as to why that edge in the graph exists. + - Select a node to explore further and press the corresponding button to make it happen. + +WhyDGML +======= +This tool can be used to visualize paths from a node of interest to the roots. To use it, pass command line option to the compiler to generate the DGML file (`--dgmllog name_of_output_file`) and then use this tool to find the path to the root. If you're looking at an optimized NativeAOT compilation, `--scandgmllog` might be preferable since it will have more details. +The input to the tool is the DGML file and name of a node of interest. The output is the list of reasons why that node was included. + +This tool located in folder `src/coreclr/tools/aot/WhyDgml` + +See https://github.com/dotnet/corert/pull/7962 for example of usage and output. diff --git a/eng/CodeAnalysis.src.globalconfig b/eng/CodeAnalysis.src.globalconfig index 400c8c432c21b..0fc9bf8e5a7ee 100644 --- a/eng/CodeAnalysis.src.globalconfig +++ b/eng/CodeAnalysis.src.globalconfig @@ -1444,7 +1444,7 @@ dotnet_diagnostic.IDE0057.severity = suggestion dotnet_diagnostic.IDE0058.severity = silent # IDE0059: Unnecessary assignment of a value -dotnet_diagnostic.IDE0059.severity = suggestion +dotnet_diagnostic.IDE0059.severity = warning # IDE0060: Remove unused parameter dotnet_diagnostic.IDE0060.severity = silent diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index 6267584b91fd1..a8d298b5be9c8 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -1,8 +1,8 @@ - + https://github.com/dotnet/icu - 35aca8766e42ad0f9ef458c4106917f1075cf230 + 4170ccfbbcada3e22aa4428a84524fabef006e38 https://github.com/dotnet/msquic @@ -16,243 +16,243 @@ https://github.com/dotnet/wcf 7f504aabb1988e9a093c1e74d8040bd52feb2f01 - + https://github.com/dotnet/llvm-project - 58a3ab6364cc934622ae0b09c3ef09768723a4e1 + e7e0ebc663c70ccb19c331af50d418a06dc92df8 - + https://github.com/dotnet/llvm-project - 58a3ab6364cc934622ae0b09c3ef09768723a4e1 + e7e0ebc663c70ccb19c331af50d418a06dc92df8 - + https://github.com/dotnet/llvm-project - 58a3ab6364cc934622ae0b09c3ef09768723a4e1 + e7e0ebc663c70ccb19c331af50d418a06dc92df8 - + https://github.com/dotnet/llvm-project - 58a3ab6364cc934622ae0b09c3ef09768723a4e1 + e7e0ebc663c70ccb19c331af50d418a06dc92df8 - + https://github.com/dotnet/llvm-project - 58a3ab6364cc934622ae0b09c3ef09768723a4e1 + e7e0ebc663c70ccb19c331af50d418a06dc92df8 - + https://github.com/dotnet/llvm-project - 58a3ab6364cc934622ae0b09c3ef09768723a4e1 + e7e0ebc663c70ccb19c331af50d418a06dc92df8 - + https://github.com/dotnet/llvm-project - 58a3ab6364cc934622ae0b09c3ef09768723a4e1 + e7e0ebc663c70ccb19c331af50d418a06dc92df8 - + https://github.com/dotnet/llvm-project - 58a3ab6364cc934622ae0b09c3ef09768723a4e1 + e7e0ebc663c70ccb19c331af50d418a06dc92df8 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 https://github.com/microsoft/vstest 140434f7109d357d0158ade9e5164a4861513965 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/llvm-project - 662aff66999c435aec09c58643e9fd703eadc3e0 + 79a6d232058e2c2f1d9e833355b72f07fe342a3b - + https://github.com/dotnet/llvm-project - 662aff66999c435aec09c58643e9fd703eadc3e0 + 79a6d232058e2c2f1d9e833355b72f07fe342a3b - + https://github.com/dotnet/llvm-project - 662aff66999c435aec09c58643e9fd703eadc3e0 + 79a6d232058e2c2f1d9e833355b72f07fe342a3b - + https://github.com/dotnet/llvm-project - 662aff66999c435aec09c58643e9fd703eadc3e0 + 79a6d232058e2c2f1d9e833355b72f07fe342a3b - + https://github.com/dotnet/llvm-project - 662aff66999c435aec09c58643e9fd703eadc3e0 + 79a6d232058e2c2f1d9e833355b72f07fe342a3b - + https://github.com/dotnet/llvm-project - 662aff66999c435aec09c58643e9fd703eadc3e0 + 79a6d232058e2c2f1d9e833355b72f07fe342a3b - + https://github.com/dotnet/llvm-project - 662aff66999c435aec09c58643e9fd703eadc3e0 + 79a6d232058e2c2f1d9e833355b72f07fe342a3b - + https://github.com/dotnet/llvm-project - 662aff66999c435aec09c58643e9fd703eadc3e0 + 79a6d232058e2c2f1d9e833355b72f07fe342a3b - + https://github.com/dotnet/runtime - c8f3b36d6d5da74333c6755ccd5687127bcd9905 + ae2f60c950cc021921fce83c796cbcb5ff96c658 - + https://github.com/dotnet/runtime - c8f3b36d6d5da74333c6755ccd5687127bcd9905 + ae2f60c950cc021921fce83c796cbcb5ff96c658 - + https://github.com/dotnet/runtime - c8f3b36d6d5da74333c6755ccd5687127bcd9905 + ae2f60c950cc021921fce83c796cbcb5ff96c658 - + https://github.com/dotnet/runtime - c8f3b36d6d5da74333c6755ccd5687127bcd9905 + ae2f60c950cc021921fce83c796cbcb5ff96c658 - + https://github.com/dotnet/runtime - c8f3b36d6d5da74333c6755ccd5687127bcd9905 + ae2f60c950cc021921fce83c796cbcb5ff96c658 - + https://github.com/dotnet/runtime - c8f3b36d6d5da74333c6755ccd5687127bcd9905 + ae2f60c950cc021921fce83c796cbcb5ff96c658 - + https://github.com/dotnet/runtime - c8f3b36d6d5da74333c6755ccd5687127bcd9905 + ae2f60c950cc021921fce83c796cbcb5ff96c658 - + https://github.com/dotnet/runtime - c8f3b36d6d5da74333c6755ccd5687127bcd9905 + ae2f60c950cc021921fce83c796cbcb5ff96c658 - + https://github.com/dotnet/linker - 1a6468ff722c8d362f37638989ec01ab9975ac28 + e485816b48273d03bd6266a64dad9bea97f861d5 - + https://github.com/dotnet/xharness - 7c293e5b676eb5b57418f775587badad65ec07f5 + 3060cda4543b80824a9238bcd176bb1a5af72044 - + https://github.com/dotnet/xharness - 7c293e5b676eb5b57418f775587badad65ec07f5 + 3060cda4543b80824a9238bcd176bb1a5af72044 - + https://github.com/dotnet/xharness - 7c293e5b676eb5b57418f775587badad65ec07f5 + 3060cda4543b80824a9238bcd176bb1a5af72044 - + https://github.com/dotnet/arcade - a0f6d2432ce3d1bb30ee747bb534f477c75fd667 + 9ffc76ac9f5799de9b28ee59f9bfbe0f8844d0d7 https://dev.azure.com/dnceng/internal/_git/dotnet-optimization @@ -270,17 +270,17 @@ https://dev.azure.com/dnceng/internal/_git/dotnet-optimization 91d6b3c1f51888d166701510189505f35714665c - + https://github.com/dotnet/hotreload-utils - 49dd195f467aa45d467a38ca02ae95d1b59062ce + 5bc948c6242bc9423c3269d122dcdf0ad6c06a83 - + https://github.com/dotnet/runtime-assets - f6e023ee68f858cd020a13dc9dfc13ba6a82b64b + a597df23119faf540d95cebab14b82f084c47384 - + https://github.com/dotnet/roslyn-analyzers - e101c379c6e3c7011562ee3af3e3de066da0048f + 6c43d213c426cf64c78eb1e9e38e4b9ec6454181 https://github.com/dotnet/sdk diff --git a/eng/Versions.props b/eng/Versions.props index 92cfc5d2f3a55..b0db712120a28 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -50,42 +50,42 @@ 3.3.2 4.0.1 4.0.1 - 7.0.0-preview1.21613.1 + 7.0.0-preview1.22067.1 2.0.0-alpha.1.21525.11 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 2.5.1-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 - 7.0.0-beta.22053.2 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 2.5.1-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 + 7.0.0-beta.22068.3 6.0.0-preview.1.102 - 7.0.0-alpha.1.22052.8 - 7.0.0-alpha.1.22052.8 - 7.0.0-alpha.1.22052.8 + 7.0.0-alpha.1.22066.4 + 7.0.0-alpha.1.22066.4 + 7.0.0-alpha.1.22066.4 3.1.0 - 7.0.0-alpha.1.22052.8 - 1.0.0-alpha.1.22052.1 - 1.0.0-alpha.1.22052.1 - 1.0.0-alpha.1.22052.1 - 1.0.0-alpha.1.22052.1 - 1.0.0-alpha.1.22052.1 - 1.0.0-alpha.1.22052.1 - 1.0.0-alpha.1.22052.1 - 1.0.0-alpha.1.22052.1 + 7.0.0-alpha.1.22066.4 + 1.0.0-alpha.1.22060.1 + 1.0.0-alpha.1.22060.1 + 1.0.0-alpha.1.22060.1 + 1.0.0-alpha.1.22060.1 + 1.0.0-alpha.1.22060.1 + 1.0.0-alpha.1.22060.1 + 1.0.0-alpha.1.22060.1 + 1.0.0-alpha.1.22060.1 5.0.0 4.3.0 @@ -120,24 +120,24 @@ 5.0.0 5.0.0 4.9.0-rc2.21473.1 - 7.0.0-alpha.1.22052.8 - 7.0.0-alpha.1.22052.8 + 7.0.0-alpha.1.22066.4 + 7.0.0-alpha.1.22066.4 4.5.4 4.5.0 - 7.0.0-alpha.1.22052.8 + 7.0.0-alpha.1.22066.4 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 - 7.0.0-beta.21620.3 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 + 7.0.0-beta.22060.1 1.0.0-prerelease.21577.2 1.0.0-prerelease.21577.2 @@ -160,10 +160,10 @@ 1.0.1-prerelease-00006 16.9.0-preview-20201201-01 - 1.0.0-prerelease.22053.2 - 1.0.0-prerelease.22053.2 - 1.0.0-prerelease.22053.2 - 1.0.2-alpha.0.22053.3 + 1.0.0-prerelease.22067.1 + 1.0.0-prerelease.22067.1 + 1.0.0-prerelease.22067.1 + 1.0.2-alpha.0.22060.2 2.4.2-pre.9 2.4.2 3.1.0 @@ -176,21 +176,21 @@ 6.0.0-preview-20211019.1 - 7.0.100-1.22053.1 + 7.0.100-1.22063.2 $(MicrosoftNETILLinkTasksVersion) - 7.0.0-alpha.1.22053.1 + 7.0.0-alpha.1.22067.1 7.0.0-alpha.1.21529.3 - 11.1.0-alpha.1.21615.1 - 11.1.0-alpha.1.21615.1 - 11.1.0-alpha.1.21615.1 - 11.1.0-alpha.1.21615.1 - 11.1.0-alpha.1.21615.1 - 11.1.0-alpha.1.21615.1 - 11.1.0-alpha.1.21615.1 - 11.1.0-alpha.1.21615.1 + 11.1.0-alpha.1.22067.2 + 11.1.0-alpha.1.22067.2 + 11.1.0-alpha.1.22067.2 + 11.1.0-alpha.1.22067.2 + 11.1.0-alpha.1.22067.2 + 11.1.0-alpha.1.22067.2 + 11.1.0-alpha.1.22067.2 + 11.1.0-alpha.1.22067.2 7.0.0-alpha.1.21601.1 $(MicrosoftNETWorkloadEmscriptenManifest70100Version) diff --git a/eng/build.sh b/eng/build.sh index f1ef5958fdbc9..ea8e3089e95f4 100755 --- a/eng/build.sh +++ b/eng/build.sh @@ -17,7 +17,7 @@ scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" usage() { echo "Common settings:" - echo " --arch (-a) Target platform: x86, x64, arm, armel, arm64, s390x or wasm." + echo " --arch (-a) Target platform: x86, x64, arm, armel, arm64, loongarch64, s390x or wasm." echo " [Default: Your machine's architecture.]" echo " --binaryLog (-bl) Output binary log." echo " --cross Optional argument to signify cross compilation." @@ -206,12 +206,12 @@ while [[ $# > 0 ]]; do fi passedArch="$(echo "$2" | tr "[:upper:]" "[:lower:]")" case "$passedArch" in - x64|x86|arm|armel|arm64|s390x|wasm) + x64|x86|arm|armel|arm64|loongarch64|s390x|wasm) arch=$passedArch ;; *) echo "Unsupported target architecture '$2'." - echo "The allowed values are x86, x64, arm, armel, arm64, s390x, and wasm." + echo "The allowed values are x86, x64, arm, armel, arm64, loongarch64, s390x, and wasm." exit 1 ;; esac diff --git a/eng/common/cross/toolchain.cmake b/eng/common/cross/toolchain.cmake index f7878dddd3921..fba2afda438b6 100644 --- a/eng/common/cross/toolchain.cmake +++ b/eng/common/cross/toolchain.cmake @@ -37,6 +37,13 @@ elseif(TARGET_ARCH_NAME STREQUAL "arm") if(TIZEN) set(TIZEN_TOOLCHAIN "armv7hl-tizen-linux-gnueabihf/9.2.0") endif() +elseif(TARGET_ARCH_NAME STREQUAL "armv6") + set(CMAKE_SYSTEM_PROCESSOR armv6l) + if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/armv6-alpine-linux-musleabihf) + set(TOOLCHAIN "armv6-alpine-linux-musleabihf") + else() + set(TOOLCHAIN "arm-linux-gnueabihf") + endif() elseif(TARGET_ARCH_NAME STREQUAL "arm64") set(CMAKE_SYSTEM_PROCESSOR aarch64) if(EXISTS ${CROSS_ROOTFS}/usr/lib/gcc/aarch64-alpine-linux-musl) @@ -60,7 +67,7 @@ elseif (ILLUMOS) set(CMAKE_SYSTEM_PROCESSOR "x86_64") set(TOOLCHAIN "x86_64-illumos") else() - message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64, s390x and x86 are supported!") + message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, armv6, arm64, s390x and x86 are supported!") endif() if(DEFINED ENV{TOOLCHAIN}) @@ -194,7 +201,7 @@ endif() # Specify compile options -if((TARGET_ARCH_NAME MATCHES "^(arm|armel|arm64|s390x)$" AND NOT ANDROID) OR ILLUMOS) +if((TARGET_ARCH_NAME MATCHES "^(arm|armv6|armel|arm64|s390x)$" AND NOT ANDROID) OR ILLUMOS) set(CMAKE_C_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_CXX_COMPILER_TARGET ${TOOLCHAIN}) set(CMAKE_ASM_COMPILER_TARGET ${TOOLCHAIN}) diff --git a/eng/common/generate-graph-files.ps1 b/eng/common/generate-graph-files.ps1 deleted file mode 100644 index 0728b1a8b570d..0000000000000 --- a/eng/common/generate-graph-files.ps1 +++ /dev/null @@ -1,86 +0,0 @@ -Param( - [Parameter(Mandatory=$true)][string] $barToken, # Token generated at https://maestro-prod.westus2.cloudapp.azure.com/Account/Tokens - [Parameter(Mandatory=$true)][string] $gitHubPat, # GitHub personal access token from https://github.com/settings/tokens (no auth scopes needed) - [Parameter(Mandatory=$true)][string] $azdoPat, # Azure Dev Ops tokens from https://dev.azure.com/dnceng/_details/security/tokens (code read scope needed) - [Parameter(Mandatory=$true)][string] $outputFolder, # Where the graphviz.txt file will be created - [string] $darcVersion, # darc's version - [string] $graphvizVersion = '2.38', # GraphViz version - [switch] $includeToolset # Whether the graph should include toolset dependencies or not. i.e. arcade, optimization. For more about - # toolset dependencies see https://github.com/dotnet/arcade/blob/master/Documentation/Darc.md#toolset-vs-product-dependencies -) - -function CheckExitCode ([string]$stage) -{ - $exitCode = $LASTEXITCODE - if ($exitCode -ne 0) { - Write-PipelineTelemetryError -Category 'Arcade' -Message "Something failed in stage: '$stage'. Check for errors above. Exiting now..." - ExitWithExitCode $exitCode - } -} - -try { - $ErrorActionPreference = 'Stop' - . $PSScriptRoot\tools.ps1 - - Import-Module -Name (Join-Path $PSScriptRoot 'native\CommonLibrary.psm1') - - Push-Location $PSScriptRoot - - Write-Host 'Installing darc...' - . .\darc-init.ps1 -darcVersion $darcVersion - CheckExitCode 'Running darc-init' - - $engCommonBaseDir = Join-Path $PSScriptRoot 'native\' - $graphvizInstallDir = CommonLibrary\Get-NativeInstallDirectory - $nativeToolBaseUri = 'https://netcorenativeassets.blob.core.windows.net/resource-packages/external' - $installBin = Join-Path $graphvizInstallDir 'bin' - - Write-Host 'Installing dot...' - .\native\install-tool.ps1 -ToolName graphviz -InstallPath $installBin -BaseUri $nativeToolBaseUri -CommonLibraryDirectory $engCommonBaseDir -Version $graphvizVersion -Verbose - - $darcExe = "$env:USERPROFILE\.dotnet\tools" - $darcExe = Resolve-Path "$darcExe\darc.exe" - - Create-Directory $outputFolder - - # Generate 3 graph descriptions: - # 1. Flat with coherency information - # 2. Graphviz (dot) file - # 3. Standard dependency graph - $graphVizFilePath = "$outputFolder\graphviz.txt" - $graphVizImageFilePath = "$outputFolder\graph.png" - $normalGraphFilePath = "$outputFolder\graph-full.txt" - $flatGraphFilePath = "$outputFolder\graph-flat.txt" - $baseOptions = @( '--github-pat', "$gitHubPat", '--azdev-pat', "$azdoPat", '--password', "$barToken" ) - - if ($includeToolset) { - Write-Host 'Toolsets will be included in the graph...' - $baseOptions += @( '--include-toolset' ) - } - - Write-Host 'Generating standard dependency graph...' - & "$darcExe" get-dependency-graph @baseOptions --output-file $normalGraphFilePath - CheckExitCode 'Generating normal dependency graph' - - Write-Host 'Generating flat dependency graph and graphviz file...' - & "$darcExe" get-dependency-graph @baseOptions --flat --coherency --graphviz $graphVizFilePath --output-file $flatGraphFilePath - CheckExitCode 'Generating flat and graphviz dependency graph' - - Write-Host "Generating graph image $graphVizFilePath" - $dotFilePath = Join-Path $installBin "graphviz\$graphvizVersion\release\bin\dot.exe" - & "$dotFilePath" -Tpng -o"$graphVizImageFilePath" "$graphVizFilePath" - CheckExitCode 'Generating graphviz image' - - Write-Host "'$graphVizFilePath', '$flatGraphFilePath', '$normalGraphFilePath' and '$graphVizImageFilePath' created!" -} -catch { - if (!$includeToolset) { - Write-Host 'This might be a toolset repo which includes only toolset dependencies. ' -NoNewline -ForegroundColor Yellow - Write-Host 'Since -includeToolset is not set there is no graph to create. Include -includeToolset and try again...' -ForegroundColor Yellow - } - Write-Host $_.ScriptStackTrace - Write-PipelineTelemetryError -Category 'Arcade' -Message $_ - ExitWithExitCode 1 -} finally { - Pop-Location -} \ No newline at end of file diff --git a/eng/common/post-build/publish-using-darc.ps1 b/eng/common/post-build/publish-using-darc.ps1 index 2427ca6b6aec7..8508397d77640 100644 --- a/eng/common/post-build/publish-using-darc.ps1 +++ b/eng/common/post-build/publish-using-darc.ps1 @@ -5,13 +5,8 @@ param( [Parameter(Mandatory=$true)][string] $MaestroToken, [Parameter(Mandatory=$false)][string] $MaestroApiEndPoint = 'https://maestro-prod.westus2.cloudapp.azure.com', [Parameter(Mandatory=$true)][string] $WaitPublishingFinish, - [Parameter(Mandatory=$false)][string] $EnableSourceLinkValidation, - [Parameter(Mandatory=$false)][string] $EnableSigningValidation, - [Parameter(Mandatory=$false)][string] $EnableNugetValidation, - [Parameter(Mandatory=$false)][string] $PublishInstallersAndChecksums, [Parameter(Mandatory=$false)][string] $ArtifactsPublishingAdditionalParameters, - [Parameter(Mandatory=$false)][string] $SymbolPublishingAdditionalParameters, - [Parameter(Mandatory=$false)][string] $SigningValidationAdditionalParameters + [Parameter(Mandatory=$false)][string] $SymbolPublishingAdditionalParameters ) try { @@ -35,27 +30,6 @@ try { $optionalParams.Add("--no-wait") | Out-Null } - if ("false" -ne $PublishInstallersAndChecksums) { - $optionalParams.Add("--publish-installers-and-checksums") | Out-Null - } - - if ("true" -eq $EnableNugetValidation) { - $optionalParams.Add("--validate-nuget") | Out-Null - } - - if ("true" -eq $EnableSourceLinkValidation) { - $optionalParams.Add("--validate-sourcelinkchecksums") | Out-Null - } - - if ("true" -eq $EnableSigningValidation) { - $optionalParams.Add("--validate-signingchecksums") | Out-Null - - if ("" -ne $SigningValidationAdditionalParameters) { - $optionalParams.Add("--signing-validation-parameters") | Out-Null - $optionalParams.Add($SigningValidationAdditionalParameters) | Out-Null - } - } - & $darc add-build-to-channel ` --id $buildId ` --publishing-infra-version $PublishingInfraVersion ` diff --git a/eng/common/sdl/configure-sdl-tool.ps1 b/eng/common/sdl/configure-sdl-tool.ps1 index 8a68fc24b11b0..bdbf49e6c71de 100644 --- a/eng/common/sdl/configure-sdl-tool.ps1 +++ b/eng/common/sdl/configure-sdl-tool.ps1 @@ -15,7 +15,9 @@ Param( # Optional: Additional params to add to any tool using CredScan. [string[]] $CrScanAdditionalRunConfigParams, # Optional: Additional params to add to any tool using PoliCheck. - [string[]] $PoliCheckAdditionalRunConfigParams + [string[]] $PoliCheckAdditionalRunConfigParams, + # Optional: Additional params to add to any tool using CodeQL/Semmle. + [string[]] $CodeQLAdditionalRunConfigParams ) $ErrorActionPreference = 'Stop' @@ -78,6 +80,11 @@ try { $tool.Args += "`"Target < $TargetDirectory`"" } $tool.Args += $PoliCheckAdditionalRunConfigParams + } elseif ($tool.Name -eq 'semmle' -or $tool.Name -eq 'codeql') { + if ($targetDirectory) { + $tool.Args += "`"SourceCodeDirectory < $TargetDirectory`"" + } + $tool.Args += $CodeQLAdditionalRunConfigParams } # Create variable pointing to the args array directly so we can use splat syntax later. diff --git a/eng/common/sdl/execute-all-sdl-tools.ps1 b/eng/common/sdl/execute-all-sdl-tools.ps1 index e5bef8ebd3a3b..4797e012c7d2f 100644 --- a/eng/common/sdl/execute-all-sdl-tools.ps1 +++ b/eng/common/sdl/execute-all-sdl-tools.ps1 @@ -34,6 +34,7 @@ Param( [string] $GuardianLoggerLevel='Standard', # Optional: the logger level for the Guardian CLI; options are Trace, Verbose, Standard, Warning, and Error [string[]] $CrScanAdditionalRunConfigParams, # Optional: Additional Params to custom build a CredScan run config in the format @("xyz:abc","sdf:1") [string[]] $PoliCheckAdditionalRunConfigParams, # Optional: Additional Params to custom build a Policheck run config in the format @("xyz:abc","sdf:1") + [string[]] $CodeQLAdditionalRunConfigParams, # Optional: Additional Params to custom build a Semmle/CodeQL run config in the format @("xyz < abc","sdf < 1") [bool] $BreakOnFailure=$False # Optional: Fail the build if there were errors during the run ) @@ -105,7 +106,8 @@ try { -AzureDevOpsAccessToken $AzureDevOpsAccessToken ` -GuardianLoggerLevel $GuardianLoggerLevel ` -CrScanAdditionalRunConfigParams $CrScanAdditionalRunConfigParams ` - -PoliCheckAdditionalRunConfigParams $PoliCheckAdditionalRunConfigParams + -PoliCheckAdditionalRunConfigParams $PoliCheckAdditionalRunConfigParams ` + -CodeQLAdditionalRunConfigParams $CodeQLAdditionalRunConfigParams if ($BreakOnFailure) { Exit-IfNZEC "Sdl" } diff --git a/eng/common/templates/job/generate-graph-files.yml b/eng/common/templates/job/generate-graph-files.yml deleted file mode 100644 index e54ce956f9088..0000000000000 --- a/eng/common/templates/job/generate-graph-files.yml +++ /dev/null @@ -1,48 +0,0 @@ -parameters: - # Optional: dependencies of the job - dependsOn: '' - - # Optional: A defined YAML pool - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#pool - pool: {} - - # Optional: Include toolset dependencies in the generated graph files - includeToolset: false - -jobs: -- job: Generate_Graph_Files - - dependsOn: ${{ parameters.dependsOn }} - - displayName: Generate Graph Files - - pool: ${{ parameters.pool }} - - variables: - # Publish-Build-Assets provides: MaestroAccessToken, BotAccount-dotnet-maestro-bot-PAT - # DotNet-AllOrgs-Darc-Pats provides: dn-bot-devdiv-dnceng-rw-code-pat - - group: Publish-Build-Assets - - group: DotNet-AllOrgs-Darc-Pats - - name: _GraphArguments - value: -gitHubPat $(BotAccount-dotnet-maestro-bot-PAT) - -azdoPat $(dn-bot-devdiv-dnceng-rw-code-pat) - -barToken $(MaestroAccessToken) - -outputFolder '$(Build.StagingDirectory)/GraphFiles/' - - ${{ if ne(parameters.includeToolset, 'false') }}: - - name: _GraphArguments - value: ${{ variables._GraphArguments }} -includeToolset - - steps: - - task: PowerShell@2 - displayName: Generate Graph Files - inputs: - filePath: eng\common\generate-graph-files.ps1 - arguments: $(_GraphArguments) - continueOnError: true - - task: PublishBuildArtifacts@1 - displayName: Publish Graph to Artifacts - inputs: - PathtoPublish: '$(Build.StagingDirectory)/GraphFiles' - PublishLocation: Container - ArtifactName: GraphFiles - continueOnError: true - condition: always() diff --git a/eng/common/templates/jobs/codeql-build.yml b/eng/common/templates/jobs/codeql-build.yml new file mode 100644 index 0000000000000..f7dc5ea4aaa63 --- /dev/null +++ b/eng/common/templates/jobs/codeql-build.yml @@ -0,0 +1,31 @@ +parameters: + # See schema documentation in /Documentation/AzureDevOps/TemplateSchema.md + continueOnError: false + # Required: A collection of jobs to run - https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=vsts&tabs=schema#job + jobs: [] + # Optional: if specified, restore and use this version of Guardian instead of the default. + overrideGuardianVersion: '' + +jobs: +- template: /eng/common/templates/jobs/jobs.yml + parameters: + enableMicrobuild: false + enablePublishBuildArtifacts: false + enablePublishTestResults: false + enablePublishBuildAssets: false + enablePublishUsingPipelines: false + enableTelemetry: true + + variables: + - group: Publish-Build-Assets + # The Guardian version specified in 'eng/common/sdl/packages.config'. This value must be kept in + # sync with the packages.config file. + - name: DefaultGuardianVersion + value: 0.109.0 + - name: GuardianPackagesConfigFile + value: $(Build.SourcesDirectory)\eng\common\sdl\packages.config + - name: GuardianVersion + value: ${{ coalesce(parameters.overrideGuardianVersion, '$(DefaultGuardianVersion)') }} + + jobs: ${{ parameters.jobs }} + diff --git a/eng/common/templates/jobs/jobs.yml b/eng/common/templates/jobs/jobs.yml index 8dd1fdbd144a0..ff4ab75c886dc 100644 --- a/eng/common/templates/jobs/jobs.yml +++ b/eng/common/templates/jobs/jobs.yml @@ -87,13 +87,3 @@ jobs: runAsPublic: ${{ parameters.runAsPublic }} publishUsingPipelines: ${{ parameters.enablePublishUsingPipelines }} enablePublishBuildArtifacts: ${{ parameters.enablePublishBuildArtifacts }} - - - ${{ if eq(parameters.graphFileGeneration.enabled, true) }}: - - template: ../job/generate-graph-files.yml - parameters: - continueOnError: ${{ parameters.continueOnError }} - includeToolset: ${{ parameters.graphFileGeneration.includeToolset }} - dependsOn: - - Asset_Registry_Publish - pool: - vmImage: 'windows-2019' diff --git a/eng/common/templates/post-build/channels/generic-internal-channel.yml b/eng/common/templates/post-build/channels/generic-internal-channel.yml deleted file mode 100644 index 8990dfc8c87cc..0000000000000 --- a/eng/common/templates/post-build/channels/generic-internal-channel.yml +++ /dev/null @@ -1,190 +0,0 @@ -parameters: - BARBuildId: '' - PromoteToChannelIds: '' - artifactsPublishingAdditionalParameters: '' - dependsOn: - - Validate - publishInstallersAndChecksums: true - symbolPublishingAdditionalParameters: '' - stageName: '' - channelName: '' - channelId: '' - transportFeed: '' - shippingFeed: '' - symbolsFeed: '' - -stages: -- stage: ${{ parameters.stageName }} - dependsOn: ${{ parameters.dependsOn }} - variables: - - template: ../common-variables.yml - displayName: ${{ parameters.channelName }} Publishing - jobs: - - template: ../setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - job: publish_symbols - displayName: Symbol Publishing - dependsOn: setupMaestroVars - condition: contains(dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'], format('[{0}]', ${{ parameters.channelId }} )) - variables: - - group: DotNet-Symbol-Server-Pats - - name: AzDOProjectName - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] - - name: AzDOPipelineId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] - - name: AzDOBuildId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] - pool: - vmImage: 'windows-2019' - steps: - - script: echo "##vso[task.logissue type=warning]Going forward, v2 Arcade publishing is no longer supported. Please read https://github.com/dotnet/arcade/blob/main/Documentation/CorePackages/Publishing.md for details, then contact dnceng if you have further questions." - displayName: Warn about v2 Arcade Publishing Usage - - # This is necessary whenever we want to publish/restore to an AzDO private feed - - task: NuGetAuthenticate@0 - displayName: 'Authenticate to AzDO Feeds' - - - task: DownloadBuildArtifacts@0 - displayName: Download Build Assets - continueOnError: true - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - downloadType: 'specific' - itemPattern: | - PdbArtifacts/** - BlobArtifacts/** - downloadPath: '$(Build.ArtifactStagingDirectory)' - checkDownloadedFiles: true - - # This is necessary whenever we want to publish/restore to an AzDO private feed - # Since sdk-task.ps1 tries to restore packages we need to do this authentication here - # otherwise it'll complain about accessing a private feed. - - task: NuGetAuthenticate@0 - displayName: 'Authenticate to AzDO Feeds' - - - task: PowerShell@2 - displayName: Enable cross-org publishing - inputs: - filePath: eng\common\enable-cross-org-publishing.ps1 - arguments: -token $(dn-bot-dnceng-artifact-feeds-rw) - - - task: PowerShell@2 - displayName: Publish - inputs: - filePath: eng\common\sdk-task.ps1 - arguments: -task PublishToSymbolServers -restore -msbuildEngine dotnet - /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) - /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) - /p:PDBArtifactsDirectory='$(Build.ArtifactStagingDirectory)/PDBArtifacts/' - /p:BlobBasePath='$(Build.ArtifactStagingDirectory)/BlobArtifacts/' - /p:SymbolPublishingExclusionsFile='$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' - /p:Configuration=Release - /p:PublishToMSDL=false - ${{ parameters.symbolPublishingAdditionalParameters }} - - - template: ../../steps/publish-logs.yml - parameters: - StageLabel: '${{ parameters.stageName }}' - JobLabel: 'SymbolPublishing' - - - job: publish_assets - displayName: Publish Assets - dependsOn: setupMaestroVars - timeoutInMinutes: 120 - variables: - - name: BARBuildId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.BARBuildId'] ] - - name: IsStableBuild - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.IsStableBuild'] ] - - name: AzDOProjectName - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] - - name: AzDOPipelineId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] - - name: AzDOBuildId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] - condition: contains(dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'], format('[{0}]', ${{ parameters.channelId }} )) - pool: - vmImage: 'windows-2019' - steps: - - script: echo "##vso[task.logissue type=warning]Going forward, v2 Arcade publishing is no longer supported. Please read https://github.com/dotnet/arcade/blob/main/Documentation/CorePackages/Publishing.md for details, then contact dnceng if you have further questions." - displayName: Warn about v2 Arcade Publishing Usage - - - task: DownloadBuildArtifacts@0 - displayName: Download Build Assets - continueOnError: true - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - downloadType: 'specific' - itemPattern: | - PackageArtifacts/** - BlobArtifacts/** - AssetManifests/** - downloadPath: '$(Build.ArtifactStagingDirectory)' - checkDownloadedFiles: true - - - task: NuGetToolInstaller@1 - displayName: 'Install NuGet.exe' - - # This is necessary whenever we want to publish/restore to an AzDO private feed - - task: NuGetAuthenticate@0 - displayName: 'Authenticate to AzDO Feeds' - - - task: PowerShell@2 - displayName: Enable cross-org publishing - inputs: - filePath: eng\common\enable-cross-org-publishing.ps1 - arguments: -token $(dn-bot-dnceng-artifact-feeds-rw) - - - task: PowerShell@2 - displayName: Publish Assets - inputs: - filePath: eng\common\sdk-task.ps1 - arguments: -task PublishArtifactsInManifest -restore -msbuildEngine dotnet - /p:PublishingInfraVersion=2 - /p:IsStableBuild=$(IsStableBuild) - /p:IsInternalBuild=$(IsInternalBuild) - /p:RepositoryName=$(Build.Repository.Name) - /p:CommitSha=$(Build.SourceVersion) - /p:NugetPath=$(NuGetExeToolPath) - /p:AzdoTargetFeedPAT='$(dn-bot-dnceng-universal-packages-rw)' - /p:AzureStorageTargetFeedPAT='$(dotnetfeed-storage-access-key-1)' - /p:BARBuildId=$(BARBuildId) - /p:MaestroApiEndpoint='$(MaestroApiEndPoint)' - /p:BuildAssetRegistryToken='$(MaestroApiAccessToken)' - /p:ManifestsBasePath='$(Build.ArtifactStagingDirectory)/AssetManifests/' - /p:BlobBasePath='$(Build.ArtifactStagingDirectory)/BlobArtifacts/' - /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts/' - /p:Configuration=Release - /p:PublishInstallersAndChecksums=${{ parameters.publishInstallersAndChecksums }} - /p:ChecksumsTargetStaticFeed=$(InternalChecksumsBlobFeedUrl) - /p:ChecksumsAzureAccountKey=$(InternalChecksumsBlobFeedKey) - /p:InstallersTargetStaticFeed=$(InternalInstallersBlobFeedUrl) - /p:InstallersAzureAccountKey=$(InternalInstallersBlobFeedKey) - /p:AzureDevOpsStaticShippingFeed='${{ parameters.shippingFeed }}' - /p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' - /p:AzureDevOpsStaticTransportFeed='${{ parameters.transportFeed }}' - /p:AzureDevOpsStaticTransportFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' - /p:AzureDevOpsStaticSymbolsFeed='${{ parameters.symbolsFeed }}' - /p:AzureDevOpsStaticSymbolsFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' - /p:PublishToMSDL=false - ${{ parameters.artifactsPublishingAdditionalParameters }} - - - template: ../../steps/publish-logs.yml - parameters: - StageLabel: '${{ parameters.stageName }}' - JobLabel: 'AssetsPublishing' - - - template: ../../steps/add-build-to-channel.yml - parameters: - ChannelId: ${{ parameters.channelId }} diff --git a/eng/common/templates/post-build/channels/generic-public-channel.yml b/eng/common/templates/post-build/channels/generic-public-channel.yml deleted file mode 100644 index 3220c6a4f92ff..0000000000000 --- a/eng/common/templates/post-build/channels/generic-public-channel.yml +++ /dev/null @@ -1,192 +0,0 @@ -parameters: - BARBuildId: '' - PromoteToChannelIds: '' - artifactsPublishingAdditionalParameters: '' - dependsOn: - - Validate - publishInstallersAndChecksums: true - symbolPublishingAdditionalParameters: '' - stageName: '' - channelName: '' - channelId: '' - transportFeed: '' - shippingFeed: '' - symbolsFeed: '' - # If the channel name is empty, no links will be generated - akaMSChannelName: '' - -stages: -- stage: ${{ parameters.stageName }} - dependsOn: ${{ parameters.dependsOn }} - variables: - - template: ../common-variables.yml - displayName: ${{ parameters.channelName }} Publishing - jobs: - - template: ../setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - job: publish_symbols - displayName: Symbol Publishing - dependsOn: setupMaestroVars - condition: contains(dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'], format('[{0}]', ${{ parameters.channelId }} )) - variables: - - group: DotNet-Symbol-Server-Pats - - name: AzDOProjectName - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] - - name: AzDOPipelineId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] - - name: AzDOBuildId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] - pool: - vmImage: 'windows-2019' - steps: - - script: echo "##vso[task.logissue type=warning]Going forward, v2 Arcade publishing is no longer supported. Please read https://github.com/dotnet/arcade/blob/main/Documentation/CorePackages/Publishing.md for details, then contact dnceng if you have further questions." - displayName: Warn about v2 Arcade Publishing Usage - - - task: DownloadBuildArtifacts@0 - displayName: Download Build Assets - continueOnError: true - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - downloadType: 'specific' - itemPattern: | - PdbArtifacts/** - BlobArtifacts/** - downloadPath: '$(Build.ArtifactStagingDirectory)' - checkDownloadedFiles: true - - # This is necessary whenever we want to publish/restore to an AzDO private feed - # Since sdk-task.ps1 tries to restore packages we need to do this authentication here - # otherwise it'll complain about accessing a private feed. - - task: NuGetAuthenticate@0 - displayName: 'Authenticate to AzDO Feeds' - - - task: PowerShell@2 - displayName: Enable cross-org publishing - inputs: - filePath: eng\common\enable-cross-org-publishing.ps1 - arguments: -token $(dn-bot-dnceng-artifact-feeds-rw) - - - task: PowerShell@2 - displayName: Publish - inputs: - filePath: eng\common\sdk-task.ps1 - arguments: -task PublishToSymbolServers -restore -msbuildEngine dotnet - /p:DotNetSymbolServerTokenMsdl=$(microsoft-symbol-server-pat) - /p:DotNetSymbolServerTokenSymWeb=$(symweb-symbol-server-pat) - /p:PDBArtifactsDirectory='$(Build.ArtifactStagingDirectory)/PDBArtifacts/' - /p:BlobBasePath='$(Build.ArtifactStagingDirectory)/BlobArtifacts/' - /p:SymbolPublishingExclusionsFile='$(Build.SourcesDirectory)/eng/SymbolPublishingExclusionsFile.txt' - /p:Configuration=Release - ${{ parameters.symbolPublishingAdditionalParameters }} - - - template: ../../steps/publish-logs.yml - parameters: - StageLabel: '${{ parameters.stageName }}' - JobLabel: 'SymbolPublishing' - - - job: publish_assets - displayName: Publish Assets - dependsOn: setupMaestroVars - timeoutInMinutes: 120 - variables: - - name: BARBuildId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.BARBuildId'] ] - - name: IsStableBuild - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.IsStableBuild'] ] - - name: AzDOProjectName - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOProjectName'] ] - - name: AzDOPipelineId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOPipelineId'] ] - - name: AzDOBuildId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.AzDOBuildId'] ] - - name: ArtifactsCategory - value: ${{ coalesce(variables._DotNetArtifactsCategory, '.NETCore') }} - condition: contains(dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'], format('[{0}]', ${{ parameters.channelId }} )) - pool: - vmImage: 'windows-2019' - steps: - - script: echo "##vso[task.logissue type=warning]Going forward, v2 Arcade publishing is no longer supported. Please read https://github.com/dotnet/arcade/blob/main/Documentation/CorePackages/Publishing.md for details, then contact dnceng if you have further questions." - displayName: Warn about v2 Arcade Publishing Usage - - - task: DownloadBuildArtifacts@0 - displayName: Download Build Assets - continueOnError: true - inputs: - buildType: specific - buildVersionToDownload: specific - project: $(AzDOProjectName) - pipeline: $(AzDOPipelineId) - buildId: $(AzDOBuildId) - downloadType: 'specific' - itemPattern: | - PackageArtifacts/** - BlobArtifacts/** - AssetManifests/** - downloadPath: '$(Build.ArtifactStagingDirectory)' - checkDownloadedFiles: true - - - task: NuGetToolInstaller@1 - displayName: 'Install NuGet.exe' - - # This is necessary whenever we want to publish/restore to an AzDO private feed - - task: NuGetAuthenticate@0 - displayName: 'Authenticate to AzDO Feeds' - - - task: PowerShell@2 - displayName: Enable cross-org publishing - inputs: - filePath: eng\common\enable-cross-org-publishing.ps1 - arguments: -token $(dn-bot-dnceng-artifact-feeds-rw) - - - task: PowerShell@2 - displayName: Publish Assets - inputs: - filePath: eng\common\sdk-task.ps1 - arguments: -task PublishArtifactsInManifest -restore -msbuildEngine dotnet - /p:PublishingInfraVersion=2 - /p:ArtifactsCategory=$(ArtifactsCategory) - /p:IsStableBuild=$(IsStableBuild) - /p:IsInternalBuild=$(IsInternalBuild) - /p:RepositoryName=$(Build.Repository.Name) - /p:CommitSha=$(Build.SourceVersion) - /p:NugetPath=$(NuGetExeToolPath) - /p:AzdoTargetFeedPAT='$(dn-bot-dnceng-universal-packages-rw)' - /p:AzureStorageTargetFeedPAT='$(dotnetfeed-storage-access-key-1)' - /p:BARBuildId=$(BARBuildId) - /p:MaestroApiEndpoint='$(MaestroApiEndPoint)' - /p:BuildAssetRegistryToken='$(MaestroApiAccessToken)' - /p:ManifestsBasePath='$(Build.ArtifactStagingDirectory)/AssetManifests/' - /p:BlobBasePath='$(Build.ArtifactStagingDirectory)/BlobArtifacts/' - /p:PackageBasePath='$(Build.ArtifactStagingDirectory)/PackageArtifacts/' - /p:Configuration=Release - /p:PublishInstallersAndChecksums=${{ parameters.publishInstallersAndChecksums }} - /p:InstallersTargetStaticFeed=$(InstallersBlobFeedUrl) - /p:InstallersAzureAccountKey=$(dotnetcli-storage-key) - /p:ChecksumsTargetStaticFeed=$(ChecksumsBlobFeedUrl) - /p:ChecksumsAzureAccountKey=$(dotnetclichecksums-storage-key) - /p:AzureDevOpsStaticShippingFeed='${{ parameters.shippingFeed }}' - /p:AzureDevOpsStaticShippingFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' - /p:AzureDevOpsStaticTransportFeed='${{ parameters.transportFeed }}' - /p:AzureDevOpsStaticTransportFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' - /p:AzureDevOpsStaticSymbolsFeed='${{ parameters.symbolsFeed }}' - /p:AzureDevOpsStaticSymbolsFeedKey='$(dn-bot-dnceng-artifact-feeds-rw)' - /p:LatestLinkShortUrlPrefix=dotnet/'${{ parameters.akaMSChannelName }}' - /p:AkaMSClientId=$(akams-client-id) - /p:AkaMSClientSecret=$(akams-client-secret) - ${{ parameters.artifactsPublishingAdditionalParameters }} - - - template: ../../steps/publish-logs.yml - parameters: - StageLabel: '${{ parameters.stageName }}' - JobLabel: 'AssetsPublishing' - - - template: ../../steps/add-build-to-channel.yml - parameters: - ChannelId: ${{ parameters.channelId }} diff --git a/eng/common/templates/post-build/post-build.yml b/eng/common/templates/post-build/post-build.yml index 4f79cf0f33703..8985b429c8543 100644 --- a/eng/common/templates/post-build/post-build.yml +++ b/eng/common/templates/post-build/post-build.yml @@ -1,71 +1,89 @@ parameters: - # Which publishing infra should be used. THIS SHOULD MATCH THE VERSION ON THE BUILD MANIFEST. - # Publishing V2 accepts optionally outlining the publishing stages - default is inline. - # Publishing V3 DOES NOT accept inlining the publishing stages. - publishingInfraVersion: 2 - # When set to true the publishing templates from the repo will be used - # otherwise Darc add-build-to-channel will be used to trigger the promotion pipeline - inline: true - - # Only used if inline==false. When set to true will stall the current build until - # the Promotion Pipeline build finishes. Otherwise, the current build will continue - # execution concurrently with the promotion build. - waitPublishingFinish: true - - BARBuildId: '' - PromoteToChannelIds: '' - - enableSourceLinkValidation: false - enableSigningValidation: true - enableSymbolValidation: false - enableNugetValidation: true - publishInstallersAndChecksums: true - SDLValidationParameters: - enable: false - continueOnError: false - params: '' - artifactNames: '' - downloadArtifacts: true + # Which publishing infra should be used. THIS SHOULD MATCH THE VERSION ON THE BUILD MANIFEST. + # Publishing V1 is no longer supported + # Publishing V2 is no longer supported + # Publishing V3 is the default + - name: publishingInfraVersion + displayName: Which version of publishing should be used to promote the build definition? + type: number + default: 3 + values: + - 3 + + - name: BARBuildId + displayName: BAR Build Id + type: number + default: 0 + + - name: PromoteToChannelIds + displayName: Channel to promote BARBuildId to + type: string + default: '' + + - name: enableSourceLinkValidation + displayName: Enable SourceLink validation + type: boolean + default: false + + - name: enableSigningValidation + displayName: Enable signing validation + type: boolean + default: true + + - name: enableSymbolValidation + displayName: Enable symbol validation + type: boolean + default: false + + - name: enableNugetValidation + displayName: Enable NuGet validation + type: boolean + default: true + + - name: publishInstallersAndChecksums + displayName: Publish installers and checksums + type: boolean + default: true + + - name: SDLValidationParameters + type: object + default: + enable: false + continueOnError: false + params: '' + artifactNames: '' + downloadArtifacts: true # These parameters let the user customize the call to sdk-task.ps1 for publishing # symbols & general artifacts as well as for signing validation - symbolPublishingAdditionalParameters: '' - artifactsPublishingAdditionalParameters: '' - signingValidationAdditionalParameters: '' + - name: symbolPublishingAdditionalParameters + displayName: Symbol publishing additional parameters + type: string + default: '' + + - name: artifactsPublishingAdditionalParameters + displayName: Artifact publishing additional parameters + type: string + default: '' + + - name: signingValidationAdditionalParameters + displayName: Signing validation additional parameters + type: string + default: '' # Which stages should finish execution before post-build stages start - validateDependsOn: - - build - publishDependsOn: - - Validate + - name: validateDependsOn + type: object + default: + - build - # Channel ID's instantiated in this file. - # When adding a new channel implementation the call to `check-channel-consistency.ps1` - # needs to be updated with the new channel ID - NetEngLatestChannelId: 2 - NetEngValidationChannelId: 9 - NetDev5ChannelId: 131 - NetDev6ChannelId: 1296 - GeneralTestingChannelId: 529 - NETCoreToolingDevChannelId: 548 - NETCoreToolingReleaseChannelId: 549 - NETInternalToolingChannelId: 551 - NETCoreExperimentalChannelId: 562 - NetEngServicesIntChannelId: 678 - NetEngServicesProdChannelId: 679 - NetCoreSDK313xxChannelId: 759 - NetCoreSDK313xxInternalChannelId: 760 - NetCoreSDK314xxChannelId: 921 - NetCoreSDK314xxInternalChannelId: 922 - VS166ChannelId: 1010 - VS167ChannelId: 1011 - VS168ChannelId: 1154 - VSMasterChannelId: 1012 - VS169ChannelId: 1473 - VS1610ChannelId: 1692 + - name: publishDependsOn + type: object + default: + - Validate stages: -- ${{ if or(and(le(parameters.publishingInfraVersion, 2), eq(parameters.inline, 'true')), eq( parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: +- ${{ if or(eq( parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: - stage: Validate dependsOn: ${{ parameters.validateDependsOn }} displayName: Validate Build Assets @@ -77,23 +95,6 @@ stages: BARBuildId: ${{ parameters.BARBuildId }} PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - ${{ if and(le(parameters.publishingInfraVersion, 2), eq(parameters.inline, 'true')) }}: - - job: - displayName: Post-build Checks - dependsOn: setupMaestroVars - variables: - - name: TargetChannels - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.TargetChannels'] ] - pool: - vmImage: 'windows-2019' - steps: - - task: PowerShell@2 - displayName: Maestro Channels Consistency - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/check-channel-consistency.ps1 - arguments: -PromoteToChannels "$(TargetChannels)" - -AvailableChannelIds ${{parameters.NetEngLatestChannelId}},${{parameters.NetEngValidationChannelId}},${{parameters.NetDev5ChannelId}},${{parameters.NetDev6ChannelId}},${{parameters.GeneralTestingChannelId}},${{parameters.NETCoreToolingDevChannelId}},${{parameters.NETCoreToolingReleaseChannelId}},${{parameters.NETInternalToolingChannelId}},${{parameters.NETCoreExperimentalChannelId}},${{parameters.NetEngServicesIntChannelId}},${{parameters.NetEngServicesProdChannelId}},${{parameters.NetCoreSDK313xxChannelId}},${{parameters.NetCoreSDK313xxInternalChannelId}},${{parameters.NetCoreSDK314xxChannelId}},${{parameters.NetCoreSDK314xxInternalChannelId}},${{parameters.VS166ChannelId}},${{parameters.VS167ChannelId}},${{parameters.VS168ChannelId}},${{parameters.VSMasterChannelId}},${{parameters.VS169ChannelId}},${{parameters.VS1610ChannelId}} - - job: displayName: NuGet Validation dependsOn: setupMaestroVars @@ -229,361 +230,38 @@ stages: artifactNames: ${{ parameters.SDLValidationParameters.artifactNames }} downloadArtifacts: ${{ parameters.SDLValidationParameters.downloadArtifacts }} -- ${{ if or(ge(parameters.publishingInfraVersion, 3), eq(parameters.inline, 'false')) }}: - - stage: publish_using_darc - ${{ if or(eq(parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: - dependsOn: ${{ parameters.publishDependsOn }} - ${{ if and(ne(parameters.enableNugetValidation, 'true'), ne(parameters.enableSigningValidation, 'true'), ne(parameters.enableSourceLinkValidation, 'true'), ne(parameters.SDLValidationParameters.enable, 'true')) }}: - dependsOn: ${{ parameters.validateDependsOn }} - displayName: Publish using Darc - variables: - - template: common-variables.yml - jobs: - - template: setup-maestro-vars.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - - - job: - displayName: Publish Using Darc - dependsOn: setupMaestroVars - timeoutInMinutes: 120 - variables: - - name: BARBuildId - value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.BARBuildId'] ] - pool: - vmImage: 'windows-2019' - steps: - - task: PowerShell@2 - displayName: Publish Using Darc - inputs: - filePath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 - arguments: -BuildId $(BARBuildId) - -PublishingInfraVersion ${{ parameters.PublishingInfraVersion }} - -AzdoToken '$(publishing-dnceng-devdiv-code-r-build-re)' - -MaestroToken '$(MaestroApiAccessToken)' - -WaitPublishingFinish ${{ parameters.waitPublishingFinish }} - -PublishInstallersAndChecksums ${{ parameters.publishInstallersAndChecksums }} - -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' - -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' - -- ${{ if and(le(parameters.publishingInfraVersion, 2), eq(parameters.inline, 'true')) }}: - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NetCore_Dev5_Publish' - channelName: '.NET 5 Dev' - akaMSChannelName: 'net5/dev' - channelId: ${{ parameters.NetDev5ChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NetCore_Dev6_Publish' - channelName: '.NET 6 Dev' - akaMSChannelName: 'net6/dev' - channelId: ${{ parameters.NetDev6ChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet6-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet6/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet6-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml +- stage: publish_using_darc + ${{ if or(eq(parameters.enableNugetValidation, 'true'), eq(parameters.enableSigningValidation, 'true'), eq(parameters.enableSourceLinkValidation, 'true'), eq(parameters.SDLValidationParameters.enable, 'true')) }}: + dependsOn: ${{ parameters.publishDependsOn }} + ${{ if and(ne(parameters.enableNugetValidation, 'true'), ne(parameters.enableSigningValidation, 'true'), ne(parameters.enableSourceLinkValidation, 'true'), ne(parameters.SDLValidationParameters.enable, 'true')) }}: + dependsOn: ${{ parameters.validateDependsOn }} + displayName: Publish using Darc + variables: + - template: common-variables.yml + jobs: + - template: setup-maestro-vars.yml parameters: BARBuildId: ${{ parameters.BARBuildId }} PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'Net_Eng_Latest_Publish' - channelName: '.NET Eng - Latest' - akaMSChannelName: 'eng/daily' - channelId: ${{ parameters.NetEngLatestChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng-symbols/nuget/v3/index.json' - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'Net_Eng_Validation_Publish' - channelName: '.NET Eng - Validation' - akaMSChannelName: 'eng/validation' - channelId: ${{ parameters.NetEngValidationChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'General_Testing_Publish' - channelName: 'General Testing' - akaMSChannelName: 'generaltesting' - channelId: ${{ parameters.GeneralTestingChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/general-testing/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/general-testing/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/general-testing-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NETCore_Tooling_Dev_Publishing' - channelName: '.NET Core Tooling Dev' - channelId: ${{ parameters.NETCoreToolingDevChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NETCore_Tooling_Release_Publishing' - channelName: '.NET Core Tooling Release' - channelId: ${{ parameters.NETCoreToolingReleaseChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-internal-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NET_Internal_Tooling_Publishing' - channelName: '.NET Internal Tooling' - channelId: ${{ parameters.NETInternalToolingChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/internal/_packaging/dotnet-tools-internal/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/internal/_packaging/dotnet-tools-internal/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/internal/_packaging/dotnet-tools-internal-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NETCore_Experimental_Publishing' - channelName: '.NET Core Experimental' - channelId: ${{ parameters.NETCoreExperimentalChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-experimental/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-experimental/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-experimental-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'Net_Eng_Services_Int_Publish' - channelName: '.NET Eng Services - Int' - channelId: ${{ parameters.NetEngServicesIntChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'Net_Eng_Services_Prod_Publish' - channelName: '.NET Eng Services - Prod' - channelId: ${{ parameters.NetEngServicesProdChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NETCore_SDK_314xx_Publishing' - channelName: '.NET Core SDK 3.1.4xx' - channelId: ${{ parameters.NetCoreSDK314xxChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-internal-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NETCore_SDK_314xx_Internal_Publishing' - channelName: '.NET Core SDK 3.1.4xx Internal' - channelId: ${{ parameters.NetCoreSDK314xxInternalChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NETCore_SDK_313xx_Publishing' - channelName: '.NET Core SDK 3.1.3xx' - channelId: ${{ parameters.NetCoreSDK313xxChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet3.1-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-internal-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'NETCore_SDK_313xx_Internal_Publishing' - channelName: '.NET Core SDK 3.1.3xx Internal' - channelId: ${{ parameters.NetCoreSDK313xxInternalChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/_packaging/dotnet3.1-internal-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'VS16_6_Publishing' - channelName: 'VS 16.6' - channelId: ${{ parameters.VS166ChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'VS16_7_Publishing' - channelName: 'VS 16.7' - channelId: ${{ parameters.VS167ChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'VS16_8_Publishing' - channelName: 'VS 16.8' - channelId: ${{ parameters.VS168ChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'VS_Master_Publishing' - channelName: 'VS Master' - channelId: ${{ parameters.VSMasterChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'VS_16_9_Publishing' - channelName: 'VS 16.9' - channelId: ${{ parameters.VS169ChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' - - - template: \eng\common\templates\post-build\channels\generic-public-channel.yml - parameters: - BARBuildId: ${{ parameters.BARBuildId }} - PromoteToChannelIds: ${{ parameters.PromoteToChannelIds }} - artifactsPublishingAdditionalParameters: ${{ parameters.artifactsPublishingAdditionalParameters }} - dependsOn: ${{ parameters.publishDependsOn }} - publishInstallersAndChecksums: ${{ parameters.publishInstallersAndChecksums }} - symbolPublishingAdditionalParameters: ${{ parameters.symbolPublishingAdditionalParameters }} - stageName: 'VS_16_10_Publishing' - channelName: 'VS 16.10' - channelId: ${{ parameters.VS1610ChannelId }} - transportFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-transport/nuget/v3/index.json' - shippingFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json' - symbolsFeed: 'https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools-symbols/nuget/v3/index.json' + - job: + displayName: Publish Using Darc + dependsOn: setupMaestroVars + timeoutInMinutes: 120 + variables: + - name: BARBuildId + value: $[ dependencies.setupMaestroVars.outputs['setReleaseVars.BARBuildId'] ] + pool: + vmImage: 'windows-2019' + steps: + - task: PowerShell@2 + displayName: Publish Using Darc + inputs: + filePath: $(Build.SourcesDirectory)/eng/common/post-build/publish-using-darc.ps1 + arguments: -BuildId $(BARBuildId) + -PublishingInfraVersion ${{ parameters.publishingInfraVersion }} + -AzdoToken '$(publishing-dnceng-devdiv-code-r-build-re)' + -MaestroToken '$(MaestroApiAccessToken)' + -WaitPublishingFinish true + -ArtifactsPublishingAdditionalParameters '${{ parameters.artifactsPublishingAdditionalParameters }}' + -SymbolPublishingAdditionalParameters '${{ parameters.symbolPublishingAdditionalParameters }}' \ No newline at end of file diff --git a/eng/common/templates/steps/execute-codeql.yml b/eng/common/templates/steps/execute-codeql.yml new file mode 100644 index 0000000000000..3930b1630214b --- /dev/null +++ b/eng/common/templates/steps/execute-codeql.yml @@ -0,0 +1,32 @@ +parameters: + # Language that should be analyzed. Defaults to csharp + language: csharp + # Build Commands + buildCommands: '' + overrideParameters: '' # Optional: to override values for parameters. + additionalParameters: '' # Optional: parameters that need user specific values eg: '-SourceToolsList @("abc","def") -ArtifactToolsList @("ghi","jkl")' + # Optional: if specified, restore and use this version of Guardian instead of the default. + overrideGuardianVersion: '' + # Optional: if true, publish the '.gdn' folder as a pipeline artifact. This can help with in-depth + # diagnosis of problems with specific tool configurations. + publishGuardianDirectoryToPipeline: false + # The script to run to execute all SDL tools. Use this if you want to use a script to define SDL + # parameters rather than relying on YAML. It may be better to use a local script, because you can + # reproduce results locally without piecing together a command based on the YAML. + executeAllSdlToolsScript: 'eng/common/sdl/execute-all-sdl-tools.ps1' + # There is some sort of bug (has been reported) in Azure DevOps where if this parameter is named + # 'continueOnError', the parameter value is not correctly picked up. + # This can also be remedied by the caller (post-build.yml) if it does not use a nested parameter + # optional: determines whether to continue the build if the step errors; + sdlContinueOnError: false + +steps: +- template: /eng/common/templates/steps/execute-sdl.yml + parameters: + overrideGuardianVersion: ${{ parameters.overrideGuardianVersion }} + executeAllSdlToolsScript: ${{ parameters.executeAllSdlToolsScript }} + overrideParameters: ${{ parameters.overrideParameters }} + additionalParameters: '${{ parameters.additionalParameters }} + -CodeQLAdditionalRunConfigParams @("BuildCommands < ${{ parameters.buildCommands }}", "Language < ${{ parameters.language }}")' + publishGuardianDirectoryToPipeline: ${{ parameters.publishGuardianDirectoryToPipeline }} + sdlContinueOnError: ${{ parameters.sdlContinueOnError }} \ No newline at end of file diff --git a/eng/common/templates/steps/source-build.yml b/eng/common/templates/steps/source-build.yml index ba40dc82f1411..d85d6d07d5c7b 100644 --- a/eng/common/templates/steps/source-build.yml +++ b/eng/common/templates/steps/source-build.yml @@ -23,7 +23,7 @@ steps: # In addition, add an msbuild argument to copy the WIP from the repo to the target build location. # This is because SetupNuGetSources.sh will alter the current NuGet.config file, and we need to preserve those # changes. - $internalRestoreArgs= + internalRestoreArgs= if [ '$(dn-bot-dnceng-artifact-feeds-rw)' != '$''(dn-bot-dnceng-artifact-feeds-rw)' ]; then # Temporarily work around https://github.com/dotnet/arcade/issues/7709 chmod +x $(Build.SourcesDirectory)/eng/common/SetupNugetSources.sh diff --git a/eng/liveBuilds.targets b/eng/liveBuilds.targets index bc2e7e5dff9a0..aab934c42ae6b 100644 --- a/eng/liveBuilds.targets +++ b/eng/liveBuilds.targets @@ -24,6 +24,9 @@ $([MSBuild]::NormalizeDirectory('$(CoreCLRArtifactsPath)', 'sharedFramework')) $([MSBuild]::NormalizeDirectory('$(CoreCLRArtifactsPath)', 'crossgen2')) + $([MSBuild]::NormalizeDirectory('$(CoreCLRArtifactsPath)', 'ilc')) + $([MSBuild]::NormalizeDirectory('$(CoreCLRArtifactsPath)', 'aotsdk')) + $([MSBuild]::NormalizeDirectory('$(CoreCLRArtifactsPath)', 'build')) $([MSBuild]::NormalizeDirectory('$(MonoArtifactsPath)', 'cross', $(TargetOS.ToLowerInvariant())-$(TargetArchitecture.ToLowerInvariant()))) diff --git a/eng/native/build-commons.sh b/eng/native/build-commons.sh index 8f1a746752a34..373091b13a001 100755 --- a/eng/native/build-commons.sh +++ b/eng/native/build-commons.sh @@ -197,7 +197,7 @@ usage() echo "" echo "Common Options:" echo "" - echo "BuildArch can be: -arm, -armel, -arm64, -s390x, x64, x86, -wasm" + echo "BuildArch can be: -arm, -armel, -arm64, -loongarch64, -s390x, x64, x86, -wasm" echo "BuildType can be: -debug, -checked, -release" echo "-os: target OS (defaults to running OS)" echo "-bindir: output directory (defaults to $__ProjectRoot/artifacts)" @@ -377,6 +377,10 @@ while :; do __BuildArch=x64 ;; + loongarch64|-loongarch64) + __BuildArch=loongarch64 + ;; + s390x|-s390x) __BuildArch=s390x ;; diff --git a/eng/native/configurecompiler.cmake b/eng/native/configurecompiler.cmake index 5a20591cc025b..fad1ac58d39c8 100644 --- a/eng/native/configurecompiler.cmake +++ b/eng/native/configurecompiler.cmake @@ -216,6 +216,9 @@ elseif (CLR_CMAKE_HOST_ARCH_ARM) elseif (CLR_CMAKE_HOST_ARCH_ARM64) set(ARCH_HOST_NAME arm64) add_definitions(-DHOST_ARM64 -DHOST_64BIT) +elseif (CLR_CMAKE_HOST_ARCH_LOONGARCH64) + set(ARCH_HOST_NAME loongarch64) + add_definitions(-DHOST_LOONGARCH64 -DHOST_64BIT) elseif (CLR_CMAKE_HOST_ARCH_S390X) set(ARCH_HOST_NAME s390x) add_definitions(-DHOST_S390X -DHOST_64BIT -DBIGENDIAN) @@ -237,6 +240,8 @@ if (CLR_CMAKE_HOST_UNIX) message("Detected Linux ARM") elseif(CLR_CMAKE_HOST_UNIX_ARM64) message("Detected Linux ARM64") + elseif(CLR_CMAKE_HOST_UNIX_LOONGARCH64) + message("Detected Linux LOONGARCH64") elseif(CLR_CMAKE_HOST_UNIX_X86) message("Detected Linux i686") elseif(CLR_CMAKE_HOST_UNIX_S390X) @@ -301,6 +306,11 @@ elseif (CLR_CMAKE_TARGET_ARCH_I386) set(ARCH_SOURCES_DIR i386) add_compile_definitions($<$>>:TARGET_X86>) add_compile_definitions($<$>>:TARGET_32BIT>) +elseif (CLR_CMAKE_TARGET_ARCH_LOONGARCH64) + set(ARCH_TARGET_NAME loongarch64) + set(ARCH_SOURCES_DIR loongarch64) + add_compile_definitions($<$>>:TARGET_LOONGARCH64>) + add_compile_definitions($<$>>:TARGET_64BIT>) elseif (CLR_CMAKE_TARGET_ARCH_S390X) set(ARCH_TARGET_NAME s390x) set(ARCH_SOURCES_DIR s390x) diff --git a/eng/native/configureplatform.cmake b/eng/native/configureplatform.cmake index f5c8abe66991a..cdf33430b49f1 100644 --- a/eng/native/configureplatform.cmake +++ b/eng/native/configureplatform.cmake @@ -43,6 +43,8 @@ if(CLR_CMAKE_HOST_OS STREQUAL Linux) set(CLR_CMAKE_HOST_UNIX_ARM 1) elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL aarch64 OR CMAKE_SYSTEM_PROCESSOR STREQUAL arm64) set(CLR_CMAKE_HOST_UNIX_ARM64 1) + elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL loongarch64 OR CMAKE_SYSTEM_PROCESSOR STREQUAL loongarch64) + set(CLR_CMAKE_HOST_UNIX_LOONGARCH64 1) elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL i686 OR CMAKE_SYSTEM_PROCESSOR STREQUAL x86) set(CLR_CMAKE_HOST_UNIX_X86 1) elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL s390x) @@ -218,6 +220,9 @@ if(CLR_CMAKE_HOST_UNIX_ARM) elseif(CLR_CMAKE_HOST_UNIX_ARM64) set(CLR_CMAKE_HOST_ARCH_ARM64 1) set(CLR_CMAKE_HOST_ARCH "arm64") +elseif(CLR_CMAKE_HOST_UNIX_LOONGARCH64) + set(CLR_CMAKE_HOST_ARCH_LOONGARCH64 1) + set(CLR_CMAKE_HOST_ARCH "loongarch64") elseif(CLR_CMAKE_HOST_UNIX_AMD64) set(CLR_CMAKE_HOST_ARCH_AMD64 1) set(CLR_CMAKE_HOST_ARCH "x64") @@ -268,6 +273,8 @@ if (CLR_CMAKE_TARGET_ARCH STREQUAL x64) set(CLR_CMAKE_TARGET_ARCH_I386 1) elseif(CLR_CMAKE_TARGET_ARCH STREQUAL arm64) set(CLR_CMAKE_TARGET_ARCH_ARM64 1) + elseif(CLR_CMAKE_TARGET_ARCH STREQUAL loongarch64) + set(CLR_CMAKE_TARGET_ARCH_LOONGARCH64 1) elseif(CLR_CMAKE_TARGET_ARCH STREQUAL arm) set(CLR_CMAKE_TARGET_ARCH_ARM 1) elseif(CLR_CMAKE_TARGET_ARCH STREQUAL armel) @@ -374,6 +381,8 @@ if(CLR_CMAKE_TARGET_UNIX) set(CLR_CMAKE_TARGET_UNIX_ARM 1) elseif(CLR_CMAKE_TARGET_ARCH STREQUAL arm64) set(CLR_CMAKE_TARGET_UNIX_ARM64 1) + elseif(CLR_CMAKE_TARGET_ARCH STREQUAL loongarch64) + set(CLR_CMAKE_TARGET_UNIX_LOONGARCH64 1) elseif(CLR_CMAKE_TARGET_ARCH STREQUAL x86) set(CLR_CMAKE_TARGET_UNIX_X86 1) elseif(CLR_CMAKE_TARGET_ARCH STREQUAL s390x) diff --git a/eng/native/functions.cmake b/eng/native/functions.cmake index 87b4d15734bf6..c4af68ba7dc61 100644 --- a/eng/native/functions.cmake +++ b/eng/native/functions.cmake @@ -4,10 +4,75 @@ function(clr_unknown_arch) elseif(CLR_CROSS_COMPONENTS_BUILD) message(FATAL_ERROR "Only AMD64, I386 host are supported for linux cross-architecture component. Found: ${CMAKE_SYSTEM_PROCESSOR}") else() - message(FATAL_ERROR "Only AMD64, ARM64 and ARM are supported. Found: ${CMAKE_SYSTEM_PROCESSOR}") + message(FATAL_ERROR "Only AMD64, ARM64, LOONGARCH64 and ARM are supported. Found: ${CMAKE_SYSTEM_PROCESSOR}") endif() endfunction() +# C to MASM include file translator +# This is replacement for the deprecated h2inc tool that used to be part of VS. +function(h2inc filename output) + file(STRINGS ${filename} lines) + get_filename_component(path "${filename}" DIRECTORY) + file(RELATIVE_PATH relative_filename "${CLR_REPO_ROOT_DIR}" "${filename}") + + file(APPEND "${output}" "// File start: ${relative_filename}\n") + + # Use of NEWLINE_CONSUME is needed for lines with trailing backslash + file(STRINGS ${filename} contents NEWLINE_CONSUME) + string(REGEX REPLACE "\\\\\n" "\\\\\\\\ \n" contents "${contents}") + string(REGEX REPLACE "\n" ";" lines "${contents}") + + foreach(line IN LISTS lines) + string(REGEX REPLACE "\\\\\\\\ " "\\\\" line "${line}") + + if(line MATCHES "^ *# pragma") + # Ignore pragmas + continue() + endif() + + if(line MATCHES "^ *# *include *\"(.*)\"") + # Expand includes. + h2inc("${path}/${CMAKE_MATCH_1}" "${output}") + continue() + endif() + + if(line MATCHES "^ *#define +([0-9A-Za-z_()]+) *(.*)") + # Augment #defines with their MASM equivalent + set(name "${CMAKE_MATCH_1}") + set(value "${CMAKE_MATCH_2}") + + # Note that we do not handle multiline constants + + # Strip comments from value + string(REGEX REPLACE "//.*" "" value "${value}") + string(REGEX REPLACE "/\\*.*\\*/" "" value "${value}") + + # Strip whitespaces from value + string(REPLACE " +$" "" value "${value}") + + # ignore #defines with arguments + if(NOT "${name}" MATCHES "\\(") + set(HEX_NUMBER_PATTERN "0x([0-9A-Fa-f]+)") + set(DECIMAL_NUMBER_PATTERN "(-?[0-9]+)") + + if("${value}" MATCHES "${HEX_NUMBER_PATTERN}") + string(REGEX REPLACE "${HEX_NUMBER_PATTERN}" "0\\1h" value "${value}") # Convert hex constants + file(APPEND "${output}" "${name} EQU ${value}\n") + elseif("${value}" MATCHES "${DECIMAL_NUMBER_PATTERN}" AND (NOT "${value}" MATCHES "[G-Zg-z]+" OR "${value}" MATCHES "\\(")) + string(REGEX REPLACE "${DECIMAL_NUMBER_PATTERN}" "\\1t" value "${value}") # Convert dec constants + file(APPEND "${output}" "${name} EQU ${value}\n") + else() + file(APPEND "${output}" "${name} TEXTEQU <${value}>\n") + endif() + endif() + endif() + + file(APPEND "${output}" "${line}\n") + endforeach() + + file(APPEND "${output}" "// File end: ${relative_filename}\n") +endfunction() + # Build a list of compiler definitions by putting -D in front of each define. function(get_compile_definitions DefinitionName) # Get the current list of definitions @@ -94,6 +159,10 @@ function(find_unwind_libs UnwindLibs) find_library(UNWIND_ARCH NAMES unwind-aarch64) endif() + if(CLR_CMAKE_HOST_ARCH_LOONGARCH64) + find_library(UNWIND_ARCH NAMES unwind-loongarch64) + endif() + if(CLR_CMAKE_HOST_ARCH_AMD64) find_library(UNWIND_ARCH NAMES unwind-x86_64) endif() diff --git a/eng/native/init-os-and-arch.sh b/eng/native/init-os-and-arch.sh index fc4078fa3a9aa..586534be1c8aa 100644 --- a/eng/native/init-os-and-arch.sh +++ b/eng/native/init-os-and-arch.sh @@ -37,6 +37,10 @@ case "$CPUName" in arch=arm64 ;; + loongarch64) + arch=loongarch64 + ;; + amd64|x86_64) arch=x64 ;; diff --git a/eng/native/tryrun.cmake b/eng/native/tryrun.cmake index 96199969da69c..e8a04c5698ad3 100644 --- a/eng/native/tryrun.cmake +++ b/eng/native/tryrun.cmake @@ -68,7 +68,7 @@ if(DARWIN) else() message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only arm64 or x64 is supported for OSX cross build!") endif() -elseif(TARGET_ARCH_NAME MATCHES "^(armel|arm|arm64|s390x|x86)$" OR FREEBSD OR ILLUMOS) +elseif(TARGET_ARCH_NAME MATCHES "^(armel|arm|arm64|loongarch64|s390x|x86)$" OR FREEBSD OR ILLUMOS) set_cache_value(FILE_OPS_CHECK_FERROR_OF_PREVIOUS_CALL_EXITCODE 1) set_cache_value(GETPWUID_R_SETS_ERRNO_EXITCODE 0) set_cache_value(HAS_POSIX_SEMAPHORES_EXITCODE 0) @@ -146,9 +146,9 @@ elseif(TARGET_ARCH_NAME MATCHES "^(armel|arm|arm64|s390x|x86)$" OR FREEBSD OR IL set_cache_value(HAVE_FUNCTIONAL_PTHREAD_ROBUST_MUTEXES_EXITCODE 0) endif() else() - message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64, s390x and x86 are supported!") + message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only armel, arm, arm64, loongarch64, s390x and x86 are supported!") endif() -if(TARGET_ARCH_NAME STREQUAL "x86" OR TARGET_ARCH_NAME STREQUAL "s390x") +if(TARGET_ARCH_NAME STREQUAL "x86" OR TARGET_ARCH_NAME STREQUAL "s390x" OR TARGET_ARCH_NAME STREQUAL "loongarch64") set_cache_value(HAVE_FUNCTIONAL_PTHREAD_ROBUST_MUTEXES_EXITCODE 0) endif() diff --git a/eng/packaging.targets b/eng/packaging.targets index 6d2bbce10da34..667837fbff106 100644 --- a/eng/packaging.targets +++ b/eng/packaging.targets @@ -23,6 +23,10 @@ '$(PreReleaseVersionLabel)' != 'servicing' and '$(GitHubRepositoryName)' != 'runtimelab'">true false + + true $(XmlDocFileRoot)1033\$(AssemblyName).xml true @@ -259,7 +263,7 @@ diff --git a/eng/pipelines/common/global-build-job.yml b/eng/pipelines/common/global-build-job.yml index cf30d702dda60..12d56d00e2d64 100644 --- a/eng/pipelines/common/global-build-job.yml +++ b/eng/pipelines/common/global-build-job.yml @@ -3,6 +3,7 @@ parameters: nameSuffix: '' buildArgs: '' archType: '' + hostedOs: '' osGroup: '' osSubgroup: '' container: '' @@ -35,8 +36,12 @@ parameters: jobs: - template: /eng/common/templates/job/job.yml parameters: - name: ${{ format('build_{0}{1}_{2}_{3}_{4}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.nameSuffix) }} - displayName: ${{ format('Build {0}{1} {2} {3} {4}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.nameSuffix) }} + ${{ if eq(parameters.hostedOs, '') }}: + name: ${{ format('build_{0}{1}_{2}_{3}_{4}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.nameSuffix) }} + displayName: ${{ format('Build {0}{1} {2} {3} {4}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig, parameters.nameSuffix) }} + ${{ if ne(parameters.hostedOs, '') }}: + name: ${{ format('build_{0}{1}_{2}_{3}_{4}_{5}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.hostedOs, parameters.buildConfig, parameters.nameSuffix) }} + displayName: ${{ format('Build {0}{1} {2} {3} {4} {5}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.hostedOs, parameters.buildConfig, parameters.nameSuffix) }} pool: ${{ parameters.pool }} container: ${{ parameters.container }} condition: and(succeeded(), ${{ parameters.condition }}) diff --git a/eng/pipelines/common/platform-matrix.yml b/eng/pipelines/common/platform-matrix.yml index ade8c7aab981b..282fa56755081 100644 --- a/eng/pipelines/common/platform-matrix.yml +++ b/eng/pipelines/common/platform-matrix.yml @@ -273,7 +273,6 @@ jobs: jobTemplate: ${{ parameters.jobTemplate }} helixQueuesTemplate: ${{ parameters.helixQueuesTemplate }} variables: ${{ parameters.variables }} - hostedOs: Linux osGroup: Browser archType: wasm targetRid: browser-wasm @@ -282,6 +281,7 @@ jobs: image: ubuntu-18.04-webassembly-20210707133424-12f133e registry: mcr jobParameters: + hostedOs: Linux runtimeFlavor: ${{ parameters.runtimeFlavor }} stagedBuild: ${{ parameters.stagedBuild }} buildConfig: ${{ parameters.buildConfig }} @@ -297,12 +297,12 @@ jobs: jobTemplate: ${{ parameters.jobTemplate }} helixQueuesTemplate: ${{ parameters.helixQueuesTemplate }} variables: ${{ parameters.variables }} - hostedOs: windows osGroup: Browser archType: wasm targetRid: browser-wasm platform: Browser_wasm_win jobParameters: + hostedOs: windows runtimeFlavor: ${{ parameters.runtimeFlavor }} stagedBuild: ${{ parameters.stagedBuild }} buildConfig: ${{ parameters.buildConfig }} diff --git a/eng/pipelines/common/templates/runtimes/run-test-job.yml b/eng/pipelines/common/templates/runtimes/run-test-job.yml index 04399d26a6a22..6aa8a54f24c0f 100644 --- a/eng/pipelines/common/templates/runtimes/run-test-job.yml +++ b/eng/pipelines/common/templates/runtimes/run-test-job.yml @@ -73,7 +73,7 @@ jobs: - ${{ if not(or(eq(parameters.runtimeVariant, 'minijit'), eq(parameters.runtimeVariant, 'monointerpreter'))) }}: - ${{ if eq(parameters.runtimeVariant, 'llvmfullaot') }}: - ${{ format('{0}_llvmaot_product_build_{1}{2}_{3}_{4}', parameters.runtimeFlavor, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig) }} - - ${{ if not(eq(parameters.runtimeVariant, 'llvmfullaot')) }}: + - ${{ if ne(parameters.runtimeVariant, 'llvmfullaot') }}: - ${{ format('{0}_{1}_product_build_{2}{3}_{4}_{5}', parameters.runtimeFlavor, parameters.runtimeVariant, parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.buildConfig) }} - ${{ if ne(parameters.liveLibrariesBuildConfig, '') }}: - ${{ format('libraries_build_{0}{1}_{2}_{3}', parameters.osGroup, parameters.osSubgroup, parameters.archType, parameters.liveLibrariesBuildConfig) }} @@ -109,7 +109,7 @@ jobs: - name: runtimeVariantArg value: '' - - ${{ if not(eq(parameters.runtimeVariant, '')) }}: + - ${{ if ne(parameters.runtimeVariant, '') }}: - name: runtimeVariantArg value: '/p:RuntimeVariant=${{ parameters.runtimeVariant }}' @@ -546,6 +546,7 @@ jobs: - jitosr - jitosr_stress - jitosr_pgo + - jitosr_stress_random - jitpartialcompilation - jitpartialcompilation_osr - jitpartialcompilation_osr_pgo diff --git a/eng/pipelines/common/variables.yml b/eng/pipelines/common/variables.yml index d6b84f837c327..6e378369aa4fc 100644 --- a/eng/pipelines/common/variables.yml +++ b/eng/pipelines/common/variables.yml @@ -11,19 +11,17 @@ variables: - name: isOfficialBuild value: ${{ and(ne(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }} -- name: isFullMatrix +- name: isRollingBuild value: ${{ and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }} -- name: isNotFullMatrix - value: ${{ and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }} -- name: isNotManualAndIsPR - value: ${{ and(not(in(variables['Build.DefinitionName'], 'runtime-staging-manual', 'runtime-manual')), eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }} -- name: isManualOrIsNotPR - value: ${{ or(in(variables['Build.DefinitionName'], 'runtime-staging-manual', 'runtime-manual'), and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest'))) }} +- name: isExtraPlatformsBuild + value: ${{ eq(variables['Build.DefinitionName'], 'runtime-extra-platforms') }} +- name: isNotExtraPlatformsBuild + value: ${{ ne(variables['Build.DefinitionName'], 'runtime-extra-platforms') }} # We only run evaluate paths on runtime, runtime-staging and runtime-community pipelines on PRs # keep in sync with /eng/pipelines/common/xplat-setup.yml - name: dependOnEvaluatePaths - value: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community')) }} + value: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms')) }} - name: debugOnPrReleaseOnRolling ${{ if ne(variables['Build.Reason'], 'PullRequest') }}: value: Release diff --git a/eng/pipelines/common/xplat-setup.yml b/eng/pipelines/common/xplat-setup.yml index 05a6bc7c4a63c..e397bcdd456a6 100644 --- a/eng/pipelines/common/xplat-setup.yml +++ b/eng/pipelines/common/xplat-setup.yml @@ -22,8 +22,7 @@ jobs: shouldContinueOnError: ${{ and(endsWith(variables['Build.DefinitionName'], 'staging'), eq(variables['Build.Reason'], 'PullRequest')) }} # keep in sync with /eng/pipelines/common/variables.yml - nonPRBuild: ${{ and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }} - dependOnEvaluatePaths: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community')) }} + dependOnEvaluatePaths: ${{ and(eq(variables['Build.Reason'], 'PullRequest'), in(variables['Build.DefinitionName'], 'runtime', 'runtime-staging', 'runtime-community', 'runtime-extra-platforms')) }} variables: # Disable component governance in our CI builds. These builds are not shipping nor @@ -50,8 +49,12 @@ jobs: value: $(buildConfigUpper) - name: _runSmokeTestsOnlyArg - value: '/p:RunSmokeTestsOnly=$(isNotManualAndIsPR)' - - ${{ if or(eq(parameters.osGroup, 'windows'), eq(parameters.hostedOs, 'windows')) }}: + value: '/p:RunSmokeTestsOnly=$(isNotExtraPlatformsBuild)' + + - name: _hostedOs + value: ${{ parameters.jobParameters.hostedOs }} + + - ${{ if or(eq(parameters.osGroup, 'windows'), eq(parameters.jobParameters.hostedOs, 'windows')) }}: - name: archiveExtension value: '.zip' - name: archiveType @@ -69,7 +72,7 @@ jobs: - name: logRootNameArg value: 'log ' - - ${{ if and(ne(parameters.osGroup, 'windows'), ne(parameters.hostedOs, 'windows')) }}: + - ${{ if and(ne(parameters.osGroup, 'windows'), ne(parameters.jobParameters.hostedOs, 'windows')) }}: - name: archiveExtension value: '.tar.gz' - name: archiveType @@ -117,12 +120,12 @@ jobs: ${{ if eq(parameters.jobParameters.pool, '') }}: pool: # Public Linux Build Pool - ${{ if and(or(in(parameters.osGroup, 'Linux', 'FreeBSD', 'Android', 'Tizen'), eq(parameters.hostedOs, 'Linux')), eq(variables['System.TeamProject'], 'public')) }}: + ${{ if and(or(in(parameters.osGroup, 'Linux', 'FreeBSD', 'Android', 'Tizen'), eq(parameters.jobParameters.hostedOs, 'Linux')), eq(variables['System.TeamProject'], 'public')) }}: name: NetCore1ESPool-Public demands: ImageOverride -equals Build.Ubuntu.1804.Amd64.Open # Official Build Linux Pool - ${{ if and(or(in(parameters.osGroup, 'Linux', 'FreeBSD', 'Browser', 'Android', 'Tizen'), eq(parameters.hostedOs, 'Linux')), ne(variables['System.TeamProject'], 'public')) }}: + ${{ if and(or(in(parameters.osGroup, 'Linux', 'FreeBSD', 'Browser', 'Android', 'Tizen'), eq(parameters.jobParameters.hostedOs, 'Linux')), ne(variables['System.TeamProject'], 'public')) }}: name: NetCore1ESPool-Internal demands: ImageOverride -equals Build.Ubuntu.1804.Amd64 @@ -136,7 +139,7 @@ jobs: demands: ImageOverride -equals Build.Windows.10.Amd64.VS2019 # Public Windows Build Pool - ${{ if and(or(eq(parameters.osGroup, 'windows'), eq(parameters.hostedOs, 'windows')), eq(variables['System.TeamProject'], 'public')) }}: + ${{ if and(or(eq(parameters.osGroup, 'windows'), eq(parameters.jobParameters.hostedOs, 'windows')), eq(variables['System.TeamProject'], 'public')) }}: name: NetCore1ESPool-Public demands: ImageOverride -equals Build.Windows.10.Amd64.VS2019.Open diff --git a/eng/pipelines/coreclr/perf_slow.yml b/eng/pipelines/coreclr/perf_slow.yml index e8410af6d361f..04994eac96a44 100644 --- a/eng/pipelines/coreclr/perf_slow.yml +++ b/eng/pipelines/coreclr/perf_slow.yml @@ -137,10 +137,11 @@ jobs: buildConfig: release container: ubuntu-18.04-cross-arm64-20211022152824-b2c2436 runtimeFlavor: mono + runtimeVariant: 'llvmaot' platforms: - Linux_arm64 jobParameters: - buildArgs: -s mono+libs+host+packs -c $(_BuildConfig) + buildArgs: -s mono+libs+host+packs -c $(_BuildConfig) /p:MonoEnableLLVM=true /p:MonoBundleLLVMOptimizer=true nameSuffix: AOT isOfficialBuild: false extraStepsTemplate: /eng/pipelines/common/upload-artifact-step.yml diff --git a/eng/pipelines/coreclr/superpmi-collect.yml b/eng/pipelines/coreclr/superpmi-collect.yml index 0d41f151d6b55..8918ee8cbfcd3 100644 --- a/eng/pipelines/coreclr/superpmi-collect.yml +++ b/eng/pipelines/coreclr/superpmi-collect.yml @@ -30,8 +30,7 @@ jobs: jobTemplate: /eng/pipelines/common/build-coreclr-and-libraries-job.yml buildConfig: checked platforms: - # Linux tests are built on the OSX machines. - # - OSX_x64 + - OSX_arm64 - Linux_arm - Linux_arm64 - Linux_x64 @@ -46,6 +45,16 @@ jobs: - Linux_x64 - windows_x64 +# superpmi-collect-job that targets macOS/arm64 depends on coreclr binaries produced by the macOS/x64 job +- template: /eng/pipelines/common/platform-matrix.yml + parameters: + jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml + buildConfig: checked + platforms: + - OSX_x64 + jobParameters: + testGroup: outerloop + - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml @@ -62,6 +71,7 @@ jobs: platforms: # Linux tests are built on the OSX machines. # - OSX_x64 + - OSX_arm64 - Linux_arm - Linux_arm64 - Linux_x64 @@ -83,6 +93,7 @@ jobs: platforms: # Linux tests are built on the OSX machines. # - OSX_x64 + - OSX_arm64 - Linux_arm - Linux_arm64 - Linux_x64 @@ -105,6 +116,7 @@ jobs: platforms: # Linux tests are built on the OSX machines. # - OSX_x64 + - OSX_arm64 - Linux_arm - Linux_arm64 - Linux_x64 @@ -127,6 +139,7 @@ jobs: platforms: # Linux tests are built on the OSX machines. # - OSX_x64 + - OSX_arm64 - Linux_arm - Linux_arm64 - Linux_x64 @@ -148,6 +161,7 @@ jobs: platforms: # Linux tests are built on the OSX machines. # - OSX_x64 + - OSX_arm64 #TODO: Need special handling of running "benchmark build" from inside TMP folder on helix machine. # - Linux_arm # - Linux_arm64 diff --git a/eng/pipelines/coreclr/templates/run-superpmi-collect-job.yml b/eng/pipelines/coreclr/templates/run-superpmi-collect-job.yml index 1ac235f6f6d08..be05b52b6b185 100644 --- a/eng/pipelines/coreclr/templates/run-superpmi-collect-job.yml +++ b/eng/pipelines/coreclr/templates/run-superpmi-collect-job.yml @@ -106,7 +106,7 @@ jobs: steps: - ${{ parameters.steps }} - - script: $(PythonScript) $(Build.SourcesDirectory)/src/coreclr/scripts/superpmi_collect_setup.py -source_directory $(Build.SourcesDirectory) -core_root_directory $(Core_Root_Dir) -arch $(archType) -mch_file_tag $(MchFileTag) -input_directory $(InputDirectory) -collection_name $(CollectionName) -collection_type $(CollectionType) -max_size 50 # size in MB + - script: $(PythonScript) $(Build.SourcesDirectory)/src/coreclr/scripts/superpmi_collect_setup.py -source_directory $(Build.SourcesDirectory) -core_root_directory $(Core_Root_Dir) -arch $(archType) -platform $(osGroup) -mch_file_tag $(MchFileTag) -input_directory $(InputDirectory) -collection_name $(CollectionName) -collection_type $(CollectionType) -max_size 50 # size in MB displayName: ${{ format('SuperPMI setup ({0})', parameters.osGroup) }} # Create required directories for merged mch collection and superpmi logs @@ -159,6 +159,10 @@ jobs: artifactName: 'SuperPMI_Collection_$(CollectionName)_$(CollectionType)_$(osGroup)$(osSubgroup)_$(archType)_$(buildConfig)' displayName: ${{ format('Upload artifacts SuperPMI {0}-{1} collection', parameters.collectionName, parameters.collectionType) }} + # Ensure the Python azure-storage-blob package is installed before doing the upload. + - script: $(PipScript) install --user --upgrade pip && $(PipScript) install --user azure.storage.blob==12.5.0 --force-reinstall + displayName: Upgrade Pip to latest and install azure-storage-blob Python package + - script: $(PythonScript) $(Build.SourcesDirectory)/src/coreclr/scripts/superpmi.py upload -log_level DEBUG -arch $(archType) -build_type $(buildConfig) -mch_files $(MergedMchFileLocation)$(CollectionName).$(CollectionType).$(MchFileTag).mch -core_root $(Build.SourcesDirectory)/artifacts/bin/coreclr/$(osGroup).x64.$(buildConfigUpper) displayName: ${{ format('Upload SuperPMI {0}-{1} collection to Azure Storage', parameters.collectionName, parameters.collectionType) }} env: diff --git a/eng/pipelines/coreclr/templates/superpmi-collect-job.yml b/eng/pipelines/coreclr/templates/superpmi-collect-job.yml index 6c990a25ff4aa..652d17af08eba 100644 --- a/eng/pipelines/coreclr/templates/superpmi-collect-job.yml +++ b/eng/pipelines/coreclr/templates/superpmi-collect-job.yml @@ -84,8 +84,8 @@ jobs: - template: /eng/pipelines/common/download-artifact-step.yml parameters: unpackFolder: '$(Build.SourcesDirectory)/artifacts/tests/libraries_zipped/$(osGroup).$(archType).$(buildConfigUpper)' - artifactFileName: 'libraries_test_assets_${{ parameters.osGroup }}_x64_Release$(archiveExtension)' - artifactName: ${{ format('libraries_test_assets_{0}_x64_Release', parameters.osGroup) }} + artifactFileName: 'libraries_test_assets_${{ parameters.osGroup }}_$(archType)_Release$(archiveExtension)' + artifactName: ${{ format('libraries_test_assets_{0}_$(archType)_Release', parameters.osGroup) }} displayName: 'generic libraries test artifacts' # Unzip individual test projects diff --git a/eng/pipelines/libraries/helix-queues-setup.yml b/eng/pipelines/libraries/helix-queues-setup.yml index ac074ab9903f8..644c64d975bac 100644 --- a/eng/pipelines/libraries/helix-queues-setup.yml +++ b/eng/pipelines/libraries/helix-queues-setup.yml @@ -28,26 +28,26 @@ jobs: # Linux arm - ${{ if eq(parameters.platform, 'Linux_arm') }}: - - ${{ if eq(parameters.jobParameters.isFullMatrix, true) }}: + - ${{ if or(eq(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - (Debian.10.Arm32.Open)Ubuntu.1804.ArmArch.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-10-helix-arm32v7-20210304164340-6616c63 - (Debian.11.Arm32.Open)Ubuntu.1804.ArmArch.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-11-helix-arm32v7-20210304164347-5a7c380 # Linux arm64 - ${{ if eq(parameters.platform, 'Linux_arm64') }}: - - ${{ if eq(parameters.jobParameters.isFullMatrix, true) }}: - - (Ubuntu.1804.ArmArch.Open)Ubuntu.1804.ArmArch.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-16.04-helix-arm64v8-20210106155927-56c6673 + - ${{ if or(eq(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - (Ubuntu.2110.Arm64.Open)Ubuntu.1804.ArmArch.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-21.10-helix-arm64v8-20211116135000-0f8d97e - - ${{ if eq(parameters.jobParameters.isFullMatrix, false) }}: + - ${{ if or(ne(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - (Ubuntu.1804.ArmArch.Open)Ubuntu.1804.ArmArch.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-16.04-helix-arm64v8-20210106155927-56c6673 # Linux musl x64 - ${{ if eq(parameters.platform, 'Linux_musl_x64') }}: - - (Alpine.314.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.14-helix-amd64-20210910135833-1848e19 - - ${{ if eq(parameters.jobParameters.isFullMatrix, true) }}: + - ${{ if or(ne(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: + - (Alpine.314.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.14-helix-amd64-20210910135833-1848e19 + - ${{ if or(eq(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - (Alpine.313.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.13-helix-amd64-20210910135845-8a6f4f3 # Linux musl arm64 - - ${{ if and(eq(parameters.platform, 'Linux_musl_arm64'), eq(parameters.jobParameters.isFullMatrix, true)) }}: + - ${{ if and(eq(parameters.platform, 'Linux_musl_arm64'), or(eq(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true))) }}: - (Alpine.313.Arm64.Open)ubuntu.1804.armarch.open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.13-helix-arm64v8-20210910135808-8a6f4f3 - (Alpine.314.Arm64.Open)ubuntu.1804.armarch.open@mcr.microsoft.com/dotnet-buildtools/prereqs:alpine-3.14-helix-arm64v8-20210910135810-8a6f4f3 @@ -62,21 +62,16 @@ jobs: - (Ubuntu.2110.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-21.10-helix-amd64-20211116135132-0f8d97e - (Debian.10.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-10-helix-amd64-bfcd90a-20200121150006 - ${{ if or(ne(parameters.jobParameters.testScope, 'outerloop'), ne(parameters.jobParameters.runtimeFlavor, 'mono')) }}: - - ${{ if eq(parameters.jobParameters.isFullMatrix, true) }}: - - (Centos.7.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:centos-7-mlnet-helix-20210714125435-dde38af - - (Centos.8.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:centos-8-helix-20201229003624-c1bf759 - - RedHat.7.Amd64.Open - - Ubuntu.1804.Amd64.Open - - SLES.12.Amd64.Open + - ${{ if or(eq(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: + - (Centos.8.Amd64.Open)Ubuntu.1604.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:centos-8-helix-20201229003624-c1bf759 - SLES.15.Amd64.Open - - (Fedora.34.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:fedora-34-helix-20210913123654-4f64125 - - (Ubuntu.2110.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-21.10-helix-amd64-20211116135132-0f8d97e - - (Debian.10.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-10-helix-amd64-20210304164434-56c6673 + - (Fedora.34.Amd64.Open)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:fedora-34-helix-20210913123654-4f64125 + - (Ubuntu.2110.Amd64.Open)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-21.04-helix-amd64-20210922170909-34a2d72 - (Debian.11.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-11-helix-amd64-20210304164428-5a7c380 - - (Mariner.1.0.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-1.0-helix-20210528192219-92bf620 - - (openSUSE.15.2.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:opensuse-15.2-helix-amd64-20211018152525-9cc02fe - - ${{ if eq(parameters.jobParameters.isFullMatrix, false) }}: - - (Centos.7.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:centos-7-mlnet-helix-20210714125435-dde38af + - (Mariner.1.0.Amd64.Open)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:cbl-mariner-1.0-helix-20210528192219-92bf620 + - (openSUSE.15.2.Amd64.Open)ubuntu.1604.amd64.open@mcr.microsoft.com/dotnet-buildtools/prereqs:opensuse-15.2-helix-amd64-20211018152525-9cc02fe + - ${{ if or(ne(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: + - (Centos.7.Amd64.Open)Ubuntu.1604.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:centos-7-mlnet-helix-20210714125435-dde38af - RedHat.7.Amd64.Open - (Debian.10.Amd64.Open)Ubuntu.1804.Amd64.Open@mcr.microsoft.com/dotnet-buildtools/prereqs:debian-10-helix-amd64-20210304164434-56c6673 - Ubuntu.1804.Amd64.Open @@ -94,10 +89,9 @@ jobs: # OSX x64 - ${{ if eq(parameters.platform, 'OSX_x64') }}: - - ${{ if eq(parameters.jobParameters.isFullMatrix, true) }}: + - ${{ if or(eq(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - OSX.1014.Amd64.Open - - OSX.1015.Amd64.Open - - ${{ if eq(parameters.jobParameters.isFullMatrix, false) }}: + - ${{ if or(ne(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - OSX.1015.Amd64.Open # Android @@ -126,18 +120,18 @@ jobs: - ${{ if eq(parameters.platform, 'windows_x64') }}: # netcoreapp - ${{ if notIn(parameters.jobParameters.framework, 'net48') }}: + # libraries on mono outerloop - ${{ if and(eq(parameters.jobParameters.testScope, 'outerloop'), eq(parameters.jobParameters.runtimeFlavor, 'mono')) }}: - Windows.81.Amd64.Open - Windows.10.Amd64.Server19H1.Open + # libraries on coreclr (outerloop and innerloop), or libraries on mono innerloop - ${{ if or(ne(parameters.jobParameters.testScope, 'outerloop'), ne(parameters.jobParameters.runtimeFlavor, 'mono')) }}: - - ${{ if eq(parameters.jobParameters.isFullMatrix, true) }}: - - Windows.81.Amd64.Open + - ${{ if or(eq(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - Windows.10.Amd64.ServerRS5.Open - - Windows.10.Amd64.Server19H1.Open - - ${{ if ne(parameters.jobParameters.runtimeFlavor, 'mono') }}: - - (Windows.Nano.1809.Amd64.Open)windows.10.amd64.serverrs5.open@mcr.microsoft.com/dotnet-buildtools/prereqs:nanoserver-1809-helix-amd64-08e8e40-20200107182504 + - ${{ if ne(parameters.jobParameters.testScope, 'outerloop') }}: + - Windows.10.Amd64.Server19H1.Open - (Windows.Server.Core.1909.Amd64.Open)windows.10.amd64.server20h1.open@mcr.microsoft.com/dotnet-buildtools/prereqs:windowsservercore-2004-helix-amd64-20200904200251-272704c - - ${{ if ne(parameters.jobParameters.isFullMatrix, true) }}: + - ${{ if or(ne(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - Windows.81.Amd64.Open - Windows.10.Amd64.Server19H1.ES.Open - Windows.11.Amd64.ClientPre.Open @@ -154,20 +148,18 @@ jobs: - ${{ if eq(parameters.platform, 'windows_x86') }}: # netcoreapp - ${{ if notIn(parameters.jobParameters.framework, 'net48') }}: + # mono outerloop - ${{ if and(eq(parameters.jobParameters.testScope, 'outerloop'), eq(parameters.jobParameters.runtimeFlavor, 'mono')) }}: - Windows.7.Amd64.Open - Windows.10.Amd64.ServerRS5.Open + # libraries on coreclr (outerloop and innerloop), or libraries on mono innerloop - ${{ if or(ne(parameters.jobParameters.testScope, 'outerloop'), ne(parameters.jobParameters.runtimeFlavor, 'mono')) }}: - - ${{ if eq(parameters.jobParameters.isFullMatrix, true) }}: - - Windows.7.Amd64.Open + - ${{ if or(eq(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: - Windows.10.Amd64.ServerRS5.Open - Windows.10.Amd64.Server19H1.Open - - ${{ if ne(parameters.jobParameters.isFullMatrix, true) }}: - - ${{ if eq(parameters.jobParameters.buildConfig, 'Release') }}: - - Windows.10.Amd64.Server19H1.ES.Open - - ${{ if eq(parameters.jobParameters.buildConfig, 'Debug') }}: - - Windows.7.Amd64.Open - - Windows.10.Amd64.Server19H1.Open + - ${{ if or(ne(parameters.jobParameters.isExtraPlatforms, true), eq(parameters.jobParameters.includeAllPlatforms, true)) }}: + - Windows.10.Amd64.Server19H1.ES.Open + - Windows.7.Amd64.Open # .NETFramework - ${{ if eq(parameters.jobParameters.framework, 'net48') }}: diff --git a/eng/pipelines/libraries/outerloop-mono.yml b/eng/pipelines/libraries/outerloop-mono.yml index 1267cf72a62de..17a7101e26004 100644 --- a/eng/pipelines/libraries/outerloop-mono.yml +++ b/eng/pipelines/libraries/outerloop-mono.yml @@ -23,7 +23,7 @@ jobs: platforms: - windows_x86 - Browser_wasm - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - windows_x64 - Linux_x64 - Linux_arm @@ -34,7 +34,7 @@ jobs: nameSuffix: AllSubsets_Mono buildArgs: -s mono+libs+libs.tests -c $(_BuildConfig) -testscope outerloop /p:ArchiveTests=true timeoutInMinutes: 180 - isFullMatrix: ${{ variables['isFullMatrix'] }} + includeAllPlatforms: ${{ variables['isRollingBuild'] }} # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -44,7 +44,7 @@ jobs: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) - - ${{ if eq(variables['isFullMatrix'], false) }}: + - ${{ if eq(variables['isRollingBuild'], false) }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/global-build-job.yml @@ -61,7 +61,7 @@ jobs: nameSuffix: AllSubsets_Mono buildArgs: -s mono+libs+libs.tests -c $(_BuildConfig) -testscope outerloop /p:ArchiveTests=true timeoutInMinutes: 180 - isFullMatrix: ${{ variables['isFullMatrix'] }} + includeAllPlatforms: ${{ variables['isRollingBuild'] }} # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: diff --git a/eng/pipelines/libraries/outerloop.yml b/eng/pipelines/libraries/outerloop.yml index 28932a0baff3c..72c2de49363a2 100644 --- a/eng/pipelines/libraries/outerloop.yml +++ b/eng/pipelines/libraries/outerloop.yml @@ -27,7 +27,7 @@ jobs: - ${{ if eq(variables['includeLinuxOuterloop'], true) }}: - Linux_x64 - Linux_musl_x64 - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - Linux_arm - Linux_arm64 - Linux_musl_arm64 @@ -46,27 +46,27 @@ jobs: platforms: - ${{ if eq(variables['includeWindowsOuterloop'], true) }}: - windows_x86 - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - windows_x64 - ${{ if eq(variables['includeLinuxOuterloop'], true) }}: - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - Linux_x64 - Linux_arm - Linux_arm64 - Linux_musl_x64 - Linux_musl_arm64 - - ${{ if and(eq(variables['includeOsxOuterloop'], true), eq(variables['isFullMatrix'], true)) }}: + - ${{ if and(eq(variables['includeOsxOuterloop'], true), eq(variables['isRollingBuild'], true)) }}: - OSX_arm64 - OSX_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} - isFullMatrix: ${{ variables['isFullMatrix'] }} + includeAllPlatforms: ${{ variables['isRollingBuild'] }} runTests: true testScope: outerloop liveRuntimeBuildConfig: release - - ${{ if eq(variables['isFullMatrix'], false) }}: + - ${{ if eq(variables['isRollingBuild'], false) }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml @@ -83,7 +83,7 @@ jobs: helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} - isFullMatrix: ${{ variables['isFullMatrix'] }} + includeAllPlatforms: ${{ variables['isRollingBuild'] }} runTests: true testScope: outerloop liveRuntimeBuildConfig: release @@ -95,12 +95,12 @@ jobs: buildConfig: Release platforms: - windows_x86 - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - windows_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} - isFullMatrix: ${{ variables['isFullMatrix'] }} + includeAllPlatforms: ${{ variables['isRollingBuild'] }} framework: net48 runTests: true testScope: outerloop diff --git a/eng/pipelines/libraries/variables.yml b/eng/pipelines/libraries/variables.yml index 9bb89d7d49384..2abd5adabe2c9 100644 --- a/eng/pipelines/libraries/variables.yml +++ b/eng/pipelines/libraries/variables.yml @@ -6,7 +6,7 @@ variables: value: $(Build.SourcesDirectory)/src/libraries - name: pipelinesPath value: /eng/pipelines/libraries - - name: isFullMatrix + - name: isRollingBuild value: ${{ notIn(variables['Build.Reason'], 'PullRequest') }} - name: includeWindowsOuterloop value: ${{ or(endsWith(variables['Build.DefinitionName'], 'windows'), endsWith(variables['Build.DefinitionName'], 'outerloop')) }} diff --git a/eng/pipelines/runtime-community.yml b/eng/pipelines/runtime-community.yml index 5bebcc00a2663..f588ad52b0f33 100644 --- a/eng/pipelines/runtime-community.yml +++ b/eng/pipelines/runtime-community.yml @@ -46,7 +46,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -56,4 +56,4 @@ jobs: or( eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) diff --git a/eng/pipelines/runtime-manual.yml b/eng/pipelines/runtime-extra-platforms.yml similarity index 59% rename from eng/pipelines/runtime-manual.yml rename to eng/pipelines/runtime-extra-platforms.yml index d6182de37f3be..844666bdea5dc 100644 --- a/eng/pipelines/runtime-manual.yml +++ b/eng/pipelines/runtime-extra-platforms.yml @@ -1,161 +1,125 @@ +# This pipeline includes the platforms that we don't have resources to run on every PR but that we want +# to still have test coverage, we run this pipeline on a schedule and also developers can run it +# via /azp run command on PRs. This pipeline permits us to have the main runtime pipeline run the same +# platforms in PRs and Scheduled builds. + +# Setting batch to true, triggers one build at a time. +# if there is a push while a build in progress, it will wait, +# until the running build finishes, and produce a build with all the changes +# that happened during the last build. trigger: none +schedules: + - cron: "0 9,21 * * *" # run at 9:00 and 21:00 (UTC) which is 1:00 and 13:00 (PST). + displayName: Runtime extra main schedule + branches: + include: + - main + always: false # run only if there were changes since the last successful scheduled run. + - cron: "0 6,18 * * *" # run at 6:00 and 18:00 (UTC) which is 22:00 and 10:00 (PST). + displayName: Runtime extra release schedule + branches: + include: + - release/* + always: false # run only if there were changes since the last successful scheduled run. + variables: - template: /eng/pipelines/common/variables.yml jobs: # -# iOS/tvOS interp - requires AOT Compilation and Interp flags -# Build the whole product using Mono and run libraries tests +# Evaluate paths # -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - iOSSimulator_x64 - - tvOSSimulator_x64 - - iOSSimulator_arm64 - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:RunAOTCompilation=true /p:MonoForceInterpreter=true /p:BuildDarwinFrameworks=true - timeoutInMinutes: 180 - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - interpreter: true - testRunNamePrefixSuffix: Mono_$(_BuildConfig) +- ${{ if eq(variables.dependOnEvaluatePaths, true) }}: + - template: /eng/pipelines/common/evaluate-default-paths.yml # -# MacCatalyst interp - requires AOT Compilation and Interp flags -# Build the whole product using Mono and run libraries tests +# Build CoreCLR release +# Always as they are needed by Installer and we always build and test the Installer. # - template: /eng/pipelines/common/platform-matrix.yml parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono + jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml + buildConfig: release platforms: - - MacCatalyst_x64 - # don't run tests on arm64 PRs until we can get significantly more devices - - ${{ if eq(variables['isFullMatrix'], true) }}: - - MacCatalyst_arm64 + - Linux_x64 + - Linux_arm + - Linux_arm64 + - Linux_musl_x64 + - OSX_x64 + - windows_x64 + - windows_x86 + - windows_arm64 jobParameters: testGroup: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:DevTeamProvisioning=adhoc /p:RunAOTCompilation=true /p:MonoForceInterpreter=true /p:BuildDarwinFrameworks=true - timeoutInMinutes: 180 - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - interpreter: true - testRunNamePrefixSuffix: Mono_$(_BuildConfig) # -# MacCatalyst interp - requires AOT Compilation and Interp flags -# Build the whole product using Mono and run libraries tests -# The test app is built with the App Sandbox entitlement +# Build libraries using live CoreLib # - template: /eng/pipelines/common/platform-matrix.yml parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml + jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release - runtimeFlavor: mono platforms: - - MacCatalyst_x64 - # don't run tests on arm64 PRs until we can get significantly more devices - - ${{ if eq(variables['isFullMatrix'], true) }}: - - MacCatalyst_arm64 - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono_AppSandbox - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:DevTeamProvisioning=adhoc /p:RunAOTCompilation=true /p:MonoForceInterpreter=true /p:BuildDarwinFrameworks=true /p:EnableAppSandbox=true - timeoutInMinutes: 180 - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - interpreter: true - testRunNamePrefixSuffix: Mono_$(_BuildConfig) + - Linux_x64 + - Linux_arm + - Linux_arm64 + - Linux_musl_x64 + - OSX_x64 + - windows_x64 + - windows_x86 + - windows_arm64 # -# iOS/tvOS devices - Full AOT + AggressiveTrimming to reduce size -# Build the whole product using Mono and run libraries tests +# Libraries Release Test Execution against a release coreclr runtime +# Only when the PR contains a libraries change # - template: /eng/pipelines/common/platform-matrix.yml parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml + jobTemplate: /eng/pipelines/libraries/run-test-job.yml buildConfig: Release - runtimeFlavor: mono platforms: - - iOS_arm64 - - tvOS_arm64 - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:DevTeamProvisioning=- /p:RunAOTCompilation=true /p:BuildTestsOnHelix=true /p:UsePortableRuntimePack=true /p:BuildDarwinFrameworks=true - timeoutInMinutes: 180 - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:NeedsToBuildAppsOnHelix=true - -# -# Build the whole product using Mono and run libraries tests -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml + - Linux_x64 + - Linux_arm + - Linux_arm64 + - Linux_musl_x64 + - OSX_x64 + - windows_x64 + - windows_x86 + - windows_arm64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Android_x86 - - Android_x64 jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true $(_runSmokeTestsOnlyArg) - timeoutInMinutes: 180 - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) + isOfficialBuild: false + isExtraPlatforms: ${{ variables.isExtraPlatformsBuild }} + testScope: innerloop + liveRuntimeBuildConfig: release + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(variables['isRollingBuild'], true)) +# Run net48 tests on win-x64 - template: /eng/pipelines/common/platform-matrix.yml parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml + jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release - runtimeFlavor: mono platforms: - - Android_arm - - Android_arm64 + - windows_x64 + helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true $(_runSmokeTestsOnlyArg) - timeoutInMinutes: 180 - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) + framework: net48 + runTests: true + testScope: innerloop + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(variables['isRollingBuild'], true)) + +#### MONO LEGS # -# Build the whole product using Mono and run libraries tests +# Build the whole product using Mono and run libraries tests, for Wasm.Build.Tests # - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -164,132 +128,137 @@ jobs: buildConfig: Release runtimeFlavor: mono platforms: - - Windows_x64 + # BuildWasmApps should only happen on the extra platforms build as we already have coverage for this build on PRs. + - Browser_wasm + # disable until https://github.com/dotnet/runtime/issues/63987 is fixed + # - Browser_wasm_win + variables: + # map dependencies variables to local variables + - name: wasmbuildtestsContainsChange + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'] ] jobParameters: - testScope: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true - timeoutInMinutes: 120 + isExtraPlatforms: ${{ variables.isExtraPlatformsBuild }} + testGroup: innerloop + nameSuffix: WasmBuildTests + buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:TestWasmBuildTests=true /p:TestAssemblies=false /p:BrowserHost=$(_hostedOs) + timeoutInMinutes: 180 + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'], true), + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) + testRunNamePrefixSuffix: Mono_$(_BuildConfig)_$(_hostedOs) + extraHelixArguments: /p:BrowserHost=$(_hostedOs) + scenarios: + - buildwasmapps + condition: >- + or( + eq(variables['wasmbuildtestsContainsChange'], true), + eq(variables['isRollingBuild'], true)) # -# Build the whole product using Mono for Android and run runtime tests with interpreter +# Build Browser_wasm, on windows, run console and browser tests # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml - buildConfig: Release + helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml + buildConfig: release runtimeFlavor: mono platforms: - - Android_x64 + # disable until https://github.com/dotnet/runtime/issues/63987 is fixed + # - Browser_wasm_win variables: - - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: pr/dotnet/runtime/$(Build.SourceBranch) - - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: ci/dotnet/runtime/$(Build.SourceBranch) - - name: timeoutPerTestInMinutes - value: 60 - - name: timeoutPerTestCollectionInMinutes - value: 180 + # map dependencies variables to local variables + - name: librariesContainsChange + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] + - name: monoContainsChange + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] jobParameters: testGroup: innerloop - nameSuffix: AllSubsets_Mono_RuntimeTests_Interp - buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 240 - runtimeVariant: monointerpreter + nameSuffix: ConsoleBrowserTests + buildArgs: -subset mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=windows + timeoutInMinutes: 180 + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), + eq(variables['isRollingBuild'], true)) # extra steps, run tests - extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml + extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) + testRunNamePrefixSuffix: Windows_wasm_$(_BuildConfig) + extraHelixArguments: /p:BrowserHost=windows + scenarios: + - normal + - wasmtestonbrowser + condition: >- + or( + eq(variables['librariesContainsChange'], true), + eq(variables['monoContainsChange'], true), + eq(variables['isRollingBuild'], true)) # -# Build the whole product using Mono and run runtime tests with the JIT. +# Build for Browser/wasm, with EnableAggressiveTrimming=true # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml + helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml buildConfig: Release runtimeFlavor: mono platforms: - - iOSSimulator_x64 + - Browser_wasm variables: - - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: pr/dotnet/runtime/$(Build.SourceBranch) - - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: ci/dotnet/runtime/$(Build.SourceBranch) - - name: timeoutPerTestInMinutes - value: 60 - - name: timeoutPerTestCollectionInMinutes - value: 180 + # map dependencies variables to local variables + - name: librariesContainsChange + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] + - name: monoContainsChange + value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] jobParameters: + isExtraPlatforms: ${{ variables.isExtraPlatformsBuild }} testGroup: innerloop - nameSuffix: AllSubsets_Mono_RuntimeTests - buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 240 + nameSuffix: AllSubsets_Mono_EAT + buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true $(_runSmokeTestsOnlyArg) /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=true /p:RunAOTCompilation=false + timeoutInMinutes: 180 + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), + eq(variables['isRollingBuild'], true)) # extra steps, run tests - extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml + extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) + extraHelixArguments: /p:NeedsToBuildWasmAppsOnHelix=true $(_runSmokeTestsOnlyArg) + scenarios: + - normal + condition: >- + or( + eq(variables['librariesContainsChange'], true), + eq(variables['monoContainsChange'], true), + eq(variables['isRollingBuild'], true)) # -# Build the whole product using Mono for Android and run runtime tests with Android devices -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Android_arm64 - variables: - - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: pr/dotnet/runtime/$(Build.SourceBranch) - - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: ci/dotnet/runtime/$(Build.SourceBranch) - - name: timeoutPerTestInMinutes - value: 60 - - name: timeoutPerTestCollectionInMinutes - value: 180 - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono_RuntimeTests - buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 240 - # don't run tests on PRs until we can get significantly more devices - # Turn off the testing for now, until https://github.com/dotnet/xharness/issues/663 gets resolved - # ${{ if eq(variables['isFullMatrix'], true) }}: - # # extra steps, run tests - # extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml - # extraStepsParameters: - # creator: dotnet-bot - # testRunNamePrefixSuffix: Mono_$(_BuildConfig) - -# -# Build Browser_wasm, on windows, run console and browser tests +# Build for Browser/wasm with RunAOTCompilation=true # - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/global-build-job.yml helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: release + buildConfig: Release runtimeFlavor: mono platforms: - - Browser_wasm_win + - Browser_wasm + # disable until https://github.com/dotnet/runtime/issues/63987 is fixed + # - Browser_wasm_win variables: # map dependencies variables to local variables - name: librariesContainsChange @@ -297,78 +266,79 @@ jobs: - name: monoContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] jobParameters: + isExtraPlatforms: ${{ variables.isExtraPlatformsBuild }} testGroup: innerloop - nameSuffix: Windows_wasm - buildArgs: -subset mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=windows + nameSuffix: AllSubsets_Mono_AOT + buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true $(_runSmokeTestsOnlyArg) /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=true /p:RunAOTCompilation=true /p:BrowserHost=$(_hostedOs) timeoutInMinutes: 180 condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:BrowserHost=windows + testRunNamePrefixSuffix: Mono_AOT_$(_BuildConfig)_$(_hostedOs) + extraHelixArguments: /p:NeedsToBuildWasmAppsOnHelix=true $(_runSmokeTestsOnlyArg) /p:BrowserHost=$(_hostedOs) scenarios: - normal - - WasmTestOnBrowser - - WasmTestOnNodeJs condition: >- or( eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) +# +# Build the whole product using Mono and run runtime tests +# - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: release + helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml + buildConfig: Release runtimeFlavor: mono platforms: - - Browser_wasm_win + - Browser_wasm variables: - # map dependencies variables to local variables - - name: wasmbuildtestsContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'] ] + - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: + - name: _HelixSource + value: pr/dotnet/runtime/$(Build.SourceBranch) + - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: + - name: _HelixSource + value: ci/dotnet/runtime/$(Build.SourceBranch) + - name: timeoutPerTestInMinutes + value: 10 + - name: timeoutPerTestCollectionInMinutes + value: 200 jobParameters: testGroup: innerloop - nameSuffix: Windows_wasm_WBT - buildArgs: -subset mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=windows /p:TestWasmBuildTests=true /p:TestAssemblies=false + nameSuffix: AllSubsets_Mono_RuntimeTests + buildArgs: -s mono+libs -c $(_BuildConfig) timeoutInMinutes: 180 condition: >- or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(variables['isRollingBuild'], true)) + extraStepsTemplate: /eng/pipelines/common/templates/runtimes/wasm-runtime-and-send-to-helix.yml extraStepsParameters: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:BrowserHost=windows - scenarios: - - buildwasmapps - condition: >- - or( - eq(variables['wasmbuildtestsContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) +# +# Build the whole product using Mono and run libraries tests +# - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/global-build-job.yml helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: release + buildConfig: Release runtimeFlavor: mono platforms: - - Browser_wasm_win + - Windows_x64 variables: # map dependencies variables to local variables - name: librariesContainsChange @@ -376,34 +346,30 @@ jobs: - name: monoContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] jobParameters: - testGroup: innerloop - nameSuffix: Windows_wasm_AOT - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=windows /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=true /p:RunAOTCompilation=true $(_runSmokeTestsOnlyArg) - timeoutInMinutes: 180 + testScope: innerloop + nameSuffix: AllSubsets_Mono + buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true + timeoutInMinutes: 120 condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:BrowserHost=windows /p:NeedsToBuildWasmAppsOnHelix=true $(_runSmokeTestsOnlyArg) - scenarios: - - normal condition: >- or( eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # -# Build for Browser/wasm, with EnableAggressiveTrimming=true +# iOS/tvOS devices - Full AOT + AggressiveTrimming to reduce size +# Build the whole product using Mono and run libraries tests # - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -412,7 +378,8 @@ jobs: buildConfig: Release runtimeFlavor: mono platforms: - - Browser_wasm + - iOS_arm64 + - tvOS_arm64 variables: # map dependencies variables to local variables - name: librariesContainsChange @@ -421,21 +388,26 @@ jobs: value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] jobParameters: testGroup: innerloop - nameSuffix: AllSubsets_Mono_EAT - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:RunSmokeTestsOnly=false /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=true /p:RunAOTCompilation=false + nameSuffix: AllSubsets_Mono + buildArgs: -s mono+libs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:DevTeamProvisioning=- /p:RunAOTCompilation=true $(_runSmokeTestsOnlyArg) /p:BuildTestsOnHelix=true /p:UsePortableRuntimePack=true /p:BuildDarwinFrameworks=true timeoutInMinutes: 180 + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:NeedsToBuildWasmAppsOnHelix=true /p:RunSmokeTestsOnly=false - scenarios: - - normal + extraHelixArguments: /p:NeedsToBuildAppsOnHelix=true + condition: >- + or( + eq(variables['librariesContainsChange'], true), + eq(variables['monoContainsChange'], true), + eq(variables['isRollingBuild'], true)) -# -# Build for Browser/wasm with RunAOTCompilation=true -# - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/common/global-build-job.yml @@ -443,7 +415,8 @@ jobs: buildConfig: Release runtimeFlavor: mono platforms: - - Browser_wasm + - Android_arm + - Android_arm64 variables: # map dependencies variables to local variables - name: librariesContainsChange @@ -452,20 +425,27 @@ jobs: value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] jobParameters: testGroup: innerloop - nameSuffix: AllSubsets_Mono_AOT - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:RunSmokeTestsOnly=false /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=true /p:RunAOTCompilation=true + nameSuffix: AllSubsets_Mono + buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true $(_runSmokeTestsOnlyArg) timeoutInMinutes: 180 + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:NeedsToBuildWasmAppsOnHelix=true /p:RunSmokeTestsOnly=false - scenarios: - - normal + condition: >- + or( + eq(variables['librariesContainsChange'], true), + eq(variables['monoContainsChange'], true), + eq(variables['isRollingBuild'], true)) # -# Build for Browser/wasm and test it on NodeJS +# Build for Browser/wasm and test it on v8, browser, and nodejs # - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -477,8 +457,6 @@ jobs: - Browser_wasm variables: # map dependencies variables to local variables - - name: librariesContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - name: monoContainsChange value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] jobParameters: @@ -488,8 +466,8 @@ jobs: timeoutInMinutes: 180 condition: >- or( - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -501,44 +479,46 @@ jobs: - WasmTestOnNodeJs condition: >- or( - eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build the whole product using Mono and run runtime tests +# Build Mono release +# Only when libraries, mono, or the runtime tests changed +# Currently only these architectures are needed for the runtime tests. +- template: /eng/pipelines/common/platform-matrix.yml + parameters: + jobTemplate: /eng/pipelines/mono/templates/build-job.yml + runtimeFlavor: mono + buildConfig: release + platforms: + - Linux_arm64 + jobParameters: + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(variables['isRollingBuild'], true)) + # +# Mono Test builds with CoreCLR runtime tests using live libraries debug build +# Only when Mono is changed - template: /eng/pipelines/common/platform-matrix.yml parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml - buildConfig: Release + jobTemplate: /eng/pipelines/common/templates/runtimes/build-test-job.yml + buildConfig: release runtimeFlavor: mono platforms: - - Browser_wasm - variables: - - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: pr/dotnet/runtime/$(Build.SourceBranch) - - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: ci/dotnet/runtime/$(Build.SourceBranch) - - name: timeoutPerTestInMinutes - value: 10 - - name: timeoutPerTestCollectionInMinutes - value: 200 + - CoreClrTestBuildHost # Either OSX_x64 or Linux_x64 jobParameters: testGroup: innerloop - nameSuffix: AllSubsets_Mono_RuntimeTests - buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 180 - # NOTE: Per PR test execution is not recommended for mobile runtime tests - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/common/templates/runtimes/wasm-runtime-and-send-to-helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(variables['isRollingBuild'], true)) # Wasm debugger tests - template: /eng/pipelines/common/platform-matrix.yml @@ -579,7 +559,8 @@ jobs: buildConfig: Release runtimeFlavor: mono platforms: - - Browser_wasm_win + # disable until https://github.com/dotnet/runtime/issues/63987 is fixed + # - Browser_wasm_win variables: # map dependencies variables to local variables - name: wasmdebuggertestsContainsChange @@ -630,9 +611,100 @@ jobs: nameSuffix: AllSubsets_Mono_RuntimeTests buildArgs: -s mono+libs -c $(_BuildConfig) timeoutInMinutes: 240 - # NOTE: Per PR test execution is not recommended for mobile runtime tests + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml extraStepsParameters: creator: dotnet-bot testRunNamePrefixSuffix: Mono_$(_BuildConfig) + +# +# Build the whole product using Mono for Android and run runtime tests with interpreter +# +- template: /eng/pipelines/common/platform-matrix.yml + parameters: + jobTemplate: /eng/pipelines/common/global-build-job.yml + helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml + buildConfig: Release + runtimeFlavor: mono + platforms: + - Android_x64 + variables: + - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: + - name: _HelixSource + value: pr/dotnet/runtime/$(Build.SourceBranch) + - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: + - name: _HelixSource + value: ci/dotnet/runtime/$(Build.SourceBranch) + - name: timeoutPerTestInMinutes + value: 60 + - name: timeoutPerTestCollectionInMinutes + value: 180 + jobParameters: + testGroup: innerloop + nameSuffix: AllSubsets_Mono_RuntimeTests_Interp + buildArgs: -s mono+libs -c $(_BuildConfig) + timeoutInMinutes: 240 + runtimeVariant: monointerpreter + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(variables['isRollingBuild'], true)) + # NOTE: Per PR test execution is not recommended for runtime tests + ${{ if eq(variables['isRollingBuild'], true) }}: + # extra steps, run tests + extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml + extraStepsParameters: + creator: dotnet-bot + testRunNamePrefixSuffix: Mono_$(_BuildConfig) + +# +# Mono CoreCLR runtime Test executions using live libraries in jit mode +# Only when Mono is changed +- template: /eng/pipelines/common/platform-matrix.yml + parameters: + jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml + buildConfig: release + runtimeFlavor: mono + platforms: + - Linux_arm64 + helixQueueGroup: pr + helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml + jobParameters: + testGroup: innerloop + liveLibrariesBuildConfig: Release + liveRuntimeBuildConfig: release + runtimeVariant: minijit + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(variables['isRollingBuild'], true)) + +# +# Mono CoreCLR runtime Test executions using live libraries in interpreter mode +# Only when Mono is changed +- template: /eng/pipelines/common/platform-matrix.yml + parameters: + jobTemplate: /eng/pipelines/common/templates/runtimes/run-test-job.yml + buildConfig: release + runtimeFlavor: mono + platforms: + - Linux_arm64 + helixQueueGroup: pr + helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml + jobParameters: + testGroup: innerloop + liveLibrariesBuildConfig: Release + liveRuntimeBuildConfig: release + runtimeVariant: monointerpreter + condition: >- + or( + eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), + eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), + eq(variables['isRollingBuild'], true)) diff --git a/eng/pipelines/runtime-staging.yml b/eng/pipelines/runtime-staging.yml index 4288d372433df..42803677d0037 100644 --- a/eng/pipelines/runtime-staging.yml +++ b/eng/pipelines/runtime-staging.yml @@ -75,7 +75,7 @@ jobs: - iOSSimulator_x64 - tvOSSimulator_x64 # don't run tests on arm64 PRs until we can get significantly more devices - - ${{ if eq(variables['isManualOrIsNotPR'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - iOSSimulator_arm64 variables: # map dependencies variables to local variables @@ -93,8 +93,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -105,8 +104,7 @@ jobs: or( eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # MacCatalyst interp - requires AOT Compilation and Interp flags @@ -121,7 +119,7 @@ jobs: platforms: - MacCatalyst_x64 # don't run tests on arm64 PRs until we can get significantly more devices - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - MacCatalyst_arm64 variables: # map dependencies variables to local variables @@ -139,8 +137,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -149,10 +146,9 @@ jobs: testRunNamePrefixSuffix: Mono_$(_BuildConfig) condition: >- or( - eq(variables['librariesContainsChange'], true), - eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['librariesContainsChange'], true), + eq(variables['monoContainsChange'], true), + eq(variables['isRollingBuild'], true)) # # MacCatalyst interp - requires AOT Compilation and Interp flags @@ -168,7 +164,7 @@ jobs: platforms: - MacCatalyst_x64 # don't run tests on arm64 PRs until we can get significantly more devices - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - MacCatalyst_arm64 variables: # map dependencies variables to local variables @@ -185,8 +181,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -195,53 +190,9 @@ jobs: testRunNamePrefixSuffix: Mono_$(_BuildConfig) condition: >- or( - eq(variables['librariesContainsChange'], true), - eq(variables['monoContainsChange'], true), - eq(variables['isFullMatrix'], true)) - -# -# iOS/tvOS devices - Full AOT + AggressiveTrimming to reduce size -# Build the whole product using Mono and run libraries tests -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - iOS_arm64 - - tvOS_arm64 - variables: - # map dependencies variables to local variables - - name: librariesContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:DevTeamProvisioning=- /p:RunAOTCompilation=true $(_runSmokeTestsOnlyArg) /p:BuildTestsOnHelix=true /p:UsePortableRuntimePack=true /p:BuildDarwinFrameworks=true - timeoutInMinutes: 180 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:NeedsToBuildAppsOnHelix=true - condition: >- - or( - eq(variables['librariesContainsChange'], true), - eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['librariesContainsChange'], true), + eq(variables['monoContainsChange'], true), + eq(variables['isRollingBuild'], true)) # # Build the whole product using Mono and run libraries tests @@ -271,88 +222,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - condition: >- - or( - eq(variables['librariesContainsChange'], true), - eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Android_arm - - Android_arm64 - variables: - # map dependencies variables to local variables - - name: librariesContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true $(_runSmokeTestsOnlyArg) - timeoutInMinutes: 180 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - condition: >- - or( - eq(variables['librariesContainsChange'], true), - eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - -# -# Build the whole product using Mono and run libraries tests -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Windows_x64 - variables: - # map dependencies variables to local variables - - name: librariesContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] - jobParameters: - testScope: innerloop - nameSuffix: AllSubsets_Mono - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true - timeoutInMinutes: 120 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -362,50 +232,7 @@ jobs: or( eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - -# -# Build the whole product using Mono for Android and run runtime tests with interpreter -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Android_x64 - variables: - - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: pr/dotnet/runtime/$(Build.SourceBranch) - - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: ci/dotnet/runtime/$(Build.SourceBranch) - - name: timeoutPerTestInMinutes - value: 60 - - name: timeoutPerTestCollectionInMinutes - value: 180 - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono_RuntimeTests_Interp - buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 240 - runtimeVariant: monointerpreter - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - # NOTE: Per PR test execution is not recommended for runtime tests - ${{ if eq(variables['isManualOrIsNotPR'], true) }}: - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) + eq(variables['isRollingBuild'], true)) # # Build the whole product using Mono and run runtime tests with the JIT. @@ -438,9 +265,8 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - ${{ if eq(variables['isManualOrIsNotPR'], true) }}: + eq(variables['isRollingBuild'], true)) + ${{ if eq(variables['isRollingBuild'], true) }}: # extra steps, run tests extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml extraStepsParameters: @@ -478,205 +304,16 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # don't run tests on PRs until we can get significantly more devices # Turn off the testing for now, until https://github.com/dotnet/runtime/issues/60128 gets resolved - # ${{ if eq(variables['isFullMatrix'], true) }}: + # ${{ if eq(variables['isRollingBuild'], true) }}: # # extra steps, run tests # extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml # extraStepsParameters: # creator: dotnet-bot # testRunNamePrefixSuffix: Mono_$(_BuildConfig) -# -# Build Browser_wasm, on windows, run console and browser tests -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: release - runtimeFlavor: mono - platforms: - - Browser_wasm_win - variables: - # map dependencies variables to local variables - - name: librariesContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] - jobParameters: - testGroup: innerloop - nameSuffix: Windows_wasm - buildArgs: -subset mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=windows $(_runSmokeTestsOnlyArg) - timeoutInMinutes: 180 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:BrowserHost=windows $(_runSmokeTestsOnlyArg) - scenarios: - - normal - - WasmTestOnBrowser - condition: >- - or( - eq(variables['librariesContainsChange'], true), - eq(variables['monoContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - -# -# Build Browser_wasm, on windows, and run tests with AOT -# -# Disabled due to https://github.com/dotnet/runtime/issues/61721 -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: release - runtimeFlavor: mono - platforms: - - Browser_wasm_win - variables: - # map dependencies variables to local variables - - name: librariesContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'] ] - - name: monoContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'] ] - jobParameters: - testGroup: innerloop - nameSuffix: Windows_wasm_AOT - buildArgs: -s mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=windows /p:EnableAggressiveTrimming=true /p:BuildAOTTestsOnHelix=true /p:RunAOTCompilation=true $(_runSmokeTestsOnlyArg) - timeoutInMinutes: 180 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:BrowserHost=windows /p:NeedsToBuildWasmAppsOnHelix=true $(_runSmokeTestsOnlyArg) - scenarios: - - normal - condition: >- - or( - eq(variables['librariesContainsChange'], true), - eq(variables['monoContainsChange'], true), - eq(variables['isFullMatrix'], true)) - -# -# Build Browser_wasm, on windows, and run Wasm.Build.Tests -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: release - runtimeFlavor: mono - platforms: - - Browser_wasm_win - variables: - # map dependencies variables to local variables - - name: wasmbuildtestsContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'] ] - jobParameters: - testGroup: innerloop - nameSuffix: Windows_wasm_WBT - buildArgs: -subset mono+libs+host+packs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:BrowserHost=windows /p:TestWasmBuildTests=true /p:TestAssemblies=false - timeoutInMinutes: 180 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:BrowserHost=windows - scenarios: - - buildwasmapps - condition: >- - or( - eq(variables['wasmbuildtestsContainsChange'], true), - eq(variables['isManualOrIsNotPR'], true), - eq(variables['isFullMatrix'], true)) - -# Wasm debugger tests -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Browser_wasm - variables: - # map dependencies variables to local variables - - name: wasmdebuggertestsContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_wasmdebuggertests.containsChange'] ] - jobParameters: - testGroup: innerloop - nameSuffix: Mono_DebuggerTests - buildArgs: -s mono+libs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:TestWasmDebuggerTests=true /p:TestAssemblies=false - timeoutInMinutes: 180 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmdebuggertests.containsChange'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - scenarios: - - wasmdebuggertests - -# Wasm debugger tests - windows -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Browser_wasm_win - variables: - # map dependencies variables to local variables - - name: wasmdebuggertestsContainsChange - value: $[ dependencies.evaluate_paths.outputs['SetPathVars_wasmdebuggertests.containsChange'] ] - jobParameters: - testGroup: innerloop - nameSuffix: Windows_wasm_DebuggerTests - buildArgs: -s mono+libs+libs.tests -c $(_BuildConfig) /p:ArchiveTests=true /p:TestWasmDebuggerTests=true /p:TestAssemblies=false /p:BrowserHost=windows - timeoutInMinutes: 180 - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmdebuggertests.containsChange'], true), - eq(variables['isFullMatrix'], true)) - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/libraries/helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - extraHelixArguments: /p:BrowserHost=windows - scenarios: - - wasmdebuggertests - # # CoreCLR Build for running Apple Silicon libraries-innerloop # @@ -685,7 +322,7 @@ jobs: jobTemplate: /eng/pipelines/coreclr/templates/build-job.yml buildConfig: release platforms: - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - OSX_arm64 jobParameters: testGroup: innerloop @@ -697,12 +334,11 @@ jobs: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release platforms: - - ${{ if eq(variables['isFullMatrix'], true) }}: + - ${{ if eq(variables['isRollingBuild'], true) }}: - OSX_arm64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: ${{ variables['isOfficialBuild'] }} - isFullMatrix: ${{ variables['isFullMatrix'] }} runTests: true testScope: innerloop liveRuntimeBuildConfig: release diff --git a/eng/pipelines/runtime.yml b/eng/pipelines/runtime.yml index 5d7f3ffde2f81..cfc899e8d808d 100644 --- a/eng/pipelines/runtime.yml +++ b/eng/pipelines/runtime.yml @@ -91,7 +91,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build the whole product using GNU compiler toolchain @@ -114,7 +114,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build CoreCLR OSX_x64 checked @@ -133,7 +133,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build CoreCLR release @@ -178,7 +178,7 @@ jobs: # # Build CoreCLR Formatting Job # Only when CoreCLR is changed, and only in the 'main' branch (no release branches; -# both CI and PR builds). +# both Rolling and PR builds). # - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -194,7 +194,7 @@ jobs: eq(variables['System.PullRequest.TargetBranch'], 'main')), or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr_jit.containsChange'], true), - eq(variables['isFullMatrix'], true))) + eq(variables['isRollingBuild'], true))) # # CoreCLR NativeAOT debug build and smoke tests @@ -277,7 +277,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # Build Mono AOT offset headers once, for consumption elsewhere # Only when mono changed @@ -297,7 +297,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # Build the whole product using Mono runtime # Only when libraries, mono or installer are changed @@ -323,7 +323,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -343,7 +343,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build the whole product using Mono and run libraries tests, multi-scenario @@ -372,7 +372,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -385,7 +385,7 @@ jobs: or( eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build the whole product using Mono and run libraries tests, for Wasm.Build.Tests @@ -410,7 +410,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_wasmbuildtests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -420,8 +420,8 @@ jobs: - buildwasmapps condition: >- or( - eq(variables['wasmbuildtestsContainsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['wasmbuildtestsContainsChange'], true), + eq(variables['isRollingBuild'], true)) # # Build for Browser/wasm, with EnableAggressiveTrimming=true @@ -450,7 +450,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -463,7 +463,7 @@ jobs: or( eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build for Browser/wasm with RunAOTCompilation=true @@ -492,7 +492,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # extra steps, run tests extraStepsTemplate: /eng/pipelines/libraries/helix.yml extraStepsParameters: @@ -505,7 +505,7 @@ jobs: or( eq(variables['librariesContainsChange'], true), eq(variables['monoContainsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # Build and test libraries under single-file publishing - template: /eng/pipelines/common/platform-matrix.yml @@ -518,7 +518,6 @@ jobs: - Linux_x64 jobParameters: testGroup: innerloop - isFullMatrix: ${{ variables.isFullMatrix }} isSingleFile: true nameSuffix: SingleFile buildArgs: -s clr+libs+libs.tests -c $(_BuildConfig) /p:TestSingleFile=true /p:ArchiveTests=true @@ -529,78 +528,6 @@ jobs: creator: dotnet-bot testRunNamePrefixSuffix: SingleFile_$(_BuildConfig) -# -# Build the whole product using Mono and run runtime tests -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Browser_wasm - variables: - - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: pr/dotnet/runtime/$(Build.SourceBranch) - - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: ci/dotnet/runtime/$(Build.SourceBranch) - - name: timeoutPerTestInMinutes - value: 10 - - name: timeoutPerTestCollectionInMinutes - value: 200 - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono_RuntimeTests - buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 180 - condition: >- - eq(variables['isFullMatrix'], true) - # NOTE: Per PR test execution is not recommended for mobile runtime tests - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/common/templates/runtimes/wasm-runtime-and-send-to-helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - -# -# Build the whole product using Mono for Android and run runtime tests with Android emulator -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/common/global-build-job.yml - helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml - buildConfig: Release - runtimeFlavor: mono - platforms: - - Android_x64 - variables: - - ${{ if and(eq(variables['System.TeamProject'], 'public'), eq(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: pr/dotnet/runtime/$(Build.SourceBranch) - - ${{ if and(eq(variables['System.TeamProject'], 'public'), ne(variables['Build.Reason'], 'PullRequest')) }}: - - name: _HelixSource - value: ci/dotnet/runtime/$(Build.SourceBranch) - - name: timeoutPerTestInMinutes - value: 60 - - name: timeoutPerTestCollectionInMinutes - value: 180 - jobParameters: - testGroup: innerloop - nameSuffix: AllSubsets_Mono_RuntimeTests - buildArgs: -s mono+libs -c $(_BuildConfig) - timeoutInMinutes: 240 - condition: >- - eq(variables['isFullMatrix'], true) - # NOTE: Per PR test execution is not recommended for mobile runtime tests - # extra steps, run tests - extraStepsTemplate: /eng/pipelines/common/templates/runtimes/android-runtime-and-send-to-helix.yml - extraStepsParameters: - creator: dotnet-bot - testRunNamePrefixSuffix: Mono_$(_BuildConfig) - # # Build Mono and Installer on LLVMJIT mode # @@ -621,7 +548,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -641,7 +568,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build Mono and Installer on LLVMAOT mode @@ -664,7 +591,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -683,7 +610,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build Mono debug @@ -709,7 +636,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build Mono release AOT cross-compilers @@ -740,7 +667,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -767,7 +694,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_installer.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build Mono release @@ -790,7 +717,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build Mono release @@ -810,7 +737,7 @@ jobs: eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build Mono release with LLVM AOT @@ -830,7 +757,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Build libraries using live CoreLib @@ -849,8 +776,6 @@ jobs: - windows_arm - windows_arm64 - windows_x86 - jobParameters: - liveRuntimeBuildConfig: release - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -864,9 +789,12 @@ jobs: - OSX_x64 - windows_x64 - FreeBSD_x64 + - ${{ if eq(variables['isRollingBuild'], false) }}: + # we need to build windows_x86 for debug on PRs in order to test + # against a checked runtime when the PR contains coreclr changes + - windows_x86 jobParameters: testScope: innerloop - liveRuntimeBuildConfig: release # # Libraries Build that only run when coreclr is changed @@ -874,7 +802,7 @@ jobs: # and those are already built above # -- ${{ if eq(variables['isFullMatrix'], false) }}: +- ${{ if eq(variables['isRollingBuild'], false) }}: - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml @@ -884,45 +812,24 @@ jobs: - Linux_musl_arm - Linux_musl_arm64 jobParameters: - liveRuntimeBuildConfig: release condition: >- eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true) -# -# Libraries Build that only run when libraries is changed -# -- template: /eng/pipelines/common/platform-matrix.yml - parameters: - jobTemplate: /eng/pipelines/libraries/build-job.yml - buildConfig: ${{ variables.debugOnPrReleaseOnRolling }} - platforms: - - ${{ if eq(variables['isFullMatrix'], false) }}: - - windows_x86 - jobParameters: - liveRuntimeBuildConfig: release - condition: >- - or( - eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(variables['isFullMatrix'], true)) - - template: /eng/pipelines/common/platform-matrix.yml parameters: jobTemplate: /eng/pipelines/libraries/build-job.yml buildConfig: Release platforms: - windows_x86 - - ${{ if eq(variables['isFullMatrix'], true) }}: - - windows_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: - isFullMatrix: ${{ variables.isFullMatrix }} framework: net48 runTests: true testScope: innerloop condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -931,14 +838,13 @@ jobs: platforms: - windows_x64 jobParameters: - isFullMatrix: ${{ variables.isFullMatrix }} framework: allConfigurations runTests: true useHelix: false condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Installer Build and Test @@ -1006,7 +912,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # CoreCLR Test executions using live libraries @@ -1029,7 +935,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -1049,7 +955,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -1065,7 +971,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr_AppleSilicon.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Mono Test builds with CoreCLR runtime tests using live libraries debug build @@ -1083,7 +989,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Mono CoreCLR runtime Test executions using live libraries in jit mode @@ -1095,8 +1001,6 @@ jobs: runtimeFlavor: mono platforms: - OSX_x64 - - ${{ if eq(variables['isFullMatrix'], true) }}: - - Linux_arm64 helixQueueGroup: pr helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: @@ -1108,7 +1012,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Mono CoreCLR runtime Test executions using live libraries in interpreter mode @@ -1120,8 +1024,6 @@ jobs: runtimeFlavor: mono platforms: - OSX_x64 - - ${{ if eq(variables['isFullMatrix'], true) }}: - - Linux_arm64 helixQueueGroup: pr helixQueuesTemplate: /eng/pipelines/coreclr/templates/helix-queues-setup.yml jobParameters: @@ -1133,7 +1035,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Mono CoreCLR runtime Test executions using live libraries and LLVM AOT # Only when Mono is changed @@ -1158,7 +1060,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Mono CoreCLR runtime Test executions using live libraries and LLVM Full AOT @@ -1184,7 +1086,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_runtimetests.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Libraries Release Test Execution against a release mono runtime. @@ -1203,7 +1105,6 @@ jobs: helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: false - isFullMatrix: ${{ variables.isFullMatrix }} runtimeDisplayName: mono testScope: innerloop liveRuntimeBuildConfig: release @@ -1211,7 +1112,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Libraries Release Test Execution against a release mono interpreter runtime. @@ -1229,7 +1130,6 @@ jobs: helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: false - isFullMatrix: ${{ variables.isFullMatrix }} interpreter: true runtimeDisplayName: mono_interpreter testScope: innerloop @@ -1238,7 +1138,7 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_mono.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Libraries Release Test Execution against a release coreclr runtime @@ -1250,18 +1150,15 @@ jobs: buildConfig: Release platforms: - windows_x86 - - ${{ if eq(variables['isFullMatrix'], true) }}: - - windows_arm64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: false - isFullMatrix: ${{ variables.isFullMatrix }} testScope: innerloop liveRuntimeBuildConfig: release condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Libraries Debug Test Execution against a release coreclr runtime @@ -1276,20 +1173,15 @@ jobs: - OSX_x64 - Linux_x64 - Linux_musl_x64 - - ${{ if eq(variables['isFullMatrix'], true) }}: - - Linux_arm64 - - ${{ if eq(variables['isFullMatrix'], false) }}: - - windows_x86 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: isOfficialBuild: false - isFullMatrix: ${{ variables.isFullMatrix }} testScope: innerloop liveRuntimeBuildConfig: release condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Libraries Test Execution against a checked runtime @@ -1313,7 +1205,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) # # Libraries Test Execution against a checked runtime @@ -1335,7 +1227,7 @@ jobs: condition: >- or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) - template: /eng/pipelines/common/platform-matrix.yml parameters: @@ -1352,4 +1244,4 @@ jobs: or( eq(dependencies.evaluate_paths.outputs['SetPathVars_coreclr.containsChange'], true), eq(dependencies.evaluate_paths.outputs['SetPathVars_libraries.containsChange'], true), - eq(variables['isFullMatrix'], true)) + eq(variables['isRollingBuild'], true)) diff --git a/eng/pipelines/runtimelab.yml b/eng/pipelines/runtimelab.yml index 9f1cd90822e83..27e954a9a7026 100644 --- a/eng/pipelines/runtimelab.yml +++ b/eng/pipelines/runtimelab.yml @@ -190,7 +190,7 @@ stages: - Linux_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: - isFullMatrix: false + isRollingBuild: false isOfficialBuild: false testScope: innerloop liveRuntimeBuildConfig: Release @@ -207,7 +207,7 @@ stages: - windows_x64 helixQueuesTemplate: /eng/pipelines/libraries/helix-queues-setup.yml jobParameters: - isFullMatrix: false + isRollingBuild: false isOfficialBuild: false testScope: innerloop liveRuntimeBuildConfig: Release diff --git a/eng/run-test.sh b/eng/run-test.sh index 64474cc435af1..0475cff40cd83 100644 --- a/eng/run-test.sh +++ b/eng/run-test.sh @@ -31,7 +31,7 @@ usage() echo " default: Debug" echo " --os OS to run (FreeBSD, Linux, NetBSD, illumos or Solaris)" echo " default: detect current OS" - echo " --arch Architecture to run (x64, arm, armel, x86, arm64)" + echo " --arch Architecture to run (x64, arm, armel, x86, arm64, loongarch64)" echo " default: detect current architecture" echo echo "Execution options:" diff --git a/eng/targetingpacks.targets b/eng/targetingpacks.targets index 9dd37bef8fa1c..4213c84e709d9 100644 --- a/eng/targetingpacks.targets +++ b/eng/targetingpacks.targets @@ -33,7 +33,7 @@ LatestRuntimeFrameworkVersion="$(ProductVersion)" RuntimeFrameworkName="$(LocalFrameworkOverrideName)" RuntimePackNamePatterns="$(LocalFrameworkOverrideName).Runtime.**RID**" - RuntimePackRuntimeIdentifiers="linux-arm;linux-arm64;linux-musl-arm64;linux-musl-x64;linux-x64;osx-x64;rhel.6-x64;tizen.4.0.0-armel;tizen.5.0.0-armel;win-arm;win-arm64;win-x64;win-x86;linux-musl-arm;osx-arm64;maccatalyst-x64;maccatalyst-arm64" + RuntimePackRuntimeIdentifiers="linux-arm;linux-arm64;linux-musl-arm64;linux-loongarch64;linux-musl-x64;linux-x64;osx-x64;rhel.6-x64;tizen.4.0.0-armel;tizen.5.0.0-armel;win-arm;win-arm64;win-x64;win-x86;linux-musl-arm;osx-arm64;maccatalyst-x64;maccatalyst-arm64" TargetFramework="$(NetCoreAppCurrent)" TargetingPackName="$(LocalFrameworkOverrideName).Ref" TargetingPackVersion="$(ProductVersion)" @@ -43,13 +43,13 @@ RuntimeFrameworkName="$(LocalFrameworkOverrideName)" LatestRuntimeFrameworkVersion="$(ProductVersion)" RuntimePackNamePatterns="$(LocalFrameworkOverrideName).Runtime.Mono.**RID**" - RuntimePackRuntimeIdentifiers="linux-arm;linux-arm64;linux-musl-arm64;linux-musl-x64;linux-x64;osx-x64;rhel.6-x64;win-arm;win-arm64;win-x64;win-x86;linux-musl-arm;osx-arm64;maccatalyst-x64;maccatalyst-arm64;browser-wasm;ios-arm64;ios-arm;iossimulator-arm64;iossimulator-x64;iossimulator-x86;tvos-arm64;tvossimulator-arm64;tvossimulator-x64;android-arm64;android-arm;android-x64;android-x86" + RuntimePackRuntimeIdentifiers="linux-arm;linux-arm64;linux-musl-arm64;linux-loongarch64;linux-musl-x64;linux-x64;osx-x64;rhel.6-x64;win-arm;win-arm64;win-x64;win-x86;linux-musl-arm;osx-arm64;maccatalyst-x64;maccatalyst-arm64;browser-wasm;ios-arm64;ios-arm;iossimulator-arm64;iossimulator-x64;iossimulator-x86;tvos-arm64;tvossimulator-arm64;tvossimulator-x64;android-arm64;android-arm;android-x64;android-x86" RuntimePackLabels="Mono" Condition="'@(KnownRuntimePack)' == '' or !@(KnownRuntimePack->AnyHaveMetadataValue('TargetFramework', '$(NetCoreAppCurrent)'))"/> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eng/testing/tests.props b/eng/testing/tests.props index 86c661d4bb281..3025ab6233504 100644 --- a/eng/testing/tests.props +++ b/eng/testing/tests.props @@ -7,6 +7,7 @@ $(TestDependsOn);GenerateRunScript;RunTests true $(MSBuildThisFileDirectory)ILLinkDescriptors\ + true diff --git a/eng/testing/tests.singlefile.targets b/eng/testing/tests.singlefile.targets index 85ee6deb32db3..e6783add3640a 100644 --- a/eng/testing/tests.singlefile.targets +++ b/eng/testing/tests.singlefile.targets @@ -12,7 +12,7 @@ chmod +rwx $(AssemblyName) && ./$(AssemblyName) - + true true true @@ -20,6 +20,30 @@ $(SingleFileHostSourcePath).exe + + $(CoreCLRILCompilerDir) + $(CoreCLRILCompilerDir)netstandard/ILCompiler.Build.Tasks.dll + $(CoreCLRAotSdkDir) + $(NetCoreAppCurrentTestHostSharedFrameworkPath) + $(NoWarn);IL3050;IL3052;IL3055;IL1005 + false + + + true + + + + + + + + + + + + + + diff --git a/global.json b/global.json index 16691a4405b23..6e753c749b04a 100644 --- a/global.json +++ b/global.json @@ -12,12 +12,12 @@ "python3": "3.7.1" }, "msbuild-sdks": { - "Microsoft.DotNet.Build.Tasks.TargetFramework.Sdk": "7.0.0-beta.22053.2", - "Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.22053.2", - "Microsoft.DotNet.Helix.Sdk": "7.0.0-beta.22053.2", - "Microsoft.DotNet.SharedFramework.Sdk": "7.0.0-beta.22053.2", + "Microsoft.DotNet.Build.Tasks.TargetFramework.Sdk": "7.0.0-beta.22068.3", + "Microsoft.DotNet.Arcade.Sdk": "7.0.0-beta.22068.3", + "Microsoft.DotNet.Helix.Sdk": "7.0.0-beta.22068.3", + "Microsoft.DotNet.SharedFramework.Sdk": "7.0.0-beta.22068.3", "Microsoft.Build.NoTargets": "3.1.0", "Microsoft.Build.Traversal": "3.0.23", - "Microsoft.NET.Sdk.IL": "7.0.0-alpha.1.22052.8" + "Microsoft.NET.Sdk.IL": "7.0.0-alpha.1.22066.4" } } diff --git a/src/coreclr/.nuget/Microsoft.ILVerification/Microsoft.ILVerification.pkgproj b/src/coreclr/.nuget/Microsoft.ILVerification/Microsoft.ILVerification.pkgproj index db820d395a125..685f941510195 100644 --- a/src/coreclr/.nuget/Microsoft.ILVerification/Microsoft.ILVerification.pkgproj +++ b/src/coreclr/.nuget/Microsoft.ILVerification/Microsoft.ILVerification.pkgproj @@ -15,7 +15,7 @@ lib\netstandard2.0\ILVerification.dll - 1.8.1 + $(SystemReflectionMetadataVersion) netstandard2.0 Build,Analyzers diff --git a/src/coreclr/CMakeLists.txt b/src/coreclr/CMakeLists.txt index 2440f6ca999ca..38e5488938b6d 100644 --- a/src/coreclr/CMakeLists.txt +++ b/src/coreclr/CMakeLists.txt @@ -247,7 +247,6 @@ add_subdirectory(debug) add_subdirectory(binder) add_subdirectory(classlibnative) add_subdirectory(dlls) -add_subdirectory(ToolBox) add_subdirectory(tools) add_subdirectory(unwinder) add_subdirectory(interop) diff --git a/src/coreclr/System.Private.CoreLib/src/System/Math.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Math.CoreCLR.cs index c86aa1b2e62bf..a619dc4b1ca79 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Math.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Math.CoreCLR.cs @@ -16,14 +16,6 @@ namespace System { public static partial class Math { - [Intrinsic] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern double Abs(double value); - - [Intrinsic] - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern float Abs(float value); - [Intrinsic] [MethodImpl(MethodImplOptions.InternalCall)] public static extern double Acos(double d); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs index 44884c129e237..fe5da8367cdd4 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.cs @@ -46,7 +46,7 @@ internal static string UnmangleTypeName(string typeName) while (true) { i = typeName.LastIndexOf('+', i); - if (i == -1) + if (i < 0) { break; } @@ -626,7 +626,7 @@ internal Type[] GetTypesNoLock() { // Are there any possible special characters left? int i = className.AsSpan(startIndex).IndexOfAny('[', '*', '&'); - if (i == -1) + if (i < 0) { // No, type name is simple. baseName = className; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs index 36fe011d10d4f..6d9b8121fa6b4 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.cs @@ -527,7 +527,7 @@ internal TypeBuilder( } int iLast = fullname.LastIndexOf('.'); - if (iLast == -1 || iLast == 0) + if (iLast <= 0) { // no name space m_strNameSpace = string.Empty; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs index dd9c22987203a..cba7d80fa15b0 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeModule.cs @@ -523,7 +523,7 @@ public override string Name int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar); - if (i == -1) + if (i < 0) return s; return s.Substring(i + 1); diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index 2c7bb900641aa..a0d7026b54407 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -1992,8 +1992,8 @@ private static void SplitName(string? fullname, out string? name, out string? ns return; // Get namespace - int nsDelimiter = fullname.LastIndexOf(".", StringComparison.Ordinal); - if (nsDelimiter != -1) + int nsDelimiter = fullname.LastIndexOf('.'); + if (nsDelimiter >= 0) { ns = fullname.Substring(0, nsDelimiter); int nameLength = fullname.Length - ns.Length - 1; diff --git a/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs b/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs index 406e1dc8c533d..d51fca9673e39 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/StubHelpers.cs @@ -184,7 +184,7 @@ internal static unsafe void ConvertFixedToNative(int flags, string strManaged, I internal static unsafe string ConvertFixedToManaged(IntPtr cstr, int length) { int end = SpanHelpers.IndexOf(ref *(byte*)cstr, 0, length); - if (end != -1) + if (end >= 0) { length = end; } @@ -512,7 +512,7 @@ internal static unsafe void ConvertToNative(string? strManaged, IntPtr nativeHom internal static unsafe string ConvertToManaged(IntPtr nativeHome, int length) { int end = SpanHelpers.IndexOf(ref *(char*)nativeHome, '\0', length); - if (end != -1) + if (end >= 0) { length = end; } diff --git a/src/coreclr/ToolBox/CMakeLists.txt b/src/coreclr/ToolBox/CMakeLists.txt deleted file mode 100644 index 4e7f4368681d1..0000000000000 --- a/src/coreclr/ToolBox/CMakeLists.txt +++ /dev/null @@ -1,2 +0,0 @@ -add_subdirectory(SOS) -add_subdirectory(superpmi) diff --git a/src/coreclr/binder/assemblybindercommon.cpp b/src/coreclr/binder/assemblybindercommon.cpp index 830c673ea06a6..7b48a0a90ce83 100644 --- a/src/coreclr/binder/assemblybindercommon.cpp +++ b/src/coreclr/binder/assemblybindercommon.cpp @@ -972,7 +972,7 @@ namespace BINDER_SPACE { // Search Assembly.ni.dll, then Assembly.dll // The Assembly.ni.dll paths are rare, and intended for supporting managed C++ R2R assemblies. - SString candidates[] = { W(".ni.dll"), W(".dll") }; + const WCHAR* const candidates[] = { W(".ni.dll"), W(".dll") }; // Loop through the binding paths looking for a matching assembly for (int i = 0; i < 2; i++) diff --git a/src/coreclr/binder/bindertracing.cpp b/src/coreclr/binder/bindertracing.cpp index 499e20d928887..e349b99b3c14e 100644 --- a/src/coreclr/binder/bindertracing.cpp +++ b/src/coreclr/binder/bindertracing.cpp @@ -176,8 +176,8 @@ namespace BinderTracing { static thread_local bool t_AssemblyLoadStartInProgress = false; - AssemblyBindOperation::AssemblyBindOperation(AssemblySpec *assemblySpec, const WCHAR *assemblyPath) - : m_bindRequest { assemblySpec, nullptr, assemblyPath } + AssemblyBindOperation::AssemblyBindOperation(AssemblySpec *assemblySpec, const SString& assemblyPath) + : m_bindRequest { assemblySpec, SString::Empty(), assemblyPath } , m_populatedBindRequest { false } , m_checkedIgnoreBind { false } , m_ignoreBind { false } diff --git a/src/coreclr/binder/inc/bindertracing.h b/src/coreclr/binder/inc/bindertracing.h index 75d8270b8eee5..ca28c04519638 100644 --- a/src/coreclr/binder/inc/bindertracing.h +++ b/src/coreclr/binder/inc/bindertracing.h @@ -27,7 +27,7 @@ namespace BinderTracing { public: // This class assumes the assembly spec will have a longer lifetime than itself - AssemblyBindOperation(AssemblySpec *assemblySpec, const WCHAR *assemblyPath = nullptr); + AssemblyBindOperation(AssemblySpec *assemblySpec, const SString& assemblyPath = SString::Empty()); ~AssemblyBindOperation(); void SetResult(PEAssembly *assembly, bool cached = false); diff --git a/src/coreclr/build-runtime.sh b/src/coreclr/build-runtime.sh index 0952992949282..8d42b92ce95c0 100755 --- a/src/coreclr/build-runtime.sh +++ b/src/coreclr/build-runtime.sh @@ -50,6 +50,8 @@ build_cross_architecture_components() __SkipCrossArchBuild=0 elif [[ "$__BuildArch" == "arm64" && "$__CrossArch" == "x64" ]]; then __SkipCrossArchBuild=0 + elif [[ "$__BuildArch" == "loongarch64" && "$__CrossArch" == "x64" ]]; then + __SkipCrossArchBuild=0 else # not supported return diff --git a/src/coreclr/classlibnative/float/floatdouble.cpp b/src/coreclr/classlibnative/float/floatdouble.cpp index 67aceb60ea13e..d20b772eb2207 100644 --- a/src/coreclr/classlibnative/float/floatdouble.cpp +++ b/src/coreclr/classlibnative/float/floatdouble.cpp @@ -42,15 +42,6 @@ #pragma float_control(precise, off) #endif -/*=====================================Abs====================================== -** -==============================================================================*/ -FCIMPL1_V(double, COMDouble::Abs, double x) - FCALL_CONTRACT; - - return fabs(x); -FCIMPLEND - /*=====================================Acos===================================== ** ==============================================================================*/ diff --git a/src/coreclr/classlibnative/float/floatsingle.cpp b/src/coreclr/classlibnative/float/floatsingle.cpp index 965998fbaa2ba..1694fd78cb846 100644 --- a/src/coreclr/classlibnative/float/floatsingle.cpp +++ b/src/coreclr/classlibnative/float/floatsingle.cpp @@ -8,18 +8,6 @@ #include "floatsingle.h" -// Windows x86 and Windows ARM/ARM64 may not define _isnanf() or _copysignf() but they do -// define _isnan() and _copysign(). We will redirect the macros to these other functions if -// the macro is not defined for the platform. This has the side effect of a possible implicit -// upcasting for arguments passed in and an explicit downcasting for the _copysign() call. -#if (defined(TARGET_X86) || defined(TARGET_ARM) || defined(TARGET_ARM64)) && !defined(TARGET_UNIX) - -#if !defined(_copysignf) -#define _copysignf (float)_copysign -#endif - -#endif - // The default compilation mode is /fp:precise, which disables floating-point intrinsics. This // default compilation mode has previously caused performance regressions in floating-point code. // We enable /fp:fast semantics for the majority of the math functions, as it will speed up performance @@ -40,15 +28,6 @@ #pragma float_control(precise, off) #endif -/*=====================================Abs===================================== -** -==============================================================================*/ -FCIMPL1_V(float, COMSingle::Abs, float x) - FCALL_CONTRACT; - - return fabsf(x); -FCIMPLEND - /*=====================================Acos===================================== ** ==============================================================================*/ diff --git a/src/coreclr/classlibnative/inc/floatdouble.h b/src/coreclr/classlibnative/inc/floatdouble.h index 9163349127ca1..43fecbd47431f 100644 --- a/src/coreclr/classlibnative/inc/floatdouble.h +++ b/src/coreclr/classlibnative/inc/floatdouble.h @@ -9,7 +9,6 @@ class COMDouble { public: - FCDECL1_V(static double, Abs, double x); FCDECL1_V(static double, Acos, double x); FCDECL1_V(static double, Acosh, double x); FCDECL1_V(static double, Asin, double x); diff --git a/src/coreclr/classlibnative/inc/floatsingle.h b/src/coreclr/classlibnative/inc/floatsingle.h index 09a0512b230db..765032ce6371e 100644 --- a/src/coreclr/classlibnative/inc/floatsingle.h +++ b/src/coreclr/classlibnative/inc/floatsingle.h @@ -9,7 +9,6 @@ class COMSingle { public: - FCDECL1_V(static float, Abs, float x); FCDECL1_V(static float, Acos, float x); FCDECL1_V(static float, Acosh, float x); FCDECL1_V(static float, Asin, float x); diff --git a/src/coreclr/clrdefinitions.cmake b/src/coreclr/clrdefinitions.cmake index 50aab221c8032..d5fc9f5e1ee8e 100644 --- a/src/coreclr/clrdefinitions.cmake +++ b/src/coreclr/clrdefinitions.cmake @@ -191,12 +191,12 @@ if (CLR_CMAKE_TARGET_ARCH_AMD64) add_definitions(-DUNIX_AMD64_ABI_ITF) endif (CLR_CMAKE_TARGET_ARCH_AMD64) add_definitions(-DFEATURE_USE_ASM_GC_WRITE_BARRIERS) -if(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64) +if(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64 OR CLR_CMAKE_TARGET_ARCH_LOONGARCH64) add_definitions(-DFEATURE_USE_SOFTWARE_WRITE_WATCH_FOR_GC_HEAP) -endif(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64) -if(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64) +endif(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64 OR CLR_CMAKE_TARGET_ARCH_LOONGARCH64) +if(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64 OR CLR_CMAKE_TARGET_ARCH_LOONGARCH64) add_definitions(-DFEATURE_MANUALLY_MANAGED_CARD_BUNDLES) -endif(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64) +endif(CLR_CMAKE_TARGET_ARCH_AMD64 OR CLR_CMAKE_TARGET_ARCH_ARM64 OR CLR_CMAKE_TARGET_ARCH_LOONGARCH64) if(NOT CLR_CMAKE_TARGET_UNIX) add_definitions(-DFEATURE_WIN32_REGISTRY) @@ -240,6 +240,7 @@ function(set_target_definitions_to_custom_os_and_arch) elseif (TARGETDETAILS_ARCH STREQUAL "x86") target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE UNIX_X86_ABI) elseif (TARGETDETAILS_ARCH STREQUAL "arm64") + elseif (TARGETDETAILS_ARCH STREQUAL "loongarch64") endif() if ((TARGETDETAILS_ARCH STREQUAL "arm64") AND (TARGETDETAILS_OS STREQUAL "unix_osx")) target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE OSX_ARM64_ABI) @@ -260,6 +261,10 @@ function(set_target_definitions_to_custom_os_and_arch) target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE TARGET_64BIT) target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE TARGET_ARM64) target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE FEATURE_MULTIREG_RETURN) + elseif(TARGETDETAILS_ARCH STREQUAL "loongarch64") + target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE TARGET_64BIT) + target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE TARGET_LOONGARCH64) + target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE FEATURE_MULTIREG_RETURN) elseif((TARGETDETAILS_ARCH STREQUAL "arm") OR (TARGETDETAILS_ARCH STREQUAL "armel")) target_compile_definitions(${TARGETDETAILS_TARGET} PRIVATE TARGET_ARM) endif() diff --git a/src/coreclr/debug/createdump/crashinfomac.cpp b/src/coreclr/debug/createdump/crashinfomac.cpp index ad9c247e37dfd..3ada3bd767c96 100644 --- a/src/coreclr/debug/createdump/crashinfomac.cpp +++ b/src/coreclr/debug/createdump/crashinfomac.cpp @@ -277,6 +277,9 @@ void CrashInfo::VisitSegment(MachOModule& module, const segment_command_64& segm uint64_t start = segment.vmaddr + module.LoadBias(); uint64_t end = start + segment.vmsize; + // Add this module segment to the set used by the thread unwinding to lookup the module base address for an ip. + AddModuleAddressRange(start, end, module.BaseAddress()); + // Round to page boundary start = start & PAGE_MASK; _ASSERTE(start > 0); @@ -297,9 +300,6 @@ void CrashInfo::VisitSegment(MachOModule& module, const segment_command_64& segm } // Add this module segment to the module mappings list m_moduleMappings.insert(moduleRegion); - - // Add this module segment to the set used by the thread unwinding to lookup the module base address for an ip. - AddModuleAddressRange(start, end, module.BaseAddress()); } else { diff --git a/src/coreclr/debug/createdump/stackframe.h b/src/coreclr/debug/createdump/stackframe.h index 75e20d93120c0..00c3a1cfb7fd8 100644 --- a/src/coreclr/debug/createdump/stackframe.h +++ b/src/coreclr/debug/createdump/stackframe.h @@ -66,9 +66,16 @@ struct StackFrame } } +// See comment in threadinfo.cpp UnwindNativeFrames function +#if defined(__aarch64__) + #define STACK_POINTER_MASK ~0x7 +#else + #define STACK_POINTER_MASK ~0x0 +#endif + inline uint64_t ModuleAddress() const { return m_moduleAddress; } inline uint64_t InstructionPointer() const { return m_instructionPointer; } - inline uint64_t StackPointer() const { return m_stackPointer; } + inline uint64_t StackPointer() const { return m_stackPointer & STACK_POINTER_MASK; } inline uint32_t NativeOffset() const { return m_nativeOffset; } inline uint32_t Token() const { return m_token; } inline uint32_t ILOffset() const { return m_ilOffset; } diff --git a/src/coreclr/debug/createdump/threadinfo.cpp b/src/coreclr/debug/createdump/threadinfo.cpp index 82509f5275065..e64eafc8d29a9 100644 --- a/src/coreclr/debug/createdump/threadinfo.cpp +++ b/src/coreclr/debug/createdump/threadinfo.cpp @@ -53,6 +53,16 @@ ThreadInfo::UnwindNativeFrames(CONTEXT* pContext) uint64_t ip = 0, sp = 0; GetFrameLocation(pContext, &ip, &sp); +#if defined(__aarch64__) + // ARM64 can have frames with the same SP but different IPs. Increment sp so it gets added to the stack + // frames in the correct order and to prevent the below loop termination on non-increasing sp. Since stack + // pointers are always 8 byte align, this increase is masked off in StackFrame::StackPointer() to get the + // original stack pointer. + if (sp == previousSp && ip != previousIp) + { + sp++; + } +#endif if (ip == 0 || sp <= previousSp) { TRACE_VERBOSE("Unwind: sp not increasing or ip == 0 sp %p ip %p\n", (void*)sp, (void*)ip); break; diff --git a/src/coreclr/debug/daccess/daccess.cpp b/src/coreclr/debug/daccess/daccess.cpp index 5c2c55cfe439b..9aaf6e6e4cb17 100644 --- a/src/coreclr/debug/daccess/daccess.cpp +++ b/src/coreclr/debug/daccess/daccess.cpp @@ -5690,7 +5690,7 @@ ClrDataAccess::GetJitHelperName( #define JITHELPER(code,fn,sig) #code, #include }; - static_assert_no_msg(COUNTOF(s_rgHelperNames) == CORINFO_HELP_COUNT); + static_assert_no_msg(ARRAY_SIZE(s_rgHelperNames) == CORINFO_HELP_COUNT); #ifdef TARGET_UNIX if (!dynamicHelpersOnly) @@ -5745,7 +5745,7 @@ ClrDataAccess::RawGetMethodName( address &= ~THUMB_CODE; #endif - const UINT k_cch64BitHexFormat = COUNTOF("1234567812345678"); + const UINT k_cch64BitHexFormat = ARRAY_SIZE("1234567812345678"); HRESULT status; if (flags != 0) @@ -5887,7 +5887,7 @@ ClrDataAccess::RawGetMethodName( // Printf failed. Estimate a size that will be at least big enough to hold the name if (symbolLen) { - size_t cchSymbol = COUNTOF(s_wszFormatNameWithStubManager) + + size_t cchSymbol = ARRAY_SIZE(s_wszFormatNameWithStubManager) + wcslen(wszStubManagerName) + k_cch64BitHexFormat + 1; @@ -5950,7 +5950,7 @@ ClrDataAccess::RawGetMethodName( // Printf failed. Estimate a size that will be at least big enough to hold the name if (symbolLen) { - size_t cchSymbol = COUNTOF(s_wszFormatNameAddressOnly) + + size_t cchSymbol = ARRAY_SIZE(s_wszFormatNameAddressOnly) + k_cch64BitHexFormat + 1; diff --git a/src/coreclr/dlls/mscordac/CMakeLists.txt b/src/coreclr/dlls/mscordac/CMakeLists.txt index 8d04b34e48aad..25c2532358774 100644 --- a/src/coreclr/dlls/mscordac/CMakeLists.txt +++ b/src/coreclr/dlls/mscordac/CMakeLists.txt @@ -47,7 +47,7 @@ else(CLR_CMAKE_HOST_WIN32) set(REDEFINES_FILE_SCRIPT ${CMAKE_SOURCE_DIR}/generateredefinesfile.sh) - if (CLR_CMAKE_HOST_ARCH_ARM OR CLR_CMAKE_HOST_ARCH_ARM64) + if (CLR_CMAKE_HOST_ARCH_ARM OR CLR_CMAKE_HOST_ARCH_ARM64 OR CLR_CMAKE_HOST_ARCH_LOONGARCH64) set(JUMP_INSTRUCTION b) else() set(JUMP_INSTRUCTION jmp) diff --git a/src/coreclr/dlls/mscordac/mscordac_unixexports.src b/src/coreclr/dlls/mscordac/mscordac_unixexports.src index 2a529b2f4a779..334d1b90c9308 100644 --- a/src/coreclr/dlls/mscordac/mscordac_unixexports.src +++ b/src/coreclr/dlls/mscordac/mscordac_unixexports.src @@ -65,7 +65,6 @@ nativeStringResourceTable_mscorrc #PAL_wcsrchr #PAL_wcscmp #PAL_wcschr -#PAL_wcscspn #PAL_wcscat #PAL_wcsstr #PAL__open @@ -140,8 +139,6 @@ nativeStringResourceTable_mscorrc #LoadLibraryA #LoadLibraryW #LoadLibraryExW -#LocalAlloc -#LocalFree #MapViewOfFile #MapViewOfFileEx #MoveFileExW diff --git a/src/coreclr/gc/gc.cpp b/src/coreclr/gc/gc.cpp index ace66eac26670..e270bcdc91ee4 100644 --- a/src/coreclr/gc/gc.cpp +++ b/src/coreclr/gc/gc.cpp @@ -2522,6 +2522,8 @@ size_t gc_heap::bgc_loh_size_increased = 0; size_t gc_heap::bgc_poh_size_increased = 0; +size_t gc_heap::background_soh_size_end_mark = 0; + size_t gc_heap::background_soh_alloc_count = 0; size_t gc_heap::background_uoh_alloc_count = 0; @@ -9402,7 +9404,7 @@ void gc_heap::remove_ro_segment (heap_segment* seg) enter_spin_lock (&gc_heap::gc_lock); - seg_table->remove ((uint8_t*)seg); + seg_table->remove (heap_segment_mem (seg)); seg_mapping_table_remove_ro_segment (seg); // Locate segment (and previous segment) in the list. @@ -10890,7 +10892,7 @@ void gc_heap::seg_clear_mark_array_bits_soh (heap_segment* seg) } } -void gc_heap::clear_batch_mark_array_bits (uint8_t* start, uint8_t* end) +void gc_heap::bgc_clear_batch_mark_array_bits (uint8_t* start, uint8_t* end) { if ((start < background_saved_highest_address) && (end > background_saved_lowest_address)) @@ -10914,8 +10916,15 @@ void gc_heap::clear_batch_mark_array_bits (uint8_t* start, uint8_t* end) if (startwrd == endwrd) { - unsigned int wrd = firstwrd | lastwrd; - mark_array[startwrd] &= wrd; + if (startbit != endbit) + { + unsigned int wrd = firstwrd | lastwrd; + mark_array[startwrd] &= wrd; + } + else + { + assert (start == end); + } return; } @@ -10938,18 +10947,6 @@ void gc_heap::clear_batch_mark_array_bits (uint8_t* start, uint8_t* end) } } } - -void gc_heap::bgc_clear_batch_mark_array_bits (uint8_t* start, uint8_t* end) -{ - if ((start < background_saved_highest_address) && - (end > background_saved_lowest_address)) - { - start = max (start, background_saved_lowest_address); - end = min (end, background_saved_highest_address); - - clear_batch_mark_array_bits (start, end); - } -} #endif //BACKGROUND_GC inline @@ -28892,6 +28889,14 @@ void gc_heap::plan_phase (int condemned_gen_number) { dprintf (2,( "**** Doing Compacting GC ****")); +#if defined(USE_REGIONS) && defined(BACKGROUND_GC) + if (should_update_end_mark_size()) + { + background_soh_size_end_mark += generation_end_seg_allocated (older_gen) - + r_older_gen_end_seg_allocated; + } +#endif //USE_REGIONS && BACKGROUND_GC + #ifndef USE_REGIONS if (should_expand) { @@ -29396,6 +29401,13 @@ void gc_heap::fix_generation_bounds (int condemned_gen_number, } } #endif //MULTIPLE_HEAPS + +#ifdef BACKGROUND_GC + if (should_update_end_mark_size()) + { + background_soh_size_end_mark = generation_size (max_generation); + } +#endif //BACKGROUND_GC #endif //!USE_REGIONS { @@ -29614,6 +29626,14 @@ void gc_heap::thread_final_regions (bool compact_p) generation_final_regions[gen_idx].tail = generation_tail_region (gen); } +#ifdef BACKGROUND_GC + heap_segment* max_gen_tail_region = 0; + if (should_update_end_mark_size()) + { + max_gen_tail_region = generation_final_regions[max_generation].tail; + } +#endif //BACKGROUND_GC + // Step 2: for each region in the condemned generations, we thread it onto its planned generation // in our generation_final_regions array. for (int gen_idx = condemned_gen_number; gen_idx >= 0; gen_idx--) @@ -29664,6 +29684,21 @@ void gc_heap::thread_final_regions (bool compact_p) } } +#ifdef BACKGROUND_GC + if (max_gen_tail_region) + { + max_gen_tail_region = heap_segment_next (max_gen_tail_region); + + while (max_gen_tail_region) + { + background_soh_size_end_mark += heap_segment_allocated (max_gen_tail_region) - + heap_segment_mem (max_gen_tail_region); + + max_gen_tail_region = heap_segment_next (max_gen_tail_region); + } + } +#endif //BACKGROUND_GC + // Step 4: if a generation doesn't have any regions, we need to get a new one for it; // otherwise we just set the head region as the start region for that generation. for (int gen_idx = 0; gen_idx <= max_generation; gen_idx++) @@ -29701,7 +29736,7 @@ void gc_heap::thread_final_regions (bool compact_p) } } - verify_regions (true); + verify_regions (true, false); } void gc_heap::thread_start_region (generation* gen, heap_segment* region) @@ -29752,7 +29787,7 @@ heap_segment* gc_heap::get_new_region (int gen_number, size_t size) heap_segment_next (generation_tail_region (gen)) = new_region; generation_tail_region (gen) = new_region; - verify_regions (gen_number, false); + verify_regions (gen_number, false, settings.concurrent); } return new_region; @@ -29779,6 +29814,12 @@ heap_segment* gc_heap::allocate_new_region (gc_heap* hp, int gen_num, bool uoh_p heap_segment* res = make_heap_segment (start, (end - start), hp, gen_num); dprintf (REGIONS_LOG, ("got a new region %Ix %Ix->%Ix", (size_t)res, start, end)); + + if (res == nullptr) + { + global_region_allocator.delete_region (start); + } + return res; } @@ -29815,7 +29856,7 @@ void gc_heap::update_start_tail_regions (generation* gen, (size_t)prev_region, heap_segment_mem (prev_region))); } - verify_regions (false); + verify_regions (false, settings.concurrent); } // There's one complication with deciding whether we can make a region SIP or not - if the plan_gen_num of @@ -30090,6 +30131,8 @@ inline void gc_heap::check_demotion_helper_sip (uint8_t** pval, int parent_gen_num, uint8_t* parent_loc) { uint8_t* child_object = *pval; + if (!is_in_heap_range (child_object)) + return; if (!child_object) return; int child_object_plan_gen = get_region_plan_gen_num (child_object); @@ -32927,6 +32970,11 @@ void gc_heap::decommit_mark_array_by_seg (heap_segment* seg) } } +bool gc_heap::should_update_end_mark_size() +{ + return ((settings.condemned_generation == (max_generation - 1)) && (current_c_gc_state == c_gc_state_planning)); +} + void gc_heap::background_mark_phase () { verify_mark_array_cleared(); @@ -33001,6 +33049,7 @@ void gc_heap::background_mark_phase () bgc_begin_poh_size = total_poh_size; bgc_loh_size_increased = 0; bgc_poh_size_increased = 0; + background_soh_size_end_mark = 0; dprintf (GTC_LOG, ("BM: h%d: loh: %Id, soh: %Id, poh: %Id", heap_number, total_loh_size, total_soh_size, total_poh_size)); @@ -33481,6 +33530,8 @@ void gc_heap::background_mark_phase () heap_segment_background_allocated (seg) = heap_segment_allocated (seg); } + background_soh_size_end_mark += heap_segment_background_allocated (seg) - heap_segment_mem (seg); + dprintf (3333, ("h%d gen%d seg %Ix (%Ix) background allocated is %Ix", heap_number, i, (size_t)(seg), heap_segment_mem (seg), heap_segment_background_allocated (seg))); @@ -42103,7 +42154,7 @@ gc_heap::verify_free_lists () } } -void gc_heap::verify_regions (int gen_number, bool can_verify_gen_num) +void gc_heap::verify_regions (int gen_number, bool can_verify_gen_num, bool can_verify_tail) { #ifdef USE_REGIONS // For the given generation, verify that @@ -42166,7 +42217,7 @@ void gc_heap::verify_regions (int gen_number, bool can_verify_gen_num) FATAL_GC_ERROR(); } - if (tail_region != prev_region_in_gen) + if (can_verify_tail && (tail_region != prev_region_in_gen)) { dprintf (REGIONS_LOG, ("h%d gen%d tail region is %Ix(%Ix), diff from last region %Ix(%Ix)!!", heap_number, gen_number, @@ -42177,12 +42228,18 @@ void gc_heap::verify_regions (int gen_number, bool can_verify_gen_num) #endif //USE_REGIONS } -void gc_heap::verify_regions (bool can_verify_gen_num) +inline bool is_user_alloc_gen (int gen_number) +{ + return ((gen_number == soh_gen0) || (gen_number == loh_generation) || (gen_number == poh_generation)); +} + +void gc_heap::verify_regions (bool can_verify_gen_num, bool concurrent_p) { #ifdef USE_REGIONS for (int i = 0; i < total_generation_count; i++) { - verify_regions (i, can_verify_gen_num); + bool can_verify_tail = (concurrent_p ? !is_user_alloc_gen (i) : true); + verify_regions (i, can_verify_gen_num, can_verify_tail); } #endif //USE_REGIONS } @@ -42313,7 +42370,7 @@ void gc_heap::verify_heap (BOOL begin_gc_p) //verify that the generation structures makes sense { #ifdef USE_REGIONS - verify_regions (true); + verify_regions (true, settings.concurrent); #else //USE_REGIONS generation* gen = generation_of (max_generation); @@ -43374,8 +43431,15 @@ void GCHeap::SetYieldProcessorScalingFactor (float scalingFactor) unsigned int GCHeap::WhichGeneration (Object* object) { - gc_heap* hp = gc_heap::heap_of ((uint8_t*)object); - unsigned int g = hp->object_gennum ((uint8_t*)object); + uint8_t* o = (uint8_t*)object; +#ifdef FEATURE_BASICFREEZE + if (!((o < g_gc_highest_address) && (o >= g_gc_lowest_address))) + { + return max_generation; + } +#endif //FEATURE_BASICFREEZE + gc_heap* hp = gc_heap::heap_of (o); + unsigned int g = hp->object_gennum (o); dprintf (3, ("%Ix is in gen %d", (size_t)object, g)); return g; } @@ -45097,11 +45161,11 @@ size_t GCHeap::GetTotalBytesInUse () for (int i = 0; i < gc_heap::n_heaps; i++) { GCHeap* Hp = gc_heap::g_heaps [i]->vm_heap; - tot_size += Hp->ApproxTotalBytesInUse (FALSE); + tot_size += Hp->ApproxTotalBytesInUse(); } return tot_size; #else - return ApproxTotalBytesInUse (); + return ApproxTotalBytesInUse(); #endif //MULTIPLE_HEAPS } @@ -45156,58 +45220,58 @@ size_t GCHeap::ApproxTotalBytesInUse(BOOL small_heap_only) size_t totsize = 0; enter_spin_lock (&pGenGCHeap->gc_lock); - // the complication with the following code is that background GC may - // remove the ephemeral segment while we are iterating - // if so, we retry a couple times and ultimately may report a slightly wrong result - for (int tries = 1; tries <= 3; tries++) + // For gen0 it's a bit complicated because we are currently allocating in it. We get the fragmentation first + // just so that we don't give a negative number for the resulting size. + generation* gen = pGenGCHeap->generation_of (0); + size_t gen0_frag = generation_free_list_space (gen) + generation_free_obj_space (gen); + uint8_t* current_alloc_allocated = pGenGCHeap->alloc_allocated; + heap_segment* current_eph_seg = pGenGCHeap->ephemeral_heap_segment; + size_t gen0_size = 0; +#ifdef USE_REGIONS + heap_segment* gen0_seg = generation_start_segment (gen); + while (gen0_seg) { - heap_segment* eph_seg = generation_allocation_segment (pGenGCHeap->generation_of (0)); - // Get small block heap size info - totsize = (pGenGCHeap->alloc_allocated - heap_segment_mem (eph_seg)); - heap_segment* seg1 = generation_start_segment (pGenGCHeap->generation_of (max_generation)); - while ((seg1 != eph_seg) && (seg1 != nullptr) -#ifdef BACKGROUND_GC - && (seg1 != pGenGCHeap->freeable_soh_segment) -#endif //BACKGROUND_GC - ) + uint8_t* end = in_range_for_segment (current_alloc_allocated, gen0_seg) ? + current_alloc_allocated : heap_segment_allocated (gen0_seg); + gen0_size += end - heap_segment_mem (gen0_seg); + + if (gen0_seg == current_eph_seg) { -#ifdef BACKGROUND_GC - if (!heap_segment_decommitted_p (seg1)) -#endif //BACKGROUND_GC - { - totsize += heap_segment_allocated (seg1) - - heap_segment_mem (seg1); - } - seg1 = heap_segment_next (seg1); - } - if (seg1 == eph_seg) break; + } + + gen0_seg = heap_segment_next (gen0_seg); + } +#else //USE_REGIONS + // For segments ephemeral seg does not change. + gen0_size = current_alloc_allocated - heap_segment_mem (current_eph_seg); +#endif //USE_REGIONS + + totsize = gen0_size - gen0_frag; + + int stop_gen_index = max_generation; + + if (gc_heap::current_c_gc_state == c_gc_state_planning) + { + // During BGC sweep since we can be deleting SOH segments, we avoid walking the segment + // list. + generation* oldest_gen = pGenGCHeap->generation_of (max_generation); + totsize = pGenGCHeap->background_soh_size_end_mark - generation_free_list_space (oldest_gen) - generation_free_obj_space (oldest_gen); + stop_gen_index--; } - //discount the fragmentation - for (int i = 0; i <= max_generation; i++) + for (int i = (max_generation - 1); i <= stop_gen_index; i++) { generation* gen = pGenGCHeap->generation_of (i); - totsize -= (generation_free_list_space (gen) + generation_free_obj_space (gen)); + totsize += pGenGCHeap->generation_size (i) - generation_free_list_space (gen) - generation_free_obj_space (gen); } if (!small_heap_only) { for (int i = uoh_start_generation; i < total_generation_count; i++) { - heap_segment* seg2 = generation_start_segment (pGenGCHeap->generation_of (i)); - - while (seg2 != 0) - { - totsize += heap_segment_allocated (seg2) - - heap_segment_mem (seg2); - seg2 = heap_segment_next (seg2); - } - - //discount the fragmentation - generation* uoh_gen = pGenGCHeap->generation_of (i); - size_t frag = generation_free_list_space (uoh_gen) + generation_free_obj_space (uoh_gen); - totsize -= frag; + generation* gen = pGenGCHeap->generation_of (i); + totsize += pGenGCHeap->generation_size (i) - generation_free_list_space (gen) - generation_free_obj_space (gen); } } leave_spin_lock (&pGenGCHeap->gc_lock); diff --git a/src/coreclr/gc/gcinterface.dac.h b/src/coreclr/gc/gcinterface.dac.h index cfffcf1221a81..c7d72c7145baf 100644 --- a/src/coreclr/gc/gcinterface.dac.h +++ b/src/coreclr/gc/gcinterface.dac.h @@ -111,7 +111,7 @@ enum oom_reason /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ /* If you modify failure_get_memory and */ /* oom_reason be sure to make the corresponding */ -/* changes in toolbox\sos\strike\strike.cpp. */ +/* changes in tools\sos\strike\strike.cpp. */ /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ enum failure_get_memory { diff --git a/src/coreclr/gc/gcpriv.h b/src/coreclr/gc/gcpriv.h index 081b9a539c073..baa0272db1368 100644 --- a/src/coreclr/gc/gcpriv.h +++ b/src/coreclr/gc/gcpriv.h @@ -51,7 +51,7 @@ inline void FATAL_GC_ERROR() // // This means any empty regions can be freely used for any generation. For // Server GC we will balance regions between heaps. -// For now enable regions by default for only StandAlone GC builds +// For now disable regions outside of StandAlone GC builds #if defined (HOST_64BIT) && defined (BUILD_AS_STANDALONE) #define USE_REGIONS #endif //HOST_64BIT && BUILD_AS_STANDALONE @@ -1286,9 +1286,9 @@ class gc_heap PER_HEAP void verify_free_lists(); PER_HEAP - void verify_regions (int gen_number, bool can_verify_gen_num); + void verify_regions (int gen_number, bool can_verify_gen_num, bool can_verify_tail); PER_HEAP - void verify_regions (bool can_verify_gen_num); + void verify_regions (bool can_verify_gen_num, bool concurrent_p); PER_HEAP_ISOLATED void enter_gc_lock_for_verify_heap(); PER_HEAP_ISOLATED @@ -2156,8 +2156,6 @@ class gc_heap PER_HEAP void seg_clear_mark_array_bits_soh (heap_segment* seg); PER_HEAP - void clear_batch_mark_array_bits (uint8_t* start, uint8_t* end); - PER_HEAP void bgc_clear_batch_mark_array_bits (uint8_t* start, uint8_t* end); #ifdef VERIFY_HEAP PER_HEAP @@ -3440,6 +3438,9 @@ class gc_heap PER_HEAP void decommit_mark_array_by_seg (heap_segment* seg); + PER_HEAP_ISOLATED + bool should_update_end_mark_size(); + PER_HEAP void background_mark_phase(); @@ -4268,6 +4269,9 @@ class gc_heap PER_HEAP size_t bgc_poh_size_increased; + PER_HEAP + size_t background_soh_size_end_mark; + PER_HEAP size_t background_soh_alloc_count; diff --git a/src/coreclr/gc/unix/gcenv.unix.cpp b/src/coreclr/gc/unix/gcenv.unix.cpp index 895d2afdf395a..2d979c395610e 100644 --- a/src/coreclr/gc/unix/gcenv.unix.cpp +++ b/src/coreclr/gc/unix/gcenv.unix.cpp @@ -28,6 +28,10 @@ #undef min #undef max +#ifndef __has_cpp_attribute +#define __has_cpp_attribute(x) (0) +#endif + #if __has_cpp_attribute(fallthrough) #define FALLTHROUGH [[fallthrough]] #else @@ -98,7 +102,7 @@ extern "C" # define __NR_membarrier 389 # elif defined(__aarch64__) # define __NR_membarrier 283 -# elif +# else # error Unknown architecture # endif # endif diff --git a/src/coreclr/hosts/corerun/dotenv.cpp b/src/coreclr/hosts/corerun/dotenv.cpp index ba22f5004713d..0e0e37c7919b0 100644 --- a/src/coreclr/hosts/corerun/dotenv.cpp +++ b/src/coreclr/hosts/corerun/dotenv.cpp @@ -4,10 +4,13 @@ #include "dotenv.hpp" #include #include -#include #include #include +#ifdef TARGET_WINDOWS +#include +#endif + namespace { pal::string_t convert_to_string_t(std::string str) diff --git a/src/coreclr/hosts/coreshim/CoreShim.cpp b/src/coreclr/hosts/coreshim/CoreShim.cpp index 62ab011df1215..23265e5872b3f 100644 --- a/src/coreclr/hosts/coreshim/CoreShim.cpp +++ b/src/coreclr/hosts/coreshim/CoreShim.cpp @@ -375,7 +375,7 @@ HRESULT coreclr::Initialize( HMODULE mod = ::GetModuleHandleW(W("CoreRun.exe")); if (mod != NULL) { - using GetCurrentClrDetailsFunc = HRESULT(*)(void **clrInstance, unsigned int *appDomainId); + using GetCurrentClrDetailsFunc = HRESULT(__cdecl *)(void **clrInstance, unsigned int *appDomainId); auto getCurrentClrDetails = (GetCurrentClrDetailsFunc)::GetProcAddress(mod, "GetCurrentClrDetails"); RETURN_IF_FAILED(getCurrentClrDetails(&_clrInst, &_appDomainId)); if (_clrInst != nullptr) diff --git a/src/coreclr/ildasm/dasm.cpp b/src/coreclr/ildasm/dasm.cpp index 63c3d5bf98e22..ae7dcd603c9b9 100644 --- a/src/coreclr/ildasm/dasm.cpp +++ b/src/coreclr/ildasm/dasm.cpp @@ -183,7 +183,7 @@ void DumpCustomAttributeProps(mdToken tkCA, mdToken tkType, mdToken tkOwner, BYT WCHAR* RstrW(unsigned id) { static WCHAR buffer[1024]; - DWORD cchBuff = (DWORD)COUNTOF(buffer); + DWORD cchBuff = (DWORD)ARRAY_SIZE(buffer); WCHAR* buff = (WCHAR*)buffer; memset(buffer,0,sizeof(buffer)); switch(id) @@ -221,7 +221,7 @@ WCHAR* RstrW(unsigned id) case IDS_E_CANTACCESSW32RES: case IDS_E_CANTOPENW32RES: case IDS_ERRORREOPENINGFILE: - wcscpy_s(buffer,COUNTOF(buffer),W("// ")); + wcscpy_s(buffer,ARRAY_SIZE(buffer),W("// ")); buff +=3; cchBuff -= 3; break; @@ -232,12 +232,12 @@ WCHAR* RstrW(unsigned id) case IDS_E_CODESIZE: case IDS_W_CREATEDMRES: case IDS_E_READINGMRES: - wcscpy_s(buffer,COUNTOF(buffer),W("%s// ")); + wcscpy_s(buffer,ARRAY_SIZE(buffer),W("%s// ")); buff +=5; cchBuff -= 5; break; case IDS_E_NORVA: - wcscpy_s(buffer,COUNTOF(buffer),W("/* ")); + wcscpy_s(buffer,ARRAY_SIZE(buffer),W("/* ")); buff += 3; cchBuff -= 3; break; @@ -3695,7 +3695,7 @@ BOOL DumpMethod(mdToken FuncToken, const char *pszClassName, DWORD dwEntryPointT if (FAILED(g_pImport->GetParamDefProps(tkArg, &wSequence, &dwAttr, &szName))) { char sz[256]; - sprintf_s(sz, COUNTOF(sz), RstrUTF(IDS_E_INVALIDRECORD), tkArg); + sprintf_s(sz, ARRAY_SIZE(sz), RstrUTF(IDS_E_INVALIDRECORD), tkArg); printError(GUICookie, sz); continue; } diff --git a/src/coreclr/ildasm/dasm_formattype.cpp b/src/coreclr/ildasm/dasm_formattype.cpp index f12ed036ba849..44311a87377c0 100644 --- a/src/coreclr/ildasm/dasm_formattype.cpp +++ b/src/coreclr/ildasm/dasm_formattype.cpp @@ -169,7 +169,7 @@ const char* ANCHORPT(_In_ __nullterminated const char* szOrig, mdToken tk) { char szPrefix[64]; const char* szPostfix = ""; - sprintf_s(szPrefix, COUNTOF(szPrefix), "",tk); + sprintf_s(szPrefix, ARRAY_SIZE(szPrefix), "",tk); g_szBuf_ANCHORPT->Shrink(0); appendStr(g_szBuf_ANCHORPT,szPrefix); appendStr(g_szBuf_ANCHORPT,szOrig); @@ -192,7 +192,7 @@ const char* JUMPPT(_In_ __nullterminated const char* szOrig, mdToken tk) { char szPrefix[64]; const char* szPostfix = ""; - sprintf_s(szPrefix,COUNTOF(szPrefix), "",tk); + sprintf_s(szPrefix,ARRAY_SIZE(szPrefix), "",tk); g_szBuf_JUMPPT->Shrink(0); appendStr(g_szBuf_JUMPPT,szPrefix); appendStr(g_szBuf_JUMPPT,szOrig); diff --git a/src/coreclr/inc/bbsweep.h b/src/coreclr/inc/bbsweep.h index eda1e11d2f2e1..4e3636681e4e4 100644 --- a/src/coreclr/inc/bbsweep.h +++ b/src/coreclr/inc/bbsweep.h @@ -31,11 +31,9 @@ #pragma push_macro("SetEvent") #pragma push_macro("ResetEvent") #pragma push_macro("ReleaseSemaphore") -#pragma push_macro("LocalFree") #undef SetEvent #undef ResetEvent #undef ReleaseSemaphore -#undef LocalFree // MAX_COUNT is the maximal number of runtime processes that can run at a given time #define MAX_COUNT 20 @@ -299,7 +297,6 @@ class BBSweep if (pSD) delete [] ((char *) pSD); if (pAdminSid) FreeSid(pAdminSid); if (hToken) CloseHandle(hToken); - if (pACL) LocalFree(pACL); if (buffer) delete [] ((char *) buffer); #endif } @@ -416,7 +413,6 @@ class BBSweep HANDLE hBBSweepThread; // a handle to the CLR sweeper thread (that calls watch for sweep events) }; -#pragma pop_macro("LocalFree") #pragma pop_macro("ReleaseSemaphore") #pragma pop_macro("ResetEvent") #pragma pop_macro("SetEvent") diff --git a/src/coreclr/inc/clrconfigvalues.h b/src/coreclr/inc/clrconfigvalues.h index a14ba1ec98da4..28b1010666369 100644 --- a/src/coreclr/inc/clrconfigvalues.h +++ b/src/coreclr/inc/clrconfigvalues.h @@ -348,14 +348,8 @@ RETAIL_CONFIG_DWORD_INFO(INTERNAL_JitVNMapSelBudget, W("JitVNMapSelBudget"), 100 #else // !(defined(TARGET_AMD64) || defined(TARGET_X86) || defined(TARGET_ARM64)) #define EXTERNAL_FeatureSIMD_Default 0 #endif // !(defined(TARGET_AMD64) || defined(TARGET_X86) || defined(TARGET_ARM64)) -#if defined(TARGET_AMD64) || defined(TARGET_X86) -#define EXTERNAL_JitEnableAVX_Default 1 -#else // !(defined(TARGET_AMD64) || defined(TARGET_X86) -#define EXTERNAL_JitEnableAVX_Default 0 -#endif // !(defined(TARGET_AMD64) || defined(TARGET_X86) RETAIL_CONFIG_DWORD_INFO(EXTERNAL_FeatureSIMD, W("FeatureSIMD"), EXTERNAL_FeatureSIMD_Default, "Enable SIMD intrinsics recognition in System.Numerics.dll and/or System.Numerics.Vectors.dll") RETAIL_CONFIG_DWORD_INFO(INTERNAL_SIMD16ByteOnly, W("SIMD16ByteOnly"), 0, "Limit maximum SIMD vector length to 16 bytes (used by x64_arm64_altjit)") -RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableAVX, W("EnableAVX"), EXTERNAL_JitEnableAVX_Default, "Enable AVX instruction set for wide operations as default") RETAIL_CONFIG_DWORD_INFO(UNSUPPORTED_TrackDynamicMethodDebugInfo, W("TrackDynamicMethodDebugInfo"), 0, "Specifies whether debug info should be generated and tracked for dynamic methods") #ifdef FEATURE_MULTICOREJIT @@ -724,6 +718,41 @@ RETAIL_CONFIG_DWORD_INFO(INTERNAL_GDBJitEmitDebugFrame, W("GDBJitEmitDebugFrame" #endif #endif +// +// Hardware Intrinsic ISAs +// +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableHWIntrinsic, W("EnableHWIntrinsic"), 1, "Allows Base+ hardware intrinsics to be disabled") + +#if defined(TARGET_AMD64) || defined(TARGET_X86) +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableAES, W("EnableAES"), 1, "Allows AES+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableAVX, W("EnableAVX"), 1, "Allows AVX+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableAVX2, W("EnableAVX2"), 1, "Allows AVX2+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableAVXVNNI, W("EnableAVXVNNI"), 1, "Allows AVX VNNI+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableBMI1, W("EnableBMI1"), 1, "Allows BMI1+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableBMI2, W("EnableBMI2"), 1, "Allows BMI2+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableFMA, W("EnableFMA"), 1, "Allows FMA+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableLZCNT, W("EnableLZCNT"), 1, "Allows LZCNT+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnablePCLMULQDQ, W("EnablePCLMULQDQ"), 1, "Allows PCLMULQDQ+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnablePOPCNT, W("EnablePOPCNT"), 1, "Allows POPCNT+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableSSE, W("EnableSSE"), 1, "Allows SSE+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableSSE2, W("EnableSSE2"), 1, "Allows SSE2+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableSSE3, W("EnableSSE3"), 1, "Allows SSE3+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableSSE3_4, W("EnableSSE3_4"), 1, "Allows SSE3+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableSSE41, W("EnableSSE41"), 1, "Allows SSE4.1+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableSSE42, W("EnableSSE42"), 1, "Allows SSE4.2+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableSSSE3, W("EnableSSSE3"), 1, "Allows SSSE3+ hardware intrinsics to be disabled") +#elif defined(TARGET_ARM64) +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64AdvSimd, W("EnableArm64AdvSimd"), 1, "Allows Arm64 AdvSimd+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64Aes, W("EnableArm64Aes"), 1, "Allows Arm64 Aes+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64Atomics, W("EnableArm64Atomics"), 1, "Allows Arm64 Atomics+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64Crc32, W("EnableArm64Crc32"), 1, "Allows Arm64 Crc32+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64Dczva, W("EnableArm64Dczva"), 1, "Allows Arm64 Dczva+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64Dp, W("EnableArm64Dp"), 1, "Allows Arm64 Dp+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64Rdm, W("EnableArm64Rdm"), 1, "Allows Arm64 Rdm+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64Sha1, W("EnableArm64Sha1"), 1, "Allows Arm64 Sha1+ hardware intrinsics to be disabled") +RETAIL_CONFIG_DWORD_INFO(EXTERNAL_EnableArm64Sha256, W("EnableArm64Sha256"), 1, "Allows Arm64 Sha256+ hardware intrinsics to be disabled") +#endif + /// /// Uncategorized /// diff --git a/src/coreclr/inc/corhlpr.h b/src/coreclr/inc/corhlpr.h index 427e8cdc0ff5c..a4021921dd6eb 100644 --- a/src/coreclr/inc/corhlpr.h +++ b/src/coreclr/inc/corhlpr.h @@ -86,16 +86,11 @@ do { hr = (EXPR); if(FAILED(hr)) { goto LABEL; } } while (0) #define _ASSERTE(expr) #endif -#ifndef COUNTOF -#define COUNTOF(a) (sizeof(a) / sizeof(*a)) -#endif - #if !BIGENDIAN #define VAL16(x) x #define VAL32(x) x #endif - //***************************************************************************** // //***** Macro to assist with cleaning up local static variables diff --git a/src/coreclr/inc/corinfo.h b/src/coreclr/inc/corinfo.h index 75e50a6d64380..3bad0df909e9a 100644 --- a/src/coreclr/inc/corinfo.h +++ b/src/coreclr/inc/corinfo.h @@ -3098,12 +3098,6 @@ class ICorDynamicInfo : public ICorStaticInfo void **ppIndirection = NULL ) = 0; - // Sets another object to intercept calls to "self" and current method being compiled - virtual void setOverride( - ICorDynamicInfo *pOverride, - CORINFO_METHOD_HANDLE currentMethod - ) = 0; - // Adds an active dependency from the context method's module to the given module // This is internal callback for the EE. JIT should not call it directly. virtual void addActiveDependency( diff --git a/src/coreclr/inc/corinfoinstructionset.h b/src/coreclr/inc/corinfoinstructionset.h index 39003cb739852..b068b316168f5 100644 --- a/src/coreclr/inc/corinfoinstructionset.h +++ b/src/coreclr/inc/corinfoinstructionset.h @@ -282,6 +282,10 @@ inline CORINFO_InstructionSetFlags EnsureInstructionSetFlagsAreValid(CORINFO_Ins resultflags.RemoveInstructionSet(InstructionSet_Sha1); if (resultflags.HasInstructionSet(InstructionSet_Sha256) && !resultflags.HasInstructionSet(InstructionSet_ArmBase)) resultflags.RemoveInstructionSet(InstructionSet_Sha256); + if (resultflags.HasInstructionSet(InstructionSet_Vector64) && !resultflags.HasInstructionSet(InstructionSet_AdvSimd)) + resultflags.RemoveInstructionSet(InstructionSet_Vector64); + if (resultflags.HasInstructionSet(InstructionSet_Vector128) && !resultflags.HasInstructionSet(InstructionSet_AdvSimd)) + resultflags.RemoveInstructionSet(InstructionSet_Vector128); #endif // TARGET_ARM64 #ifdef TARGET_AMD64 if (resultflags.HasInstructionSet(InstructionSet_X86Base) && !resultflags.HasInstructionSet(InstructionSet_X86Base_X64)) @@ -376,12 +380,18 @@ inline CORINFO_InstructionSetFlags EnsureInstructionSetFlagsAreValid(CORINFO_Ins resultflags.RemoveInstructionSet(InstructionSet_BMI2); if (resultflags.HasInstructionSet(InstructionSet_FMA) && !resultflags.HasInstructionSet(InstructionSet_AVX)) resultflags.RemoveInstructionSet(InstructionSet_FMA); + if (resultflags.HasInstructionSet(InstructionSet_LZCNT) && !resultflags.HasInstructionSet(InstructionSet_X86Base)) + resultflags.RemoveInstructionSet(InstructionSet_LZCNT); if (resultflags.HasInstructionSet(InstructionSet_PCLMULQDQ) && !resultflags.HasInstructionSet(InstructionSet_SSE2)) resultflags.RemoveInstructionSet(InstructionSet_PCLMULQDQ); if (resultflags.HasInstructionSet(InstructionSet_POPCNT) && !resultflags.HasInstructionSet(InstructionSet_SSE42)) resultflags.RemoveInstructionSet(InstructionSet_POPCNT); + if (resultflags.HasInstructionSet(InstructionSet_Vector128) && !resultflags.HasInstructionSet(InstructionSet_SSE)) + resultflags.RemoveInstructionSet(InstructionSet_Vector128); if (resultflags.HasInstructionSet(InstructionSet_Vector256) && !resultflags.HasInstructionSet(InstructionSet_AVX)) resultflags.RemoveInstructionSet(InstructionSet_Vector256); + if (resultflags.HasInstructionSet(InstructionSet_AVXVNNI) && !resultflags.HasInstructionSet(InstructionSet_AVX2)) + resultflags.RemoveInstructionSet(InstructionSet_AVXVNNI); #endif // TARGET_AMD64 #ifdef TARGET_X86 if (resultflags.HasInstructionSet(InstructionSet_SSE) && !resultflags.HasInstructionSet(InstructionSet_X86Base)) @@ -408,12 +418,18 @@ inline CORINFO_InstructionSetFlags EnsureInstructionSetFlagsAreValid(CORINFO_Ins resultflags.RemoveInstructionSet(InstructionSet_BMI2); if (resultflags.HasInstructionSet(InstructionSet_FMA) && !resultflags.HasInstructionSet(InstructionSet_AVX)) resultflags.RemoveInstructionSet(InstructionSet_FMA); + if (resultflags.HasInstructionSet(InstructionSet_LZCNT) && !resultflags.HasInstructionSet(InstructionSet_X86Base)) + resultflags.RemoveInstructionSet(InstructionSet_LZCNT); if (resultflags.HasInstructionSet(InstructionSet_PCLMULQDQ) && !resultflags.HasInstructionSet(InstructionSet_SSE2)) resultflags.RemoveInstructionSet(InstructionSet_PCLMULQDQ); if (resultflags.HasInstructionSet(InstructionSet_POPCNT) && !resultflags.HasInstructionSet(InstructionSet_SSE42)) resultflags.RemoveInstructionSet(InstructionSet_POPCNT); + if (resultflags.HasInstructionSet(InstructionSet_Vector128) && !resultflags.HasInstructionSet(InstructionSet_SSE)) + resultflags.RemoveInstructionSet(InstructionSet_Vector128); if (resultflags.HasInstructionSet(InstructionSet_Vector256) && !resultflags.HasInstructionSet(InstructionSet_AVX)) resultflags.RemoveInstructionSet(InstructionSet_Vector256); + if (resultflags.HasInstructionSet(InstructionSet_AVXVNNI) && !resultflags.HasInstructionSet(InstructionSet_AVX2)) + resultflags.RemoveInstructionSet(InstructionSet_AVXVNNI); #endif // TARGET_X86 } while (!oldflags.Equals(resultflags)); diff --git a/src/coreclr/inc/dacvars.h b/src/coreclr/inc/dacvars.h index fdae380a90cb4..686c77217395e 100644 --- a/src/coreclr/inc/dacvars.h +++ b/src/coreclr/inc/dacvars.h @@ -5,7 +5,7 @@ // 1. in daccess.h to build the table of DAC globals // 2. in enummem.cpp to dump out the related memory of static and globals // in a mini dump or heap dump -// 3. in DacUpdateDll and toolbox\DacTablenGen\main.cs +// 3. in DacUpdateDll and tools\DacTablenGen\main.cs // // To use this functionality for other tools or purposes, define the // DEFINE_DACVAR macro & include dacvars.h like so (see enummem.cpp and/or diff --git a/src/coreclr/inc/formattype.cpp b/src/coreclr/inc/formattype.cpp index 687fc71a6a49c..7100fe285ab14 100644 --- a/src/coreclr/inc/formattype.cpp +++ b/src/coreclr/inc/formattype.cpp @@ -81,7 +81,7 @@ static void appendStrNum(CQuickBytes *out, int num) { CONTRACTL_END; char buff[16]; - sprintf_s(buff, COUNTOF(buff), "%d", num); + sprintf_s(buff, ARRAY_SIZE(buff), "%d", num); appendStr(out, buff); } @@ -265,14 +265,14 @@ PCCOR_SIGNATURE PrettyPrintSignature( callConvUndefined, callConvUndefined }; - static_assert_no_msg(COUNTOF(callConvNames) == (IMAGE_CEE_CS_CALLCONV_MASK + 1)); + static_assert_no_msg(ARRAY_SIZE(callConvNames) == (IMAGE_CEE_CS_CALLCONV_MASK + 1)); char tmp[32]; unsigned callConvIdx = callConv & IMAGE_CEE_CS_CALLCONV_MASK; const char* name_cc = callConvNames[callConvIdx]; if (name_cc == callConvUndefined) { - sprintf_s(tmp, COUNTOF(tmp), "callconv(%u) ", callConvIdx); + sprintf_s(tmp, ARRAY_SIZE(tmp), "callconv(%u) ", callConvIdx); name_cc = tmp; } @@ -290,14 +290,14 @@ PCCOR_SIGNATURE PrettyPrintSignature( if(pszArgName) { argname[0] = 0; - DumpParamAttr(argname,COUNTOF(argname),pszArgName[ixArg+numArgs].attr); + DumpParamAttr(argname, ARRAY_SIZE(argname), pszArgName[ixArg+numArgs].attr); appendStr(out,argname); } typePtr = PrettyPrintTypeOrDef(typePtr, out, pIMDI); if(pszArgName) { argname[0] = ' '; argname[1] = 0; - DumpMarshaling(pIMDI,argname,COUNTOF(argname),pszArgName[ixArg+numArgs].tok); + DumpMarshaling(pIMDI,argname, ARRAY_SIZE(argname), pszArgName[ixArg+numArgs].tok); appendStr(out,argname); } if(*name != 0) @@ -355,7 +355,7 @@ PCCOR_SIGNATURE PrettyPrintSignature( if(pszArgName) { argname[0] = 0; - DumpParamAttr(argname,COUNTOF(argname),pszArgName[ixArg].attr); + DumpParamAttr(argname, ARRAY_SIZE(argname), pszArgName[ixArg].attr); appendStr(out,argname); } typePtr = PrettyPrintTypeOrDef(typePtr, out, pIMDI); @@ -364,10 +364,10 @@ PCCOR_SIGNATURE PrettyPrintSignature( if(pszArgName) { argname[0] = ' '; argname[1] = 0; - DumpMarshaling(pIMDI,argname,COUNTOF(argname),pszArgName[ixArg].tok); - strcat_s(argname, COUNTOF(argname), ProperName(pszArgName[ixArg++].name)); + DumpMarshaling(pIMDI,argname, ARRAY_SIZE(argname), pszArgName[ixArg].tok); + strcat_s(argname, ARRAY_SIZE(argname), ProperName(pszArgName[ixArg++].name)); } - else sprintf_s(argname,COUNTOF(argname)," %s_%d",label,ixArg++); + else sprintf_s(argname, ARRAY_SIZE(argname), " %s_%d", label,ixArg++); appendStr(out,argname); } --numArgs; @@ -392,7 +392,7 @@ PCCOR_SIGNATURE PrettyPrintSignature( appendChar(out, ','); if(pszArgName) { - sprintf_s(argname,COUNTOF(argname),"[%d] ",pszArgName[ixArg].attr); + sprintf_s(argname,ARRAY_SIZE(argname),"[%d] ",pszArgName[ixArg].attr); appendStr(out,argname); } typePtr = PrettyPrintTypeOrDef(typePtr, out, pIMDI); @@ -400,9 +400,9 @@ PCCOR_SIGNATURE PrettyPrintSignature( { if(pszArgName) { - sprintf_s(argname,COUNTOF(argname)," %s",ProperLocalName(pszArgName[ixArg++].name)); + sprintf_s(argname,ARRAY_SIZE(argname)," %s",ProperLocalName(pszArgName[ixArg++].name)); } - else sprintf_s(argname,COUNTOF(argname)," %s_%d",label,ixArg++); + else sprintf_s(argname,ARRAY_SIZE(argname)," %s_%d",label,ixArg++); appendStr(out,argname); } --numArgs; @@ -689,7 +689,7 @@ PCCOR_SIGNATURE PrettyPrintType( } char sz[32]; - sprintf_s(sz, COUNTOF(sz), " /* MT: 0x%p */", pMT); + sprintf_s(sz, ARRAY_SIZE(sz), " /* MT: 0x%p */", pMT); appendStr(out, sz); break; } @@ -731,7 +731,7 @@ PCCOR_SIGNATURE PrettyPrintType( if(typ) { char sz[64]; - sprintf_s(sz,COUNTOF(sz),"/* UNKNOWN TYPE (0x%X)*/",typ); + sprintf_s(sz,ARRAY_SIZE(sz),"/* UNKNOWN TYPE (0x%X)*/",typ); appendStr(out, ERRORMSG(sz)); } break; @@ -762,7 +762,7 @@ const char* PrettyPrintClass( if(!pIMDI->IsValidToken(tk)) { char str[1024]; - sprintf_s(str,COUNTOF(str)," [ERROR: INVALID TOKEN 0x%8.8X] ",tk); + sprintf_s(str,ARRAY_SIZE(str)," [ERROR: INVALID TOKEN 0x%8.8X] ",tk); appendStr(out,ERRORMSG(str)); return(asString(out)); } @@ -851,7 +851,7 @@ const char* PrettyPrintClass( if(g_fDumpTokens) { char tmp[16]; - sprintf_s(tmp,COUNTOF(tmp),"/*%08X*/",tk); + sprintf_s(tmp,ARRAY_SIZE(tmp),"/*%08X*/",tk); appendStr(out,COMMENT(tmp)); } } @@ -880,7 +880,7 @@ const char* PrettyPrintClass( if(g_fDumpTokens) { char tmp[16]; - sprintf_s(tmp,COUNTOF(tmp),"/*%08X*/",tk); + sprintf_s(tmp,ARRAY_SIZE(tmp),"/*%08X*/",tk); appendStr(out,COMMENT(tmp)); } appendChar(out, ']'); @@ -901,7 +901,7 @@ const char* PrettyPrintClass( if(g_fDumpTokens) { char tmp[16]; - sprintf_s(tmp,COUNTOF(tmp),"/* %08X */",tk); + sprintf_s(tmp,ARRAY_SIZE(tmp),"/* %08X */",tk); appendStr(out,COMMENT(tmp)); } appendChar(out, ']'); @@ -923,7 +923,7 @@ const char* PrettyPrintClass( if(g_fDumpTokens) { char tmp[16]; - sprintf_s(tmp,COUNTOF(tmp),"/*%08X*/",tk); + sprintf_s(tmp,ARRAY_SIZE(tmp),"/*%08X*/",tk); appendStr(out,COMMENT(tmp)); } appendChar(out, ']'); @@ -951,7 +951,7 @@ const char* PrettyPrintClass( if (FAILED(pIMDI->GetSigFromToken(tk, &cSig, &sig))) { char tmp[64]; - sprintf_s(tmp, COUNTOF(tmp), "/*Invalid %08X record*/", tk); + sprintf_s(tmp, ARRAY_SIZE(tmp), "/*Invalid %08X record*/", tk); appendStr(out, COMMENT(tmp)); } else @@ -962,7 +962,7 @@ const char* PrettyPrintClass( if(g_fDumpTokens) { char tmp[16]; - sprintf_s(tmp,COUNTOF(tmp),"/*%08X*/",tk); + sprintf_s(tmp,ARRAY_SIZE(tmp),"/*%08X*/",tk); appendStr(out,COMMENT(tmp)); } } @@ -974,7 +974,7 @@ const char* PrettyPrintClass( default: { char str[128]; - sprintf_s(str,COUNTOF(str)," [ERROR: INVALID TOKEN TYPE 0x%8.8X] ",tk); + sprintf_s(str,ARRAY_SIZE(str)," [ERROR: INVALID TOKEN TYPE 0x%8.8X] ",tk); appendStr(out,ERRORMSG(str)); } } diff --git a/src/coreclr/inc/holder.h b/src/coreclr/inc/holder.h index 448610634a612..4ec7b106cc0e8 100644 --- a/src/coreclr/inc/holder.h +++ b/src/coreclr/inc/holder.h @@ -1152,7 +1152,14 @@ FORCEINLINE void HolderFreeLibrary(HMODULE h) { FreeLibrary(h); } typedef Wrapper, HolderFreeLibrary, NULL> HModuleHolder; template FORCEINLINE -void DoLocalFree(T* pMem) { (LocalFree)((HLOCAL)pMem); } +void DoLocalFree(T* pMem) +{ +#ifdef HOST_WINDOWS + (LocalFree)((void*)pMem); +#else + (free)((void*)pMem); +#endif +} template using LocalAllocHolder = SpecializedWrapper<_TYPE, DoLocalFree<_TYPE>>; diff --git a/src/coreclr/inc/icorjitinfoimpl_generated.h b/src/coreclr/inc/icorjitinfoimpl_generated.h index 602bfc74c1a68..21236cc92cb17 100644 --- a/src/coreclr/inc/icorjitinfoimpl_generated.h +++ b/src/coreclr/inc/icorjitinfoimpl_generated.h @@ -601,10 +601,6 @@ uint32_t getFieldThreadLocalStoreID( CORINFO_FIELD_HANDLE field, void** ppIndirection) override; -void setOverride( - ICorDynamicInfo* pOverride, - CORINFO_METHOD_HANDLE currentMethod) override; - void addActiveDependency( CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo) override; diff --git a/src/coreclr/inc/jiteeversionguid.h b/src/coreclr/inc/jiteeversionguid.h index 8b6285020afb8..e7b8884419e5a 100644 --- a/src/coreclr/inc/jiteeversionguid.h +++ b/src/coreclr/inc/jiteeversionguid.h @@ -43,11 +43,11 @@ typedef const GUID *LPCGUID; #define GUID_DEFINED #endif // !GUID_DEFINED -constexpr GUID JITEEVersionIdentifier = { /* 1d61ee87-b3be-48ae-a12e-2fb9b5b1cee7 */ - 0x1d61ee87, - 0xb3be, - 0x48ae, - {0xa1, 0x2e, 0x2f, 0xb9, 0xb5, 0xb1, 0xce, 0xe7} +constexpr GUID JITEEVersionIdentifier = { /* 323185e9-208a-4b35-a413-23f9aac2d5f7 */ + 0x323185e9, + 0x208a, + 0x4b35, + {0xa4, 0x13, 0x23, 0xf9, 0xaa, 0xc2, 0xd5, 0xf7} }; ////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/src/coreclr/inc/switches.h b/src/coreclr/inc/switches.h index 9e066527a8bde..65cda94ed9900 100644 --- a/src/coreclr/inc/switches.h +++ b/src/coreclr/inc/switches.h @@ -51,7 +51,7 @@ #if defined(TARGET_X86) || defined(TARGET_ARM) #define USE_LAZY_PREFERRED_RANGE 0 -#elif defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_S390X) +#elif defined(TARGET_AMD64) || defined(TARGET_ARM64) || defined(TARGET_S390X) || defined(TARGET_LOONGARCH64) #if defined(HOST_UNIX) // In PAL we have a smechanism that reserves memory on start up that is diff --git a/src/coreclr/inc/vptr_list.h b/src/coreclr/inc/vptr_list.h index 0fde8090d0699..ad17ef35a3b60 100644 --- a/src/coreclr/inc/vptr_list.h +++ b/src/coreclr/inc/vptr_list.h @@ -85,9 +85,6 @@ VPTR_CLASS(ExternalMethodFrame) #ifdef FEATURE_READYTORUN VPTR_CLASS(DynamicHelperFrame) #endif -#if defined(TARGET_X86) -VPTR_CLASS(UMThkCallFrame) -#endif #if defined(TARGET_X86) && !defined(UNIX_X86_ABI) VPTR_CLASS(TailCallFrame) #endif diff --git a/src/coreclr/jit/ICorJitInfo_API_names.h b/src/coreclr/jit/ICorJitInfo_API_names.h index d373091453220..36a7f89f4718c 100644 --- a/src/coreclr/jit/ICorJitInfo_API_names.h +++ b/src/coreclr/jit/ICorJitInfo_API_names.h @@ -152,7 +152,6 @@ DEF_CLR_API(canGetVarArgsHandle) DEF_CLR_API(constructStringLiteral) DEF_CLR_API(emptyStringLiteral) DEF_CLR_API(getFieldThreadLocalStoreID) -DEF_CLR_API(setOverride) DEF_CLR_API(addActiveDependency) DEF_CLR_API(GetDelegateCtor) DEF_CLR_API(MethodCompileComplete) diff --git a/src/coreclr/jit/ICorJitInfo_API_wrapper.hpp b/src/coreclr/jit/ICorJitInfo_API_wrapper.hpp index 1e2627ccb3c9a..6de2cf03a26b1 100644 --- a/src/coreclr/jit/ICorJitInfo_API_wrapper.hpp +++ b/src/coreclr/jit/ICorJitInfo_API_wrapper.hpp @@ -1448,15 +1448,6 @@ uint32_t WrapICorJitInfo::getFieldThreadLocalStoreID( return temp; } -void WrapICorJitInfo::setOverride( - ICorDynamicInfo* pOverride, - CORINFO_METHOD_HANDLE currentMethod) -{ - API_ENTER(setOverride); - wrapHnd->setOverride(pOverride, currentMethod); - API_LEAVE(setOverride); -} - void WrapICorJitInfo::addActiveDependency( CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo) diff --git a/src/coreclr/jit/assertionprop.cpp b/src/coreclr/jit/assertionprop.cpp index 71d2dc688968e..51fad24772b47 100644 --- a/src/coreclr/jit/assertionprop.cpp +++ b/src/coreclr/jit/assertionprop.cpp @@ -2189,7 +2189,7 @@ AssertionIndex Compiler::optCreateJtrueAssertions(GenTree* op1 AssertionInfo Compiler::optCreateJTrueBoundsAssertion(GenTree* tree) { GenTree* relop = tree->gtGetOp1(); - if ((relop->OperKind() & GTK_RELOP) == 0) + if (!relop->OperIsCompare()) { return NO_ASSERTION_INDEX; } @@ -2349,7 +2349,7 @@ AssertionInfo Compiler::optAssertionGenJtrue(GenTree* tree) } GenTree* relop = tree->AsOp()->gtOp1; - if ((relop->OperKind() & GTK_RELOP) == 0) + if (!relop->OperIsCompare()) { return NO_ASSERTION_INDEX; } @@ -2392,8 +2392,7 @@ AssertionInfo Compiler::optAssertionGenJtrue(GenTree* tree) ValueNum op1VN = vnStore->VNConservativeNormalValue(op1->gtVNPair); ValueNum op2VN = vnStore->VNConservativeNormalValue(op2->gtVNPair); // If op1 is lcl and op2 is const or lcl, create assertion. - if ((op1->gtOper == GT_LCL_VAR) && - ((op2->OperKind() & GTK_CONST) || (op2->gtOper == GT_LCL_VAR))) // Fix for Dev10 851483 + if ((op1->gtOper == GT_LCL_VAR) && (op2->OperIsConst() || (op2->gtOper == GT_LCL_VAR))) // Fix for Dev10 851483 { return optCreateJtrueAssertions(op1, op2, assertionKind); } @@ -2599,6 +2598,13 @@ void Compiler::optAssertionGen(GenTree* tree) assertionInfo = optCreateAssertion(tree->AsIndir()->Addr(), nullptr, OAK_NOT_EQUAL); break; + case GT_INTRINSIC: + if (tree->AsIntrinsic()->gtIntrinsicName == NI_System_Object_GetType) + { + assertionInfo = optCreateAssertion(tree->AsIntrinsic()->gtGetOp1(), nullptr, OAK_NOT_EQUAL); + } + break; + case GT_BOUNDS_CHECK: if (!optLocalAssertionProp) { @@ -3601,7 +3607,7 @@ AssertionIndex Compiler::optGlobalAssertionIsEqualOrNotEqualZero(ASSERT_VALARG_T GenTree* Compiler::optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, Statement* stmt) { - assert(tree->OperKind() & GTK_RELOP); + assert(tree->OperIsCompare()); if (!optLocalAssertionProp) { diff --git a/src/coreclr/jit/block.h b/src/coreclr/jit/block.h index c5996ac8239d7..81a511f4bceed 100644 --- a/src/coreclr/jit/block.h +++ b/src/coreclr/jit/block.h @@ -825,6 +825,17 @@ struct BasicBlock : private LIR::Range BBswtDesc* bbJumpSwt; // switch descriptor }; + bool KindIs(BBjumpKinds kind) const + { + return bbJumpKind == kind; + } + + template + bool KindIs(BBjumpKinds kind, T... rest) const + { + return KindIs(kind) || KindIs(rest...); + } + // NumSucc() gives the number of successors, and GetSucc() returns a given numbered successor. // // There are two versions of these functions: ones that take a Compiler* and ones that don't. You must diff --git a/src/coreclr/jit/codegenarm64.cpp b/src/coreclr/jit/codegenarm64.cpp index 250a23904944a..abcd70d040f0b 100644 --- a/src/coreclr/jit/codegenarm64.cpp +++ b/src/coreclr/jit/codegenarm64.cpp @@ -6922,9 +6922,12 @@ void CodeGen::genArm64EmitterUnitTests() #ifdef ALL_ARM64_EMITTER_UNIT_TESTS // - // R_R fmov/fcmp/fcvt + // R_R cmeq/fmov/fcmp/fcvt // + // cmeq scalar + theEmitter->emitIns_R_R(INS_cmeq, EA_8BYTE, REG_V0, REG_V1); + // fmov to vector to vector theEmitter->emitIns_Mov(INS_fmov, EA_8BYTE, REG_V0, REG_V2, /* canSkip */ false); theEmitter->emitIns_Mov(INS_fmov, EA_4BYTE, REG_V1, REG_V3, /* canSkip */ false); diff --git a/src/coreclr/jit/codegenarmarch.cpp b/src/coreclr/jit/codegenarmarch.cpp index 227de58aedc97..66ecbac761cb5 100644 --- a/src/coreclr/jit/codegenarmarch.cpp +++ b/src/coreclr/jit/codegenarmarch.cpp @@ -2840,8 +2840,8 @@ void CodeGen::genCodeForCpBlkUnroll(GenTreeBlk* node) // When both addresses are not 16-byte aligned the CopyBlock instruction sequence starts with padding // str instruction. For example, when both addresses are 8-byte aligned the instruction sequence looks like // - // ldr D_simdReg1, [srcReg, #srcOffset] - // str D_simdReg1, [dstReg, #dstOffset] + // ldr X_intReg1, [srcReg, #srcOffset] + // str X_intReg1, [dstReg, #dstOffset] // ldp Q_simdReg1, Q_simdReg2, [srcReg, #srcOffset+8] // stp Q_simdReg1, Q_simdReg2, [dstReg, #dstOffset+8] // ldp Q_simdReg1, Q_simdReg2, [srcReg, #srcOffset+40] @@ -2853,7 +2853,7 @@ void CodeGen::genCodeForCpBlkUnroll(GenTreeBlk* node) // be profitable). const bool canUse16ByteWideInstrs = isSrcRegAddrAlignmentKnown && isDstRegAddrAlignmentKnown && - (size >= FP_REGSIZE_BYTES) && (srcRegAddrAlignment == dstRegAddrAlignment); + (size >= 2 * FP_REGSIZE_BYTES) && (srcRegAddrAlignment == dstRegAddrAlignment); bool shouldUse16ByteWideInstrs = false; @@ -2876,8 +2876,7 @@ void CodeGen::genCodeForCpBlkUnroll(GenTreeBlk* node) { // In order to use 16-byte instructions the JIT needs to adjust either srcOffset or dstOffset. // The JIT should use 16-byte loads and stores when the resulting sequence (incl. an additional add - // instruction) - // has fewer number of instructions. + // instruction) has fewer number of instructions. if (helper.InstructionCount(FP_REGSIZE_BYTES) + 1 < helper.InstructionCount(REGSIZE_BYTES)) { @@ -2937,51 +2936,31 @@ void CodeGen::genCodeForCpBlkUnroll(GenTreeBlk* node) const unsigned intRegCount = node->AvailableTempRegCount(RBM_ALLINT); - switch (intRegCount) + if (intRegCount >= 2) { - case 1: - intReg1 = node->GetSingleTempReg(RBM_ALLINT); - break; - case 2: - intReg1 = node->ExtractTempReg(RBM_ALLINT); - intReg2 = node->GetSingleTempReg(RBM_ALLINT); - break; - default: - break; + intReg1 = node->ExtractTempReg(RBM_ALLINT); + intReg2 = node->ExtractTempReg(RBM_ALLINT); } - - regNumber simdReg1 = REG_NA; - regNumber simdReg2 = REG_NA; - - const unsigned simdRegCount = node->AvailableTempRegCount(RBM_ALLFLOAT); - - switch (simdRegCount) + else if (intRegCount == 1) { - case 1: - simdReg1 = node->GetSingleTempReg(RBM_ALLFLOAT); - break; - case 2: - simdReg1 = node->ExtractTempReg(RBM_ALLFLOAT); - simdReg2 = node->GetSingleTempReg(RBM_ALLFLOAT); - break; - default: - break; + intReg1 = node->GetSingleTempReg(RBM_ALLINT); + intReg2 = rsGetRsvdReg(); + } + else + { + intReg1 = rsGetRsvdReg(); } if (shouldUse16ByteWideInstrs) { + const regNumber simdReg1 = node->ExtractTempReg(RBM_ALLFLOAT); + const regNumber simdReg2 = node->GetSingleTempReg(RBM_ALLFLOAT); + helper.Unroll(FP_REGSIZE_BYTES, intReg1, simdReg1, simdReg2, srcReg, dstReg, GetEmitter()); } else { - if (intReg2 == REG_NA) - { - helper.Unroll(REGSIZE_BYTES, intReg1, simdReg1, simdReg2, srcReg, dstReg, GetEmitter()); - } - else - { - helper.UnrollBaseInstrs(intReg1, intReg2, srcReg, dstReg, GetEmitter()); - } + helper.UnrollBaseInstrs(intReg1, intReg2, srcReg, dstReg, GetEmitter()); } #endif // TARGET_ARM64 diff --git a/src/coreclr/jit/codegencommon.cpp b/src/coreclr/jit/codegencommon.cpp index 0c479168f4fee..1c9eda6f63afc 100644 --- a/src/coreclr/jit/codegencommon.cpp +++ b/src/coreclr/jit/codegencommon.cpp @@ -1362,9 +1362,10 @@ bool CodeGen::genCreateAddrMode( assert(mul == 0); - /* Special case: keep constants as 'op2' */ + /* Special case: keep constants as 'op2', but don't do this for constant handles + because they don't fit I32 that we're going to check for below anyway. */ - if (op1->IsCnsIntOrI()) + if (op1->IsCnsIntOrI() && !op1->IsIconHandle()) { // Presumably op2 is assumed to not be a constant (shouldn't happen if we've done constant folding)? tmp = op1; @@ -6235,15 +6236,9 @@ void CodeGen::genEnregisterOSRArgsAndLocals() // This local was part of the live tier0 state and is enregistered in the // OSR method. Initialize the register from the right frame slot. // - // We currently don't expect to see enregistered multi-reg args in OSR methods, - // as struct promotion is disabled. So any struct arg just uses the location - // on the tier0 frame. - // // If we ever enable promotion we'll need to generalize what follows to copy each // field from the tier0 frame to its OSR home. // - assert(!varDsc->lvIsMultiRegArg); - if (!VarSetOps::IsMember(compiler, compiler->fgFirstBB->bbLiveIn, varDsc->lvVarIndex)) { // This arg or local is not live at entry to the OSR method. @@ -7542,6 +7537,16 @@ void CodeGen::genFnProlog() #endif // PROFILING_SUPPORTED + // For OSR we may have a zero-length prolog. That's not supported + // when the method must report a generics context,/ so add a nop if so. + // + if (compiler->opts.IsOSR() && (GetEmitter()->emitGetPrologOffsetEstimate() == 0) && + (compiler->lvaReportParamTypeArg() || compiler->lvaKeepAliveAndReportThis())) + { + JITDUMP("OSR: prolog was zero length and has generic context to report: adding nop to pad prolog.\n"); + instGen(INS_nop); + } + if (!GetInterruptible()) { // The 'real' prolog ends here for non-interruptible methods. diff --git a/src/coreclr/jit/codegenlinear.cpp b/src/coreclr/jit/codegenlinear.cpp index 51e9afc074398..ff4e0b2d3c285 100644 --- a/src/coreclr/jit/codegenlinear.cpp +++ b/src/coreclr/jit/codegenlinear.cpp @@ -1657,7 +1657,7 @@ void CodeGen::genConsumeRegs(GenTree* tree) #ifdef FEATURE_SIMD // (In)Equality operation that produces bool result, when compared // against Vector zero, marks its Vector Zero operand as contained. - assert(tree->OperIsLeaf() || tree->IsSIMDZero()); + assert(tree->OperIsLeaf() || tree->IsSIMDZero() || tree->IsVectorZero()); #else assert(tree->OperIsLeaf()); #endif diff --git a/src/coreclr/jit/compiler.cpp b/src/coreclr/jit/compiler.cpp index 394aca1719aeb..56701ceb08fad 100644 --- a/src/coreclr/jit/compiler.cpp +++ b/src/coreclr/jit/compiler.cpp @@ -2240,169 +2240,27 @@ void Compiler::compSetProcessor() #endif // TARGET_X86 - // The VM will set the ISA flags depending on actual hardware support. - // We then select which ISAs to leave enabled based on the JIT config. - // The exception to this is the dummy Vector64/128/256 ISAs, which must be added explicitly. - CORINFO_InstructionSetFlags instructionSetFlags = jitFlags.GetInstructionSetFlags(); - opts.compSupportsISA = 0; - opts.compSupportsISAReported = 0; - opts.compSupportsISAExactly = 0; - -#ifdef TARGET_XARCH - if (JitConfig.EnableHWIntrinsic()) - { - // Dummy ISAs for simplifying the JIT code - instructionSetFlags.AddInstructionSet(InstructionSet_Vector128); - instructionSetFlags.AddInstructionSet(InstructionSet_Vector256); - } - - if (!JitConfig.EnableSSE()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE); -#ifdef TARGET_AMD64 - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE_X64); -#endif - } - - if (!JitConfig.EnableSSE2()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE2); -#ifdef TARGET_AMD64 - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE2_X64); -#endif - } - - if (!JitConfig.EnableAES()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_AES); - } - - if (!JitConfig.EnablePCLMULQDQ()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_PCLMULQDQ); - } - - // We need to additionally check that COMPlus_EnableSSE3_4 is set, as that - // is a prexisting config flag that controls the SSE3+ ISAs - if (!JitConfig.EnableSSE3() || !JitConfig.EnableSSE3_4()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE3); - } - - if (!JitConfig.EnableSSSE3()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSSE3); - } - - if (!JitConfig.EnableSSE41()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE41); -#ifdef TARGET_AMD64 - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE41_X64); -#endif - } - - if (!JitConfig.EnableSSE42()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE42); -#ifdef TARGET_AMD64 - instructionSetFlags.RemoveInstructionSet(InstructionSet_SSE42_X64); -#endif - } - - if (!JitConfig.EnablePOPCNT()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_POPCNT); -#ifdef TARGET_AMD64 - instructionSetFlags.RemoveInstructionSet(InstructionSet_POPCNT_X64); -#endif - } - - if (!JitConfig.EnableAVX()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_AVX); - } - - if (!JitConfig.EnableFMA()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_FMA); - } - - if (!JitConfig.EnableAVX2()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_AVX2); - } + // The VM will set the ISA flags depending on actual hardware support + // and any specified config switches specified by the user. The exception + // here is for certain "artificial ISAs" such as Vector64/128/256 where they + // don't actually exist. The JIT is in charge of adding those and ensuring + // the total sum of flags is still valid. - if (!JitConfig.EnableAVXVNNI()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_AVXVNNI); - } - - if (!JitConfig.EnableLZCNT()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_LZCNT); -#ifdef TARGET_AMD64 - instructionSetFlags.RemoveInstructionSet(InstructionSet_LZCNT_X64); -#endif // TARGET_AMD64 - } - - if (!JitConfig.EnableBMI1()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_BMI1); -#ifdef TARGET_AMD64 - instructionSetFlags.RemoveInstructionSet(InstructionSet_BMI1_X64); -#endif // TARGET_AMD64 - } + CORINFO_InstructionSetFlags instructionSetFlags = jitFlags.GetInstructionSetFlags(); - if (!JitConfig.EnableBMI2()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_BMI2); -#ifdef TARGET_AMD64 - instructionSetFlags.RemoveInstructionSet(InstructionSet_BMI2_X64); -#endif // TARGET_AMD64 - } + opts.compSupportsISA = 0; + opts.compSupportsISAReported = 0; + opts.compSupportsISAExactly = 0; +#if defined(TARGET_XARCH) + instructionSetFlags.AddInstructionSet(InstructionSet_Vector128); + instructionSetFlags.AddInstructionSet(InstructionSet_Vector256); #endif // TARGET_XARCH -#if defined(TARGET_ARM64) - if (JitConfig.EnableHWIntrinsic()) - { - // Dummy ISAs for simplifying the JIT code - instructionSetFlags.AddInstructionSet(InstructionSet_Vector64); - instructionSetFlags.AddInstructionSet(InstructionSet_Vector128); - } - if (!JitConfig.EnableArm64Aes()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_Aes); - } - - if (!JitConfig.EnableArm64Atomics()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_Atomics); - } - - if (!JitConfig.EnableArm64Crc32()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_Crc32); - instructionSetFlags.RemoveInstructionSet(InstructionSet_Crc32_Arm64); - } - - if (!JitConfig.EnableArm64Sha1()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_Sha1); - } - - if (!JitConfig.EnableArm64Sha256()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_Sha256); - } - - if (!JitConfig.EnableArm64AdvSimd()) - { - instructionSetFlags.RemoveInstructionSet(InstructionSet_AdvSimd); - instructionSetFlags.RemoveInstructionSet(InstructionSet_AdvSimd_Arm64); - } -#endif +#if defined(TARGET_ARM64) + instructionSetFlags.AddInstructionSet(InstructionSet_Vector64); + instructionSetFlags.AddInstructionSet(InstructionSet_Vector128); +#endif // TARGET_ARM64 instructionSetFlags = EnsureInstructionSetFlagsAreValid(instructionSetFlags); opts.setSupportedISAs(instructionSetFlags); @@ -2786,15 +2644,19 @@ void Compiler::compInitOptions(JitFlags* jitFlags) verboseDump = (JitConfig.JitDumpTier0() > 0); } - // Optionally suppress dumping some OSR jit requests. + // Optionally suppress dumping except for a specific OSR jit request. // - if (verboseDump && jitFlags->IsSet(JitFlags::JIT_FLAG_OSR)) - { - const int desiredOffset = JitConfig.JitDumpAtOSROffset(); + const int dumpAtOSROffset = JitConfig.JitDumpAtOSROffset(); - if (desiredOffset != -1) + if (verboseDump && (dumpAtOSROffset != -1)) + { + if (jitFlags->IsSet(JitFlags::JIT_FLAG_OSR)) + { + verboseDump = (((IL_OFFSET)dumpAtOSROffset) == info.compILEntry); + } + else { - verboseDump = (((IL_OFFSET)desiredOffset) == info.compILEntry); + verboseDump = false; } } diff --git a/src/coreclr/jit/compiler.h b/src/coreclr/jit/compiler.h index 1ba86f6da9d16..d5dcf4cd92c81 100644 --- a/src/coreclr/jit/compiler.h +++ b/src/coreclr/jit/compiler.h @@ -1735,7 +1735,7 @@ struct fgArgTabEntry // In this case, it must be removed by GenTreeCall::ResetArgInfo. bool isNonStandardArgAddedLate() const { - switch (nonStandardArgKind) + switch (static_cast(nonStandardArgKind)) { case NonStandardArgKind::None: case NonStandardArgKind::PInvokeFrame: @@ -3300,6 +3300,9 @@ class Compiler GenTree* gtNewSimdSqrtNode( var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic); + GenTree* gtNewSimdSumNode( + var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic); + GenTree* gtNewSimdUnOpNode(genTreeOps op, var_types type, GenTree* op1, @@ -3346,7 +3349,7 @@ class Compiler GenTreeLclFld* gtNewLclFldNode(unsigned lnum, var_types type, unsigned offset); GenTree* gtNewInlineCandidateReturnExpr(GenTree* inlineCandidate, var_types type, BasicBlockFlags bbFlags); - GenTree* gtNewFieldRef(var_types typ, CORINFO_FIELD_HANDLE fldHnd, GenTree* obj = nullptr, DWORD offset = 0); + GenTree* gtNewFieldRef(var_types type, CORINFO_FIELD_HANDLE fldHnd, GenTree* obj = nullptr, DWORD offset = 0); GenTree* gtNewIndexRef(var_types typ, GenTree* arrayOp, GenTree* indexOp); @@ -6728,6 +6731,12 @@ class Compiler CALLINT_ALL, // kills everything (normal method call) }; + enum class FieldKindForVN + { + SimpleStatic, + WithBaseAddr + }; + public: // A "LoopDsc" describes a ("natural") loop. We (currently) require the body of a loop to be a contiguous (in // bbNext order) sequence of basic blocks. (At times, we may require the blocks in a loop to be "properly numbered" @@ -6782,9 +6791,9 @@ class Compiler int lpLoopVarFPCount; // The register count for the FP LclVars that are read/written inside this loop int lpVarInOutFPCount; // The register count for the FP LclVars that are alive inside or across this loop - typedef JitHashTable, bool> FieldHandleSet; - FieldHandleSet* lpFieldsModified; // This has entries (mappings to "true") for all static field and object - // instance fields modified + typedef JitHashTable, FieldKindForVN> + FieldHandleSet; + FieldHandleSet* lpFieldsModified; // This has entries for all static field and object instance fields modified // in the loop. typedef JitHashTable, bool> ClassHandleSet; @@ -6795,7 +6804,7 @@ class Compiler // Adds the variable liveness information for 'blk' to 'this' LoopDsc void AddVariableLiveness(Compiler* comp, BasicBlock* blk); - inline void AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd); + inline void AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd, FieldKindForVN fieldKind); // This doesn't *always* take a class handle -- it can also take primitive types, encoded as class handles // (shifted left, with a low-order bit set to distinguish.) // Use the {Encode/Decode}ElemType methods to construct/destruct these. @@ -7042,7 +7051,7 @@ class Compiler void AddVariableLivenessAllContainingLoops(unsigned lnum, BasicBlock* blk); // Adds "fldHnd" to the set of modified fields of "lnum" and any parent loops. - void AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd); + void AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd, FieldKindForVN fieldKind); // Adds "elemType" to the set of modified array element types of "lnum" and any parent loops. void AddModifiedElemTypeAllContainingLoops(unsigned lnum, CORINFO_CLASS_HANDLE elemType); @@ -8686,7 +8695,7 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #error Unsupported platform #endif // !TARGET_XARCH && !TARGET_ARM64 - return compOpportunisticallyDependsOn(minimumIsa) && JitConfig.EnableHWIntrinsic(); + return compOpportunisticallyDependsOn(minimumIsa); #else return false; #endif @@ -8704,7 +8713,7 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #error Unsupported platform #endif // !TARGET_XARCH && !TARGET_ARM64 - return compIsaSupportedDebugOnly(minimumIsa) && JitConfig.EnableHWIntrinsic(); + return compIsaSupportedDebugOnly(minimumIsa); #else return false; #endif // FEATURE_SIMD @@ -9111,7 +9120,7 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #if defined(TARGET_XARCH) if (getSIMDSupportLevel() == SIMD_AVX2_Supported) { - return JitConfig.EnableHWIntrinsic() ? TYP_SIMD32 : TYP_SIMD16; + return TYP_SIMD32; } else { @@ -9152,14 +9161,13 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #if defined(TARGET_XARCH) if (getSIMDSupportLevel() == SIMD_AVX2_Supported) { - return JitConfig.EnableHWIntrinsic() ? YMM_REGSIZE_BYTES : XMM_REGSIZE_BYTES; + return YMM_REGSIZE_BYTES; } else { - assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported); - // Verify and record that AVX2 isn't supported compVerifyInstructionSetUnusable(InstructionSet_AVX2); + assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported); return XMM_REGSIZE_BYTES; } #elif defined(TARGET_ARM64) @@ -9182,10 +9190,12 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #if defined(FEATURE_HW_INTRINSICS) && defined(TARGET_XARCH) if (compOpportunisticallyDependsOn(InstructionSet_AVX)) { - return JitConfig.EnableHWIntrinsic() ? YMM_REGSIZE_BYTES : XMM_REGSIZE_BYTES; + return YMM_REGSIZE_BYTES; } else { + // Verify and record that AVX2 isn't supported + compVerifyInstructionSetUnusable(InstructionSet_AVX2); assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported); return XMM_REGSIZE_BYTES; } diff --git a/src/coreclr/jit/compiler.hpp b/src/coreclr/jit/compiler.hpp index 8f2d8059cc4ca..2379c0e0ac6ac 100644 --- a/src/coreclr/jit/compiler.hpp +++ b/src/coreclr/jit/compiler.hpp @@ -1078,45 +1078,57 @@ inline GenTree* Compiler::gtNewRuntimeLookup(CORINFO_GENERIC_HANDLE hnd, CorInfo return node; } -/***************************************************************************** - * - * A little helper to create a data member reference node. - */ - -inline GenTree* Compiler::gtNewFieldRef(var_types typ, CORINFO_FIELD_HANDLE fldHnd, GenTree* obj, DWORD offset) +//------------------------------------------------------------------------ +// gtNewFieldRef: a helper for creating GT_FIELD nodes. +// +// Normalizes struct types (for SIMD vectors). Sets GTF_GLOB_REF for fields +// that may be pointing into globally visible memory. +// +// Arguments: +// type - type for the field node +// fldHnd - the field handle +// obj - the instance, an address +// offset - the field offset +// +// Return Value: +// The created node. +// +inline GenTree* Compiler::gtNewFieldRef(var_types type, CORINFO_FIELD_HANDLE fldHnd, GenTree* obj, DWORD offset) { - /* 'GT_FIELD' nodes may later get transformed into 'GT_IND' */ + // GT_FIELD nodes are transformed into GT_IND nodes. assert(GenTree::s_gtNodeSizes[GT_IND] <= GenTree::s_gtNodeSizes[GT_FIELD]); - if (typ == TYP_STRUCT) + if (type == TYP_STRUCT) { - CORINFO_CLASS_HANDLE fieldClass; - (void)info.compCompHnd->getFieldType(fldHnd, &fieldClass); - typ = impNormStructType(fieldClass); + CORINFO_CLASS_HANDLE structHnd; + eeGetFieldType(fldHnd, &structHnd); + type = impNormStructType(structHnd); } - GenTree* tree = new (this, GT_FIELD) GenTreeField(typ, obj, fldHnd, offset); + + GenTree* fieldNode = new (this, GT_FIELD) GenTreeField(type, obj, fldHnd, offset); // If "obj" is the address of a local, note that a field of that struct local has been accessed. - if (obj != nullptr && obj->OperGet() == GT_ADDR && varTypeIsStruct(obj->AsOp()->gtOp1) && - obj->AsOp()->gtOp1->OperGet() == GT_LCL_VAR) + if ((obj != nullptr) && obj->OperIs(GT_ADDR) && varTypeIsStruct(obj->AsUnOp()->gtOp1) && + obj->AsUnOp()->gtOp1->OperIs(GT_LCL_VAR)) { - unsigned lclNum = obj->AsOp()->gtOp1->AsLclVarCommon()->GetLclNum(); - lvaTable[lclNum].lvFieldAccessed = 1; + LclVarDsc* varDsc = lvaGetDesc(obj->AsUnOp()->gtOp1->AsLclVarCommon()); + + varDsc->lvFieldAccessed = 1; #if defined(TARGET_AMD64) || defined(TARGET_ARM64) // These structs are passed by reference; we should probably be able to treat these // as non-global refs, but downstream logic expects these to be marked this way. - if (lvaTable[lclNum].lvIsParam) + if (varDsc->lvIsParam) { - tree->gtFlags |= GTF_GLOB_REF; + fieldNode->gtFlags |= GTF_GLOB_REF; } #endif // defined(TARGET_AMD64) || defined(TARGET_ARM64) } else { - tree->gtFlags |= GTF_GLOB_REF; + fieldNode->gtFlags |= GTF_GLOB_REF; } - return tree; + return fieldNode; } /***************************************************************************** @@ -3334,14 +3346,14 @@ inline void Compiler::optAssertionRemove(AssertionIndex index) } } -inline void Compiler::LoopDsc::AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd) +inline void Compiler::LoopDsc::AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd, FieldKindForVN fieldKind) { if (lpFieldsModified == nullptr) { lpFieldsModified = new (comp->getAllocatorLoopHoist()) Compiler::LoopDsc::FieldHandleSet(comp->getAllocatorLoopHoist()); } - lpFieldsModified->Set(fldHnd, true, FieldHandleSet::Overwrite); + lpFieldsModified->Set(fldHnd, fieldKind, FieldHandleSet::Overwrite); } inline void Compiler::LoopDsc::AddModifiedElemType(Compiler* comp, CORINFO_CLASS_HANDLE structHnd) @@ -4504,11 +4516,12 @@ inline static bool StructHasNoPromotionFlagSet(DWORD attribs) return ((attribs & CORINFO_FLG_DONT_PROMOTE) != 0); } -/***************************************************************************** - * This node should not be referenced by anyone now. Set its values to garbage - * to catch extra references - */ - +//------------------------------------------------------------------------------ +// DEBUG_DESTROY_NODE: sets value of tree to garbage to catch extra references +// +// Arguments: +// tree: This node should not be referenced by anyone now +// inline void DEBUG_DESTROY_NODE(GenTree* tree) { #ifdef DEBUG @@ -4529,6 +4542,19 @@ inline void DEBUG_DESTROY_NODE(GenTree* tree) #endif } +//------------------------------------------------------------------------------ +// DEBUG_DESTROY_NODE: sets value of trees to garbage to catch extra references +// +// Arguments: +// tree, ...rest: These nodes should not be referenced by anyone now +// +template +void DEBUG_DESTROY_NODE(GenTree* tree, T... rest) +{ + DEBUG_DESTROY_NODE(tree); + DEBUG_DESTROY_NODE(rest...); +} + //------------------------------------------------------------------------------ // lvRefCnt: access reference count for this local var // diff --git a/src/coreclr/jit/ee_il_dll.cpp b/src/coreclr/jit/ee_il_dll.cpp index ebf1ea2945195..2ec2c71f85953 100644 --- a/src/coreclr/jit/ee_il_dll.cpp +++ b/src/coreclr/jit/ee_il_dll.cpp @@ -335,20 +335,11 @@ unsigned CILJit::getMaxIntrinsicSIMDVectorLength(CORJIT_FLAGS cpuCompileFlags) if (!jitFlags.IsSet(JitFlags::JIT_FLAG_PREJIT) && jitFlags.IsSet(JitFlags::JIT_FLAG_FEATURE_SIMD) && jitFlags.GetInstructionSetFlags().HasInstructionSet(InstructionSet_AVX2)) { - // Since the ISAs can be disabled individually and since they are hierarchical in nature (that is - // disabling SSE also disables SSE2 through AVX2), we need to check each ISA in the hierarchy to - // ensure that AVX2 is actually supported. Otherwise, we will end up getting asserts downstream. - if ((JitConfig.EnableAVX2() != 0) && (JitConfig.EnableAVX() != 0) && (JitConfig.EnableSSE42() != 0) && - (JitConfig.EnableSSE41() != 0) && (JitConfig.EnableSSSE3() != 0) && (JitConfig.EnableSSE3_4() != 0) && - (JitConfig.EnableSSE3() != 0) && (JitConfig.EnableSSE2() != 0) && (JitConfig.EnableSSE() != 0) && - (JitConfig.EnableHWIntrinsic() != 0)) + if (GetJitTls() != nullptr && JitTls::GetCompiler() != nullptr) { - if (GetJitTls() != nullptr && JitTls::GetCompiler() != nullptr) - { - JITDUMP("getMaxIntrinsicSIMDVectorLength: returning 32\n"); - } - return 32; + JITDUMP("getMaxIntrinsicSIMDVectorLength: returning 32\n"); } + return 32; } #endif // defined(TARGET_XARCH) if (GetJitTls() != nullptr && JitTls::GetCompiler() != nullptr) diff --git a/src/coreclr/jit/emit.h b/src/coreclr/jit/emit.h index 47daad7798fc2..bee6a159e0042 100644 --- a/src/coreclr/jit/emit.h +++ b/src/coreclr/jit/emit.h @@ -614,6 +614,15 @@ class emitter assert((ins != INS_invalid) && (ins < INS_count)); _idIns = ins; } + bool idInsIs(instruction ins) const + { + return idIns() == ins; + } + template + bool idInsIs(instruction ins, T... rest) const + { + return idInsIs(ins) || idInsIs(rest...); + } insFormat idInsFmt() const { diff --git a/src/coreclr/jit/emitarm64.cpp b/src/coreclr/jit/emitarm64.cpp index 51e02c5c26895..52f24d4524279 100644 --- a/src/coreclr/jit/emitarm64.cpp +++ b/src/coreclr/jit/emitarm64.cpp @@ -4732,19 +4732,19 @@ void emitter::emitIns_R_R( assert(isVectorRegister(reg1)); assert(isVectorRegister(reg2)); - if (isValidVectorDatasize(size)) + if (insOptsAnyArrangement(opt)) { // Vector operation - assert(insOptsAnyArrangement(opt)); + assert(isValidVectorDatasize(size)); assert(isValidArrangement(size, opt)); elemsize = optGetElemsize(opt); fmt = IF_DV_2M; } else { - NYI("Untested"); // Scalar operation - assert(size == EA_8BYTE); // Only Double supported + assert(size == EA_8BYTE); + assert(insOptsNone(opt)); fmt = IF_DV_2L; } break; @@ -12971,6 +12971,11 @@ void emitter::emitDispIns( emitDispVectorReg(id->idReg1(), id->idInsOpt(), true); emitDispVectorReg(id->idReg2(), id->idInsOpt(), false); } + if (ins == INS_fcmeq) + { + printf(", "); + emitDispImm(0, false); + } break; case IF_DV_2P: // DV_2P ................ ......nnnnnddddd Vd Vn (aes*, sha1su1) @@ -12990,6 +12995,11 @@ void emitter::emitDispIns( emitDispVectorReg(id->idReg1(), id->idInsOpt(), true); emitDispVectorReg(id->idReg2(), id->idInsOpt(), false); } + if (ins == INS_cmeq) + { + printf(", "); + emitDispImm(0, false); + } break; case IF_DV_2N: // DV_2N .........iiiiiii ......nnnnnddddd Vd Vn imm (shift - scalar) @@ -13126,6 +13136,11 @@ void emitter::emitDispIns( emitDispReg(id->idReg1(), size, true); emitDispReg(id->idReg2(), size, false); } + if (fmt == IF_DV_2L && ins == INS_cmeq) + { + printf(", "); + emitDispImm(0, false); + } break; case IF_DV_2H: // DV_2H X........X...... ......nnnnnddddd Rd Vn (fmov, fcvtXX - to general) @@ -15614,6 +15629,11 @@ bool emitter::IsMovInstruction(instruction ins) // mov Rx, Ry # <-- last instruction // mov Ry, Rx # <-- current instruction can be omitted. // +// 4. Move that does zero extension while previous instruction already did it +// +// ldr Wx, [Ry] # <-- ldr will clear upper 4 byte of Wx +// mov Wx, Wx # <-- clears upper 4 byte in Wx +// // Arguments: // ins - The current instruction // size - Operand size of current instruction @@ -15640,6 +15660,8 @@ bool emitter::IsRedundantMov(instruction ins, emitAttr size, regNumber dst, regN return false; } + const bool isFirstInstrInBlock = (emitCurIGinsCnt == 0) && ((emitCurIG->igFlags & IGF_EXTEND) == 0); + if (dst == src) { // A mov with a EA_4BYTE has the side-effect of clearing the upper bits @@ -15655,10 +15677,18 @@ bool emitter::IsRedundantMov(instruction ins, emitAttr size, regNumber dst, regN JITDUMP("\n -- suppressing mov because src and dst is same 16-byte register.\n"); return true; } + else if (isGeneralRegisterOrSP(dst) && (size == EA_4BYTE)) + { + // See if the previous instruction already cleared upper 4 bytes for us unintentionally + if (!isFirstInstrInBlock && (emitLastIns != nullptr) && (emitLastIns->idReg1() == dst) && + (emitLastIns->idOpSize() == size) && emitLastIns->idInsIs(INS_ldr, INS_ldrh, INS_ldrb)) + { + JITDUMP("\n -- suppressing mov because ldr already cleared upper 4 bytes\n"); + return true; + } + } } - bool isFirstInstrInBlock = (emitCurIGinsCnt == 0) && ((emitCurIG->igFlags & IGF_EXTEND) == 0); - if (!isFirstInstrInBlock && // Don't optimize if instruction is not the first instruction in IG. (emitLastIns != nullptr) && (emitLastIns->idIns() == INS_mov) && // Don't optimize if last instruction was not 'mov'. diff --git a/src/coreclr/jit/emitxarch.cpp b/src/coreclr/jit/emitxarch.cpp index 40eb8d078209f..1075c4ccd97d0 100644 --- a/src/coreclr/jit/emitxarch.cpp +++ b/src/coreclr/jit/emitxarch.cpp @@ -2565,6 +2565,19 @@ UNATIVE_OFFSET emitter::emitInsSizeAM(instrDesc* id, code_t code) if (reg == REG_NA) { /* The address is of the form "[disp]" */ + CLANG_FORMAT_COMMENT_ANCHOR; + +#ifdef TARGET_X86 + // Special case: "mov eax, [disp]" and "mov [disp], eax" can use a smaller 1-byte encoding. + if ((ins == INS_mov) && (id->idReg1() == REG_EAX) && + ((id->idInsFmt() == IF_RWR_ARD) || (id->idInsFmt() == IF_AWR_RRD))) + { + // Amd64: this is one case where addr can be 64-bit in size. This is currently unused. + // If this ever changes, this code will need to be updated to add "sizeof(INT64)" to "size". + assert((size == 2) || ((size == 3) && (id->idOpSize() == EA_2BYTE))); + size--; + } +#endif size += sizeof(INT32); diff --git a/src/coreclr/jit/fgbasic.cpp b/src/coreclr/jit/fgbasic.cpp index 73695932cb543..6b41c055422b0 100644 --- a/src/coreclr/jit/fgbasic.cpp +++ b/src/coreclr/jit/fgbasic.cpp @@ -321,7 +321,7 @@ bool Compiler::fgFirstBBisScratch() // Normally, the first scratch block is a fall-through block. However, if the block after it was an empty // BBJ_ALWAYS block, it might get removed, and the code that removes it will make the first scratch block // a BBJ_ALWAYS block. - assert((fgFirstBBScratch->bbJumpKind == BBJ_NONE) || (fgFirstBBScratch->bbJumpKind == BBJ_ALWAYS)); + assert(fgFirstBBScratch->KindIs(BBJ_NONE, BBJ_ALWAYS)); return true; } @@ -1113,12 +1113,12 @@ void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, Fixed { ni = lookupNamedIntrinsic(methodHnd); - bool foldableIntrinsc = false; + bool foldableIntrinsic = false; if (IsMathIntrinsic(ni)) { // Most Math(F) intrinsics have single arguments - foldableIntrinsc = FgStack::IsConstantOrConstArg(pushedStack.Top(), impInlineInfo); + foldableIntrinsic = FgStack::IsConstantOrConstArg(pushedStack.Top(), impInlineInfo); } else { @@ -1131,7 +1131,7 @@ void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, Fixed case NI_System_GC_KeepAlive: { pushedStack.PushUnknown(); - foldableIntrinsc = true; + foldableIntrinsic = true; break; } @@ -1145,6 +1145,20 @@ void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, Fixed break; } + case NI_System_Runtime_CompilerServices_RuntimeHelpers_IsKnownConstant: + if (FgStack::IsConstArgument(pushedStack.Top(), impInlineInfo)) + { + compInlineResult->Note(InlineObservation::CALLEE_CONST_ARG_FEEDS_ISCONST); + } + else + { + compInlineResult->Note(InlineObservation::CALLEE_ARG_FEEDS_ISCONST); + } + // RuntimeHelpers.IsKnownConstant is always folded into a const + pushedStack.PushConstant(); + foldableIntrinsic = true; + break; + // These are foldable if the first argument is a constant case NI_System_Type_get_IsValueType: case NI_System_Type_GetTypeFromHandle: @@ -1159,10 +1173,10 @@ void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, Fixed case NI_Vector128_Create: #endif { - // Top() in order to keep it as is in case of foldableIntrinsc + // Top() in order to keep it as is in case of foldableIntrinsic if (FgStack::IsConstantOrConstArg(pushedStack.Top(), impInlineInfo)) { - foldableIntrinsc = true; + foldableIntrinsic = true; } break; } @@ -1177,7 +1191,7 @@ void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, Fixed if (FgStack::IsConstantOrConstArg(pushedStack.Top(0), impInlineInfo) && FgStack::IsConstantOrConstArg(pushedStack.Top(1), impInlineInfo)) { - foldableIntrinsc = true; + foldableIntrinsic = true; pushedStack.PushConstant(); } break; @@ -1186,31 +1200,31 @@ void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, Fixed case NI_IsSupported_True: case NI_IsSupported_False: { - foldableIntrinsc = true; + foldableIntrinsic = true; pushedStack.PushConstant(); break; } #if defined(TARGET_XARCH) && defined(FEATURE_HW_INTRINSICS) case NI_Vector128_get_Count: case NI_Vector256_get_Count: - foldableIntrinsc = true; + foldableIntrinsic = true; pushedStack.PushConstant(); // TODO: check if it's a loop condition - we unroll such loops. break; case NI_Vector256_get_Zero: case NI_Vector256_get_AllBitsSet: - foldableIntrinsc = true; + foldableIntrinsic = true; pushedStack.PushUnknown(); break; #elif defined(TARGET_ARM64) && defined(FEATURE_HW_INTRINSICS) case NI_Vector64_get_Count: case NI_Vector128_get_Count: - foldableIntrinsc = true; + foldableIntrinsic = true; pushedStack.PushConstant(); break; case NI_Vector128_get_Zero: case NI_Vector128_get_AllBitsSet: - foldableIntrinsc = true; + foldableIntrinsic = true; pushedStack.PushUnknown(); break; #endif @@ -1222,7 +1236,7 @@ void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, Fixed } } - if (foldableIntrinsc) + if (foldableIntrinsic) { compInlineResult->Note(InlineObservation::CALLSITE_FOLDABLE_INTRINSIC); handled = true; @@ -2407,7 +2421,7 @@ void Compiler::fgLinkBasicBlocks() /* Is the next block reachable? */ - if (curBBdesc->bbJumpKind == BBJ_ALWAYS || curBBdesc->bbJumpKind == BBJ_LEAVE) + if (curBBdesc->KindIs(BBJ_ALWAYS, BBJ_LEAVE)) { break; } @@ -4369,7 +4383,7 @@ BasicBlock* Compiler::fgSplitBlockAtBeginning(BasicBlock* curr) BasicBlock* Compiler::fgSplitEdge(BasicBlock* curr, BasicBlock* succ) { - assert(curr->bbJumpKind == BBJ_COND || curr->bbJumpKind == BBJ_SWITCH || curr->bbJumpKind == BBJ_ALWAYS); + assert(curr->KindIs(BBJ_COND, BBJ_SWITCH, BBJ_ALWAYS)); if (fgComputePredsDone) { @@ -4670,7 +4684,7 @@ void Compiler::fgRemoveBlock(BasicBlock* block, bool unreachable) } #endif // DEBUG - noway_assert(block->bbJumpKind == BBJ_NONE || block->bbJumpKind == BBJ_ALWAYS); + noway_assert(block->KindIs(BBJ_NONE, BBJ_ALWAYS)); /* Who is the "real" successor of this block? */ @@ -5182,7 +5196,7 @@ bool Compiler::fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc /* = NULL * { bool result = false; - if ((bJump->bbJumpKind == BBJ_COND) || (bJump->bbJumpKind == BBJ_ALWAYS)) + if (bJump->KindIs(BBJ_COND, BBJ_ALWAYS)) { BasicBlock* bDest = bJump->bbJumpDest; BasicBlock* bTemp = (bSrc == nullptr) ? bJump : bSrc; @@ -5799,7 +5813,7 @@ bool Compiler::fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt) noway_assert(bAlt != nullptr); // We only handle the cases when bAlt is a BBJ_ALWAYS or a BBJ_COND - if ((bAlt->bbJumpKind != BBJ_ALWAYS) && (bAlt->bbJumpKind != BBJ_COND)) + if (!bAlt->KindIs(BBJ_ALWAYS, BBJ_COND)) { return false; } diff --git a/src/coreclr/jit/fgdiagnostic.cpp b/src/coreclr/jit/fgdiagnostic.cpp index 7fd7b5d562563..0bc461ebbb949 100644 --- a/src/coreclr/jit/fgdiagnostic.cpp +++ b/src/coreclr/jit/fgdiagnostic.cpp @@ -2151,11 +2151,11 @@ void Compiler::fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth /* = 0 * { if (block == fgEntryBB) { - printf("original-entry"); + printf(" original-entry"); } if (block == fgOSREntryBB) { - printf("osr-entry"); + printf(" osr-entry"); } } @@ -2503,7 +2503,7 @@ bool BBPredsChecker::CheckEhTryDsc(BasicBlock* block, BasicBlock* blockPred, EHb bool BBPredsChecker::CheckEhHndDsc(BasicBlock* block, BasicBlock* blockPred, EHblkDsc* ehHndlDsc) { // You can do a BBJ_EHFINALLYRET or BBJ_EHFILTERRET into a handler region - if ((blockPred->bbJumpKind == BBJ_EHFINALLYRET) || (blockPred->bbJumpKind == BBJ_EHFILTERRET)) + if (blockPred->KindIs(BBJ_EHFINALLYRET, BBJ_EHFILTERRET)) { return true; } diff --git a/src/coreclr/jit/fginline.cpp b/src/coreclr/jit/fginline.cpp index bc5920d55f276..53566eb17de7b 100644 --- a/src/coreclr/jit/fginline.cpp +++ b/src/coreclr/jit/fginline.cpp @@ -47,7 +47,9 @@ unsigned Compiler::fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo) // This inline candidate has the same IL code buffer as an already // inlined method does. inlineResult->NoteFatal(InlineObservation::CALLSITE_IS_RECURSIVE); - break; + + // No need to note CALLSITE_DEPTH we're already rejecting this candidate + return depth; } if (depth > InlineStrategy::IMPLEMENTATION_MAX_INLINE_DEPTH) @@ -1433,6 +1435,13 @@ void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo) // Save the basic block flags from the retExpr basic block. iciCall->gtInlineCandidateInfo->retExpr->AsRetExpr()->bbFlags = pInlineInfo->retBB->bbFlags; } + + if (bottomBlock != nullptr) + { + // We've split the iciblock into two and the RET_EXPR was possibly moved to the bottomBlock + // so let's update its flags with retBB's ones + bottomBlock->bbFlags |= pInlineInfo->retBB->bbFlags & BBF_COMPACT_UPD; + } iciCall->ReplaceWith(pInlineInfo->retExpr, this); } diff --git a/src/coreclr/jit/fgopt.cpp b/src/coreclr/jit/fgopt.cpp index 361ff92ee8099..4e446837bcb18 100644 --- a/src/coreclr/jit/fgopt.cpp +++ b/src/coreclr/jit/fgopt.cpp @@ -145,16 +145,16 @@ bool Compiler::fgReachable(BasicBlock* b1, BasicBlock* b2) if (b1->bbNum > fgDomBBcount) { - noway_assert(b1->bbJumpKind == BBJ_NONE || b1->bbJumpKind == BBJ_ALWAYS || b1->bbJumpKind == BBJ_COND); + noway_assert(b1->KindIs(BBJ_NONE, BBJ_ALWAYS, BBJ_COND)); - if (b1->bbFallsThrough() && fgReachable(b1->bbNext, b2)) + if (b1->KindIs(BBJ_NONE, BBJ_COND) && fgReachable(b1->bbNext, b2)) { return true; } - if (b1->bbJumpKind == BBJ_ALWAYS || b1->bbJumpKind == BBJ_COND) + if (b1->KindIs(BBJ_ALWAYS, BBJ_COND) && fgReachable(b1->bbJumpDest, b2)) { - return fgReachable(b1->bbJumpDest, b2); + return true; } return false; @@ -3549,7 +3549,7 @@ bool Compiler::fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* // bool Compiler::fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev) { - assert(block->bbJumpKind == BBJ_COND || block->bbJumpKind == BBJ_ALWAYS); + assert(block->KindIs(BBJ_COND, BBJ_ALWAYS)); assert(block->bbJumpDest == bNext); assert(block->bbNext == bNext); assert(block->bbPrev == bPrev); @@ -4604,7 +4604,7 @@ bool Compiler::fgReorderBlocks() bool backwardBranch = false; // Setup bDest - if ((bPrev->bbJumpKind == BBJ_COND) || (bPrev->bbJumpKind == BBJ_ALWAYS)) + if (bPrev->KindIs(BBJ_COND, BBJ_ALWAYS)) { bDest = bPrev->bbJumpDest; forwardBranch = fgIsForwardBranch(bPrev); @@ -4854,8 +4854,7 @@ bool Compiler::fgReorderBlocks() // to bTmp (which is a higher weighted block) then it is better to keep out current // candidateBlock and have it fall into bTmp // - if ((candidateBlock == nullptr) || - ((candidateBlock->bbJumpKind != BBJ_COND) && (candidateBlock->bbJumpKind != BBJ_ALWAYS)) || + if ((candidateBlock == nullptr) || !candidateBlock->KindIs(BBJ_COND, BBJ_ALWAYS) || (candidateBlock->bbJumpDest != bTmp)) { // otherwise we have a new candidateBlock @@ -5796,7 +5795,7 @@ bool Compiler::fgUpdateFlowGraph(bool doTailDuplication) // Remove JUMPS to the following block // and optimize any JUMPS to JUMPS - if (block->bbJumpKind == BBJ_COND || block->bbJumpKind == BBJ_ALWAYS) + if (block->KindIs(BBJ_COND, BBJ_ALWAYS)) { bDest = block->bbJumpDest; if (bDest == bNext) @@ -5935,7 +5934,7 @@ bool Compiler::fgUpdateFlowGraph(bool doTailDuplication) // Add fall through fixup block, if needed. // - if ((bDest->bbJumpKind == BBJ_NONE) || (bDest->bbJumpKind == BBJ_COND)) + if (bDest->KindIs(BBJ_NONE, BBJ_COND)) { BasicBlock* const bFixup = fgNewBBafter(BBJ_ALWAYS, bDest, true); bFixup->inheritWeight(bDestNext); diff --git a/src/coreclr/jit/fgprofile.cpp b/src/coreclr/jit/fgprofile.cpp index f94cb8615be40..34ab390a9b899 100644 --- a/src/coreclr/jit/fgprofile.cpp +++ b/src/coreclr/jit/fgprofile.cpp @@ -1721,12 +1721,23 @@ PhaseStatus Compiler::fgPrepareToInstrumentMethod() // jitting on PGO. If we ever implement a broader pattern of deferral -- say deferring // based on static PGO -- we will need to reconsider. // + // Under OSR stress we may add patchpoints even without backedges. So we also + // need to change the PGO instrumetation approach if OSR stress is enabled. + // CLANG_FORMAT_COMMENT_ANCHOR; +#if defined(DEBUG) + const bool mayHaveStressPatchpoints = + (JitConfig.JitOffsetOnStackReplacement() >= 0) || (JitConfig.JitRandomOnStackReplacement() > 0); +#else + const bool mayHaveStressPatchpoints = false; +#endif + + const bool mayHavePatchpoints = + (JitConfig.TC_OnStackReplacement() > 0) && (compHasBackwardJump || mayHaveStressPatchpoints); const bool prejit = opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT); - const bool tier0WithPatchpoints = opts.jitFlags->IsSet(JitFlags::JIT_FLAG_TIER0) && - (JitConfig.TC_OnStackReplacement() > 0) && compHasBackwardJump; - const bool osrMethod = opts.IsOSR(); + const bool tier0WithPatchpoints = opts.jitFlags->IsSet(JitFlags::JIT_FLAG_TIER0) && mayHavePatchpoints; + const bool osrMethod = opts.IsOSR(); const bool useEdgeProfiles = (JitConfig.JitEdgeProfiling() > 0) && !prejit && !tier0WithPatchpoints && !osrMethod; if (useEdgeProfiles) @@ -3417,7 +3428,7 @@ weight_t Compiler::fgComputeMissingBlockWeights() // Sum up the weights of all of the return blocks and throw blocks // This is used when we have a back-edge into block 1 // - if (bDst->hasProfileWeight() && ((bDst->bbJumpKind == BBJ_RETURN) || (bDst->bbJumpKind == BBJ_THROW))) + if (bDst->hasProfileWeight() && bDst->KindIs(BBJ_RETURN, BBJ_THROW)) { returnWeight += bDst->bbWeight; } @@ -3988,7 +3999,7 @@ void Compiler::fgDebugCheckProfileData() // Exit blocks // - if ((block->bbJumpKind == BBJ_RETURN) || (block->bbJumpKind == BBJ_THROW)) + if (block->KindIs(BBJ_RETURN, BBJ_THROW)) { exitWeight += blockWeight; exitProfiled = true; @@ -4157,7 +4168,7 @@ bool Compiler::fgDebugCheckOutgoingProfileData(BasicBlock* block) // We won't check finally or filter returns (for now). // - if ((block->bbJumpKind == BBJ_EHFINALLYRET) || (block->bbJumpKind == BBJ_EHFILTERRET)) + if (block->KindIs(BBJ_EHFINALLYRET, BBJ_EHFILTERRET)) { return true; } diff --git a/src/coreclr/jit/fgstmt.cpp b/src/coreclr/jit/fgstmt.cpp index 24140b3fc52b9..f5f07399a1d37 100644 --- a/src/coreclr/jit/fgstmt.cpp +++ b/src/coreclr/jit/fgstmt.cpp @@ -182,7 +182,7 @@ void Compiler::fgInsertStmtNearEnd(BasicBlock* block, Statement* stmt) // This routine can only be used when in tree order. assert(fgOrder == FGOrderTree); - if ((block->bbJumpKind == BBJ_COND) || (block->bbJumpKind == BBJ_SWITCH) || (block->bbJumpKind == BBJ_RETURN)) + if (block->KindIs(BBJ_COND, BBJ_SWITCH, BBJ_RETURN)) { Statement* firstStmt = block->firstStmt(); noway_assert(firstStmt != nullptr); diff --git a/src/coreclr/jit/flowgraph.cpp b/src/coreclr/jit/flowgraph.cpp index 2e29847aa202b..ba032045e74b7 100644 --- a/src/coreclr/jit/flowgraph.cpp +++ b/src/coreclr/jit/flowgraph.cpp @@ -108,23 +108,8 @@ PhaseStatus Compiler::fgInsertGCPolls() // the test. // If we're doing GCPOLL_CALL, just insert a GT_CALL node before the last node in the block. - CLANG_FORMAT_COMMENT_ANCHOR; -#ifdef DEBUG - switch (block->bbJumpKind) - { - case BBJ_RETURN: - case BBJ_ALWAYS: - case BBJ_COND: - case BBJ_SWITCH: - case BBJ_NONE: - case BBJ_THROW: - case BBJ_CALLFINALLY: - break; - default: - assert(!"Unexpected block kind"); - } -#endif // DEBUG + assert(block->KindIs(BBJ_RETURN, BBJ_ALWAYS, BBJ_COND, BBJ_SWITCH, BBJ_NONE, BBJ_THROW, BBJ_CALLFINALLY)); GCPollType pollType = GCPOLL_INLINE; @@ -245,10 +230,9 @@ BasicBlock* Compiler::fgCreateGCPoll(GCPollType pollType, BasicBlock* block) createdPollBlocks = false; Statement* newStmt = nullptr; - if ((block->bbJumpKind == BBJ_ALWAYS) || (block->bbJumpKind == BBJ_CALLFINALLY) || - (block->bbJumpKind == BBJ_NONE)) + if (block->KindIs(BBJ_ALWAYS, BBJ_CALLFINALLY, BBJ_NONE)) { - // For BBJ_ALWAYS, BBJ_CALLFINALLY, and BBJ_NONE and we don't need to insert it before the condition. + // For BBJ_ALWAYS, BBJ_CALLFINALLY, and BBJ_NONE we don't need to insert it before the condition. // Just append it. newStmt = fgNewStmtAtEnd(block, call); } @@ -967,7 +951,7 @@ bool Compiler::fgAddrCouldBeNull(GenTree* addr) { return false; } - else if (addr->OperIs(GT_CNS_STR)) + else if (addr->OperIs(GT_CNS_STR, GT_CLS_VAR_ADDR)) { return false; } @@ -1269,7 +1253,7 @@ bool Compiler::fgCastNeeded(GenTree* tree, var_types toType) // If tree is a relop and we need an 4-byte integer // then we never need to insert a cast // - if ((tree->OperKind() & GTK_RELOP) && (genActualType(toType) == TYP_INT)) + if (tree->OperIsCompare() && (genActualType(toType) == TYP_INT)) { return false; } @@ -3920,7 +3904,7 @@ void Compiler::fgSetTreeSeqHelper(GenTree* tree, bool isLIR) /* Is this a leaf/constant node? */ - if (kind & (GTK_CONST | GTK_LEAF)) + if (kind & GTK_LEAF) { fgSetTreeSeqFinish(tree, isLIR); return; diff --git a/src/coreclr/jit/gentree.cpp b/src/coreclr/jit/gentree.cpp index 3a61e6318e6e1..3ba0b8a8c9095 100644 --- a/src/coreclr/jit/gentree.cpp +++ b/src/coreclr/jit/gentree.cpp @@ -20,7 +20,7 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /*****************************************************************************/ -const unsigned short GenTree::gtOperKindTable[] = { +const unsigned char GenTree::gtOperKindTable[] = { #define GTNODE(en, st, cm, ok) (ok) + GTK_COMMUTE *cm, #include "gtlist.h" }; @@ -1316,7 +1316,7 @@ bool GenTree::Compare(GenTree* op1, GenTree* op2, bool swapOK) /* Is this a constant node? */ - if (kind & GTK_CONST) + if (op1->OperIsConst()) { switch (oper) { @@ -1774,9 +1774,9 @@ unsigned Compiler::gtHashValue(GenTree* tree) hash = genTreeHashAdd(hash, oper); - /* Is this a constant or leaf node? */ + /* Is this a leaf node? */ - if (kind & (GTK_CONST | GTK_LEAF)) + if (kind & GTK_LEAF) { size_t add; @@ -3219,9 +3219,9 @@ unsigned Compiler::gtSetEvalOrder(GenTree* tree) costSz = -1; #endif - /* Is this a constant or a leaf node? */ + /* Is this a leaf node? */ - if (kind & (GTK_LEAF | GTK_CONST)) + if (kind & GTK_LEAF) { switch (oper) { @@ -4191,7 +4191,7 @@ unsigned Compiler::gtSetEvalOrder(GenTree* tree) break; } } - else if (kind & GTK_RELOP) + else if (GenTree::OperIsCompare(oper)) { /* Float compares remove both operands from the FP stack */ /* Also FP comparison uses EAX for flags */ @@ -4265,7 +4265,7 @@ unsigned Compiler::gtSetEvalOrder(GenTree* tree) such cases, both sides have a level of 0. So encourage constants to be evaluated last in such cases */ - if ((level == 0) && (level == lvl2) && (op1->OperKind() & GTK_CONST) && + if ((level == 0) && (level == lvl2) && op1->OperIsConst() && (tree->OperIsCommutative() || tree->OperIsCompare())) { lvl2++; @@ -4325,7 +4325,7 @@ unsigned Compiler::gtSetEvalOrder(GenTree* tree) // Try to force extra swapping when in the stress mode: if (compStressCompile(STRESS_REVERSE_FLAG, 60) && ((tree->gtFlags & GTF_REVERSE_OPS) == 0) && - ((op2->OperKind() & GTK_CONST) == 0)) + !op2->OperIsConst()) { tryToSwap = true; } @@ -7079,17 +7079,14 @@ GenTree* Compiler::gtClone(GenTree* tree, bool complexOK) if (tree->gtOper == GT_FIELD) { - GenTree* objp; - - // copied from line 9850 + GenTree* objp = nullptr; - objp = nullptr; if (tree->AsField()->GetFldObj() != nullptr) { objp = gtClone(tree->AsField()->GetFldObj(), false); - if (!objp) + if (objp == nullptr) { - return objp; + return nullptr; } } @@ -7185,9 +7182,9 @@ GenTree* Compiler::gtCloneExpr( unsigned kind = tree->OperKind(); GenTree* copy; - /* Is this a constant or leaf node? */ + /* Is this a leaf node? */ - if (kind & (GTK_CONST | GTK_LEAF)) + if (kind & GTK_LEAF) { switch (oper) { @@ -10066,7 +10063,7 @@ void Compiler::gtDispClassLayout(ClassLayout* layout, var_types type) /*****************************************************************************/ void Compiler::gtDispConst(GenTree* tree) { - assert(tree->OperKind() & GTK_CONST); + assert(tree->OperIsConst()); switch (tree->gtOper) { @@ -10277,7 +10274,7 @@ void Compiler::gtDispFieldSeq(FieldSeqNode* pfsn) void Compiler::gtDispLeaf(GenTree* tree, IndentStack* indentStack) { - if (tree->OperKind() & GTK_CONST) + if (tree->OperIsConst()) { gtDispConst(tree); return; @@ -10827,6 +10824,9 @@ void Compiler::gtDispTree(GenTree* tree, case NI_System_Object_GetType: printf(" objGetType"); break; + case NI_System_Runtime_CompilerServices_RuntimeHelpers_IsKnownConstant: + printf(" isKnownConst"); + break; default: unreached(); @@ -11593,7 +11593,7 @@ GenTree* Compiler::gtFoldExpr(GenTree* tree) if ((kind & GTK_UNOP) && op1) { - if (op1->OperKind() & GTK_CONST) + if (op1->OperIsConst()) { return gtFoldExprConst(tree); } @@ -11606,12 +11606,12 @@ GenTree* Compiler::gtFoldExpr(GenTree* tree) // The atomic operations are exempted here because they are never computable statically; // one of their arguments is an address. - if (((op1->OperKind() & op2->OperKind()) & GTK_CONST) && !tree->OperIsAtomicOp()) + if (op1->OperIsConst() && op2->OperIsConst() && !tree->OperIsAtomicOp()) { /* both nodes are constants - fold the expression */ return gtFoldExprConst(tree); } - else if ((op1->OperKind() | op2->OperKind()) & GTK_CONST) + else if (op1->OperIsConst() || op2->OperIsConst()) { /* at least one is a constant - see if we have a * special operator that can use only one constant @@ -12363,14 +12363,14 @@ GenTree* Compiler::gtFoldExprSpecial(GenTree* tree) case GT_DIV: case GT_UDIV: - if ((op2 == cons) && (val == 1) && !(op1->OperKind() & GTK_CONST)) + if ((op2 == cons) && (val == 1) && !op1->OperIsConst()) { goto DONE_FOLD; } break; case GT_SUB: - if ((op2 == cons) && (val == 0) && !(op1->OperKind() & GTK_CONST)) + if ((op2 == cons) && (val == 0) && !op1->OperIsConst()) { goto DONE_FOLD; } @@ -13987,7 +13987,7 @@ GenTree* Compiler::gtFoldExprConst(GenTree* tree) { JITDUMP("Double operator(s) is NaN\n"); - if (tree->OperIsRelop()) + if (tree->OperIsCompare()) { if (tree->gtFlags & GTF_RELOP_NAN_UN) { @@ -15702,7 +15702,7 @@ bool GenTree::isContained() const // these actually produce a register (the flags reg, we just don't model it) // and are a separate instruction from the branch that consumes the result. // They can only produce a result if the child is a SIMD equality comparison. - else if (OperKind() & GTK_RELOP) + else if (OperIsCompare()) { assert(isMarkedContained == false); } @@ -15924,183 +15924,108 @@ bool GenTreeIntConCommon::AddrNeedsReloc(Compiler* comp) } #endif // TARGET_X86 -bool GenTree::IsFieldAddr(Compiler* comp, GenTree** pObj, GenTree** pStatic, FieldSeqNode** pFldSeq) +//------------------------------------------------------------------------ +// IsFieldAddr: Is "this" a static or class field address? +// +// Recognizes the following three patterns: +// this: [Zero FldSeq] +// this: ADD(baseAddr, CONST FldSeq) +// this: ADD(CONST FldSeq, baseAddr) +// +// Arguments: +// comp - the Compiler object +// pBaseAddr - [out] parameter for "the base address" +// pFldSeq - [out] parameter for the field sequence +// +// Return Value: +// If "this" matches patterns denoted above, and the FldSeq found is "full", +// i. e. starts with a class field or a static field, and includes all the +// struct fields that this tree represents the address of, this method will +// return "true" and set either "pBaseAddr" to some value, which must be used +// by the caller as the key into the "first field map" to obtain the actual +// value for the field. For instance fields, "base address" will be the object +// reference, for statics - the address to which the field offset with the +// field sequence is added, see "impImportStaticFieldAccess" and "fgMorphField". +// +bool GenTree::IsFieldAddr(Compiler* comp, GenTree** pBaseAddr, FieldSeqNode** pFldSeq) { - FieldSeqNode* newFldSeq = nullptr; - GenTree* baseAddr = nullptr; - bool mustBeStatic = false; + assert(TypeIs(TYP_I_IMPL, TYP_BYREF, TYP_REF)); - FieldSeqNode* statStructFldSeq = nullptr; - if (TypeGet() == TYP_REF) - { - // Recognize struct static field patterns... - if (OperGet() == GT_IND) - { - GenTree* addr = AsOp()->gtOp1; - GenTreeIntCon* icon = nullptr; - if (addr->OperGet() == GT_CNS_INT) - { - icon = addr->AsIntCon(); - } - else if (addr->OperGet() == GT_ADD) - { - // op1 should never be a field sequence (or any other kind of handle) - assert((addr->AsOp()->gtOp1->gtOper != GT_CNS_INT) || !addr->AsOp()->gtOp1->IsIconHandle()); - if (addr->AsOp()->gtOp2->OperGet() == GT_CNS_INT) - { - icon = addr->AsOp()->gtOp2->AsIntCon(); - } - } - if (icon != nullptr && !icon->IsIconHandle(GTF_ICON_STR_HDL) // String handles are a source of TYP_REFs. - && icon->gtFieldSeq != nullptr && - icon->gtFieldSeq->m_next == nullptr // A static field should be a singleton - // TODO-Review: A pseudoField here indicates an issue - this requires investigation - // See test case src\ddsuites\src\clr\x86\CoreMangLib\Dev\Globalization\CalendarRegressions.exe - && !(FieldSeqStore::IsPseudoField(icon->gtFieldSeq->m_fieldHnd)) && - icon->gtFieldSeq != FieldSeqStore::NotAField()) // Ignore non-fields. - { - statStructFldSeq = icon->gtFieldSeq; - } - else - { - addr = addr->gtEffectiveVal(); + *pBaseAddr = nullptr; + *pFldSeq = FieldSeqStore::NotAField(); - // Perhaps it's a direct indirection of a helper call or a cse with a zero offset annotation. - if ((addr->OperGet() == GT_CALL) || (addr->OperGet() == GT_LCL_VAR)) - { - FieldSeqNode* zeroFieldSeq = nullptr; - if (comp->GetZeroOffsetFieldMap()->Lookup(addr, &zeroFieldSeq)) - { - if (zeroFieldSeq->m_next == nullptr) - { - statStructFldSeq = zeroFieldSeq; - } - } - } - } - } - else if (OperGet() == GT_CLS_VAR) + GenTree* baseAddr = nullptr; + FieldSeqNode* fldSeq = nullptr; + + if (OperIs(GT_ADD)) + { + // If one operand has a field sequence, the other operand must not have one + // as the order of fields in that case would not be well-defined. + if (AsOp()->gtOp1->IsCnsIntOrI() && AsOp()->gtOp1->IsIconHandle()) { - GenTreeClsVar* clsVar = AsClsVar(); - if (clsVar->gtFieldSeq != nullptr && clsVar->gtFieldSeq->m_next == nullptr) - { - statStructFldSeq = clsVar->gtFieldSeq; - } + assert(!AsOp()->gtOp2->IsCnsIntOrI() || !AsOp()->gtOp2->IsIconHandle()); + fldSeq = AsOp()->gtOp1->AsIntCon()->gtFieldSeq; + baseAddr = AsOp()->gtOp2; } - else if (OperIsLocal()) + else if (AsOp()->gtOp2->IsCnsIntOrI()) { - // If we have a GT_LCL_VAR, it can be result of a CSE substitution - // If it is then the CSE assignment will have a ValueNum that - // describes the RHS of the CSE assignment. - // - // The CSE could be a pointer to a boxed struct - // - ValueNum vn = gtVNPair.GetLiberal(); - if (vn != ValueNumStore::NoVN) - { - // Is the ValueNum a MapSelect involving a SharedStatic helper? - VNFuncApp funcApp1; - if (comp->vnStore->GetVNFunc(vn, &funcApp1) && (funcApp1.m_func == VNF_MapSelect) && - (comp->vnStore->IsSharedStatic(funcApp1.m_args[1]))) - { - ValueNum mapVN = funcApp1.m_args[0]; - // Is this new 'mapVN' ValueNum, a MapSelect involving a handle? - VNFuncApp funcApp2; - if (comp->vnStore->GetVNFunc(mapVN, &funcApp2) && (funcApp2.m_func == VNF_MapSelect) && - (comp->vnStore->IsVNHandle(funcApp2.m_args[1]))) - { - ValueNum fldHndVN = funcApp2.m_args[1]; - // Is this new 'fldHndVN' VNhandle a FieldHandle? - unsigned flags = comp->vnStore->GetHandleFlags(fldHndVN); - if (flags == GTF_ICON_FIELD_HDL) - { - CORINFO_FIELD_HANDLE fieldHnd = - CORINFO_FIELD_HANDLE(comp->vnStore->ConstantValue(fldHndVN)); - - // Record this field sequence in 'statStructFldSeq' as it is likely to be a Boxed Struct - // field access. - statStructFldSeq = comp->GetFieldSeqStore()->CreateSingleton(fieldHnd); - } - } - } - } + assert(!AsOp()->gtOp1->IsCnsIntOrI() || !AsOp()->gtOp1->IsIconHandle()); + fldSeq = AsOp()->gtOp2->AsIntCon()->gtFieldSeq; + baseAddr = AsOp()->gtOp1; } - if (statStructFldSeq != nullptr) + if (baseAddr != nullptr) { - assert(statStructFldSeq->m_next == nullptr); - // Is this a pointer to a boxed struct? - if (comp->gtIsStaticFieldPtrToBoxedStruct(TYP_REF, statStructFldSeq->m_fieldHnd)) - { - *pFldSeq = comp->GetFieldSeqStore()->Append(statStructFldSeq, *pFldSeq); - *pObj = nullptr; - *pStatic = this; - return true; - } + assert(!baseAddr->TypeIs(TYP_REF) || !comp->GetZeroOffsetFieldMap()->Lookup(baseAddr)); } - - // Otherwise... - *pObj = this; - *pStatic = nullptr; - return true; } - else if (OperGet() == GT_ADD) + else if (comp->GetZeroOffsetFieldMap()->Lookup(this, &fldSeq)) { - // If one operator is a field sequence/handle, the other operator must not also be a field sequence/handle. - if ((AsOp()->gtOp1->OperGet() == GT_CNS_INT) && AsOp()->gtOp1->IsIconHandle()) - { - assert((AsOp()->gtOp2->gtOper != GT_CNS_INT) || !AsOp()->gtOp2->IsIconHandle()); - newFldSeq = AsOp()->gtOp1->AsIntCon()->gtFieldSeq; - baseAddr = AsOp()->gtOp2; - } - else if (AsOp()->gtOp2->OperGet() == GT_CNS_INT) - { - assert((AsOp()->gtOp1->gtOper != GT_CNS_INT) || !AsOp()->gtOp1->IsIconHandle()); - newFldSeq = AsOp()->gtOp2->AsIntCon()->gtFieldSeq; - baseAddr = AsOp()->gtOp1; - } + baseAddr = this; } else { - // Check if "this" has a zero-offset annotation. - if (!comp->GetZeroOffsetFieldMap()->Lookup(this, &newFldSeq)) - { - // If not, this is not a field address. - return false; - } - else - { - baseAddr = this; - mustBeStatic = true; - } + // TODO-VNTypes-CQ: recognize the simple GTF_ICON_STATIC_HDL case here. It + // is not recognized right now to preserve previous behavior of this method. + return false; } - // If not we don't have a field seq, it's not a field address. - if (newFldSeq == nullptr || newFldSeq == FieldSeqStore::NotAField()) + // If we don't have a valid sequence, bail. Note that above we have overloaded an empty + // ("nullptr") sequence as "NotAField", as that's the way it is treated on tree nodes. + if ((fldSeq == nullptr) || (fldSeq == FieldSeqStore::NotAField()) || fldSeq->IsPseudoField()) { return false; } - // Prepend this field to whatever we've already accumulated (outside-in). - *pFldSeq = comp->GetFieldSeqStore()->Append(newFldSeq, *pFldSeq); + assert(baseAddr != nullptr); - // Is it a static or instance field? - if (!FieldSeqStore::IsPseudoField(newFldSeq->m_fieldHnd) && - comp->info.compCompHnd->isFieldStatic(newFldSeq->m_fieldHnd)) + // The above screens out obviously invalid cases, but we have more checks to perform. The + // sequence returned from this method *must* start with either a class (NOT struct) field + // or a static field. To avoid the expense of calling "getFieldClass" here, we will instead + // rely on the invariant that TYP_REF base addresses can never appear for struct fields - we + // will effectively treat such cases ("possible" in unsafe code) as undefined behavior. + if (comp->eeIsFieldStatic(fldSeq->GetFieldHandle())) { - // It is a static field. We're done. - *pObj = nullptr; - *pStatic = baseAddr; + // TODO-VNTypes: we will always return the "baseAddr" here for now, but strictly speaking, + // we only need to do that if we have a shared field, to encode the logical "instantiation" + // argument. In all other cases, this serves no purpose and just leads to redundant maps. + *pBaseAddr = baseAddr; + *pFldSeq = fldSeq; return true; } - else if ((baseAddr != nullptr) && !mustBeStatic) + + if (baseAddr->TypeIs(TYP_REF)) { - // It's an instance field...but it must be for a struct field, since we've not yet encountered - // a "TYP_REF" address. Analyze the reset of the address. - return baseAddr->gtEffectiveVal()->IsFieldAddr(comp, pObj, pStatic, pFldSeq); + assert(!comp->eeIsValueClass(comp->info.compCompHnd->getFieldClass(fldSeq->GetFieldHandle()))); + + *pBaseAddr = baseAddr; + *pFldSeq = fldSeq; + return true; } - // Otherwise... + // This case is reached, for example, if we have a chain of struct fields that are based on + // some pointer. We do not model such cases because we do not model maps for ByrefExposed + // memory, as it does not have the non-aliasing property of GcHeap and reference types. return false; } @@ -17810,6 +17735,20 @@ bool GenTree::isContainableHWIntrinsic() const return true; } + default: + { + return false; + } + } +#elif TARGET_ARM64 + switch (AsHWIntrinsic()->GetHWIntrinsicId()) + { + case NI_Vector64_get_Zero: + case NI_Vector128_get_Zero: + { + return true; + } + default: { return false; @@ -18074,7 +18013,15 @@ GenTree* Compiler::gtNewSimdBinOpNode(genTreeOps op, assert(op1->TypeIs(type, simdBaseType, genActualType(simdBaseType))); assert(op2 != nullptr); - assert(op2->TypeIs(type, simdBaseType, genActualType(simdBaseType))); + + if ((op == GT_LSH) || (op == GT_RSH) || (op == GT_RSZ)) + { + assert(op2->TypeIs(TYP_INT)); + } + else + { + assert(op2->TypeIs(type, simdBaseType, genActualType(simdBaseType))); + } NamedIntrinsic intrinsic = NI_Illegal; CORINFO_CLASS_HANDLE clsHnd = gtGetStructHandleForSIMD(type, simdBaseJitType); @@ -18201,6 +18148,67 @@ GenTree* Compiler::gtNewSimdBinOpNode(genTreeOps op, break; } + case GT_LSH: + case GT_RSH: + case GT_RSZ: + { + assert(!varTypeIsByte(simdBaseType)); + assert(!varTypeIsFloating(simdBaseType)); + assert((op != GT_RSH) || !varTypeIsUnsigned(simdBaseType)); + + // "over shifting" is platform specific behavior. We will match the C# behavior + // this requires we mask with (sizeof(T) * 8) - 1 which ensures the shift cannot + // exceed the number of bits available in `T`. This is roughly equivalent to + // x % (sizeof(T) * 8), but that is "more expensive" and only the same for unsigned + // inputs, where-as we have a signed-input and so negative values would differ. + + unsigned shiftCountMask = (genTypeSize(simdBaseType) * 8) - 1; + + if (op2->IsCnsIntOrI()) + { + op2->AsIntCon()->gtIconVal &= shiftCountMask; + } + else + { + op2 = gtNewOperNode(GT_AND, TYP_INT, op2, gtNewIconNode(shiftCountMask)); + op2 = gtNewSimdHWIntrinsicNode(TYP_SIMD16, op2, NI_SSE2_ConvertScalarToVector128Int32, CORINFO_TYPE_INT, + 16, isSimdAsHWIntrinsic); + } + + if (simdSize == 32) + { + assert(compIsaSupportedDebugOnly(InstructionSet_AVX2)); + + if (op == GT_LSH) + { + intrinsic = NI_AVX2_ShiftLeftLogical; + } + else if (op == GT_RSH) + { + intrinsic = NI_AVX2_ShiftRightArithmetic; + } + else + { + assert(op == GT_RSZ); + intrinsic = NI_AVX2_ShiftRightLogical; + } + } + else if (op == GT_LSH) + { + intrinsic = NI_SSE2_ShiftLeftLogical; + } + else if (op == GT_RSH) + { + intrinsic = NI_SSE2_ShiftRightArithmetic; + } + else + { + assert(op == GT_RSZ); + intrinsic = NI_SSE2_ShiftRightLogical; + } + break; + } + case GT_MUL: { GenTree** broadcastOp = nullptr; @@ -18469,6 +18477,98 @@ GenTree* Compiler::gtNewSimdBinOpNode(genTreeOps op, break; } + case GT_LSH: + case GT_RSH: + case GT_RSZ: + { + assert(!varTypeIsFloating(simdBaseType)); + assert((op != GT_RSH) || !varTypeIsUnsigned(simdBaseType)); + + // "over shifting" is platform specific behavior. We will match the C# behavior + // this requires we mask with (sizeof(T) * 8) - 1 which ensures the shift cannot + // exceed the number of bits available in `T`. This is roughly equivalent to + // x % (sizeof(T) * 8), but that is "more expensive" and only the same for unsigned + // inputs, where-as we have a signed-input and so negative values would differ. + + unsigned shiftCountMask = (genTypeSize(simdBaseType) * 8) - 1; + + if (op2->IsCnsIntOrI()) + { + op2->AsIntCon()->gtIconVal &= shiftCountMask; + + if ((simdSize == 8) && varTypeIsLong(simdBaseType)) + { + if (op == GT_LSH) + { + intrinsic = NI_AdvSimd_ShiftLeftLogicalScalar; + } + else if (op == GT_RSH) + { + intrinsic = NI_AdvSimd_ShiftRightArithmeticScalar; + } + else + { + assert(op == GT_RSZ); + intrinsic = NI_AdvSimd_ShiftRightLogicalScalar; + } + } + else if (op == GT_LSH) + { + intrinsic = NI_AdvSimd_ShiftLeftLogical; + } + else if (op == GT_RSH) + { + intrinsic = NI_AdvSimd_ShiftRightArithmetic; + } + else + { + assert(op == GT_RSZ); + intrinsic = NI_AdvSimd_ShiftRightLogical; + } + } + else + { + op2 = gtNewOperNode(GT_AND, TYP_INT, op2, gtNewIconNode(shiftCountMask)); + + if (op != GT_LSH) + { + op2 = gtNewOperNode(GT_NEG, TYP_INT, op2); + } + + op2 = gtNewSimdCreateBroadcastNode(type, op2, simdBaseJitType, simdSize, isSimdAsHWIntrinsic); + + if ((simdSize == 8) && varTypeIsLong(simdBaseType)) + { + if (op == GT_LSH) + { + intrinsic = NI_AdvSimd_ShiftLogicalScalar; + } + else if (op == GT_RSH) + { + intrinsic = NI_AdvSimd_ShiftArithmeticScalar; + } + else + { + intrinsic = NI_AdvSimd_ShiftLogicalScalar; + } + } + else if (op == GT_LSH) + { + intrinsic = NI_AdvSimd_ShiftLogical; + } + else if (op == GT_RSH) + { + intrinsic = NI_AdvSimd_ShiftArithmetic; + } + else + { + assert(op == GT_RSZ); + intrinsic = NI_AdvSimd_ShiftLogical; + } + } + break; + } + case GT_MUL: { assert(!varTypeIsLong(simdBaseType)); @@ -20596,6 +20696,123 @@ GenTree* Compiler::gtNewSimdSqrtNode( return gtNewSimdHWIntrinsicNode(type, op1, intrinsic, simdBaseJitType, simdSize, isSimdAsHWIntrinsic); } +GenTree* Compiler::gtNewSimdSumNode( + var_types type, GenTree* op1, CorInfoType simdBaseJitType, unsigned simdSize, bool isSimdAsHWIntrinsic) +{ + assert(IsBaselineSimdIsaSupportedDebugOnly()); + + var_types simdType = getSIMDTypeForSize(simdSize); + assert(varTypeIsSIMD(simdType)); + + assert(op1 != nullptr); + assert(op1->TypeIs(simdType)); + + var_types simdBaseType = JitType2PreciseVarType(simdBaseJitType); + assert(varTypeIsArithmetic(simdBaseType)); + + NamedIntrinsic intrinsic = NI_Illegal; + GenTree* tmp = nullptr; + CORINFO_CLASS_HANDLE clsHnd = gtGetStructHandleForSIMD(simdType, simdBaseJitType); + +#if defined(TARGET_XARCH) + assert(!varTypeIsByte(simdBaseType) && !varTypeIsLong(simdBaseType)); + + // HorizontalAdd combines pairs so we need log2(vectorLength) passes to sum all elements together. + unsigned vectorLength = getSIMDVectorLength(simdSize, simdBaseType); + int haddCount = genLog2(vectorLength); + + if (simdSize == 32) + { + // Minus 1 because for the last pass we split the vector to low / high and add them together. + haddCount -= 1; + + if (varTypeIsFloating(simdBaseType)) + { + assert(compIsaSupportedDebugOnly(InstructionSet_AVX)); + intrinsic = NI_AVX_HorizontalAdd; + } + else + { + assert(compIsaSupportedDebugOnly(InstructionSet_AVX2)); + intrinsic = NI_AVX2_HorizontalAdd; + } + } + else if (varTypeIsFloating(simdBaseType)) + { + assert(compIsaSupportedDebugOnly(InstructionSet_SSE3)); + intrinsic = NI_SSE3_HorizontalAdd; + } + else + { + assert(compIsaSupportedDebugOnly(InstructionSet_SSSE3)); + intrinsic = NI_SSSE3_HorizontalAdd; + } + + for (int i = 0; i < haddCount; i++) + { + op1 = impCloneExpr(op1, &tmp, clsHnd, (unsigned)CHECK_SPILL_ALL, nullptr DEBUGARG("Clone op1 for vector sum")); + op1 = gtNewSimdAsHWIntrinsicNode(simdType, op1, tmp, intrinsic, simdBaseJitType, simdSize); + } + + if (simdSize == 32) + { + intrinsic = (simdBaseType == TYP_FLOAT) ? NI_SSE_Add : NI_SSE2_Add; + + op1 = impCloneExpr(op1, &tmp, clsHnd, (unsigned)CHECK_SPILL_ALL, nullptr DEBUGARG("Clone op1 for vector sum")); + op1 = gtNewSimdAsHWIntrinsicNode(TYP_SIMD16, op1, gtNewIconNode(0x01, TYP_INT), NI_AVX_ExtractVector128, + simdBaseJitType, simdSize); + + tmp = gtNewSimdAsHWIntrinsicNode(simdType, tmp, NI_Vector256_GetLower, simdBaseJitType, simdSize); + op1 = gtNewSimdAsHWIntrinsicNode(TYP_SIMD16, op1, tmp, intrinsic, simdBaseJitType, 16); + } + + return gtNewSimdAsHWIntrinsicNode(type, op1, NI_Vector128_ToScalar, simdBaseJitType, simdSize); +#elif defined(TARGET_ARM64) + switch (simdBaseType) + { + case TYP_BYTE: + case TYP_UBYTE: + case TYP_SHORT: + case TYP_USHORT: + case TYP_INT: + case TYP_UINT: + { + tmp = gtNewSimdAsHWIntrinsicNode(simdType, op1, NI_AdvSimd_Arm64_AddAcross, simdBaseJitType, simdSize); + return gtNewSimdAsHWIntrinsicNode(type, tmp, NI_Vector64_ToScalar, simdBaseJitType, 8); + } + case TYP_FLOAT: + { + unsigned vectorLength = getSIMDVectorLength(simdSize, simdBaseType); + int haddCount = genLog2(vectorLength); + + for (int i = 0; i < haddCount; i++) + { + op1 = impCloneExpr(op1, &tmp, clsHnd, (unsigned)CHECK_SPILL_ALL, + nullptr DEBUGARG("Clone op1 for vector sum")); + op1 = gtNewSimdAsHWIntrinsicNode(simdType, op1, tmp, NI_AdvSimd_Arm64_AddPairwise, simdBaseJitType, + simdSize); + } + + return gtNewSimdAsHWIntrinsicNode(type, op1, NI_Vector128_ToScalar, simdBaseJitType, simdSize); + } + case TYP_DOUBLE: + case TYP_LONG: + case TYP_ULONG: + { + op1 = gtNewSimdAsHWIntrinsicNode(TYP_SIMD8, op1, NI_AdvSimd_Arm64_AddPairwiseScalar, simdBaseJitType, + simdSize); + return gtNewSimdAsHWIntrinsicNode(type, op1, NI_Vector64_ToScalar, simdBaseJitType, 8); + } + default: + { + unreached(); + } + } +#else +#error Unsupported platform +#endif // !TARGET_XARCH && !TARGET_ARM64 +} + GenTree* Compiler::gtNewSimdUnOpNode(genTreeOps op, var_types type, GenTree* op1, diff --git a/src/coreclr/jit/gentree.h b/src/coreclr/jit/gentree.h index c7a0ef0cea31a..8cab63e505b5f 100644 --- a/src/coreclr/jit/gentree.h +++ b/src/coreclr/jit/gentree.h @@ -82,45 +82,25 @@ enum genTreeOps : BYTE #endif }; -/***************************************************************************** - * - * The following enum defines a set of bit flags that can be used - * to classify expression tree nodes. Note that some operators will - * have more than one bit set, as follows: - * - * GTK_CONST implies GTK_LEAF - * GTK_RELOP implies GTK_BINOP - * GTK_LOGOP implies GTK_BINOP - */ - +// The following enum defines a set of bit flags that can be used +// to classify expression tree nodes. +// enum genTreeKinds { - GTK_SPECIAL = 0x0000, // unclassified operator (special handling reqd) - - GTK_CONST = 0x0001, // constant operator - GTK_LEAF = 0x0002, // leaf operator - GTK_UNOP = 0x0004, // unary operator - GTK_BINOP = 0x0008, // binary operator - GTK_RELOP = 0x0010, // comparison operator - GTK_LOGOP = 0x0020, // logical operator - - GTK_KINDMASK = 0x007F, // operator kind mask - - GTK_COMMUTE = 0x0080, // commutative operator - - GTK_EXOP = 0x0100, // Indicates that an oper for a node type that extends GenTreeOp (or GenTreeUnOp) - // by adding non-node fields to unary or binary operator. - - GTK_LOCAL = 0x0200, // is a local access (load, store, phi) - - GTK_NOVALUE = 0x0400, // node does not produce a value - GTK_NOTLIR = 0x0800, // node is not allowed in LIR - - GTK_NOCONTAIN = 0x1000, // this node is a value, but may not be contained + GTK_SPECIAL = 0x00, // special operator + GTK_LEAF = 0x01, // leaf operator + GTK_UNOP = 0x02, // unary operator + GTK_BINOP = 0x04, // binary operator - /* Define composite value(s) */ + GTK_KINDMASK = (GTK_SPECIAL | GTK_LEAF | GTK_UNOP | GTK_BINOP), // operator kind mask + GTK_SMPOP = (GTK_UNOP | GTK_BINOP), - GTK_SMPOP = (GTK_UNOP | GTK_BINOP | GTK_RELOP | GTK_LOGOP) + GTK_COMMUTE = 0x08, // commutative operator + GTK_EXOP = 0x10, // Indicates that an oper for a node type that extends GenTreeOp (or GenTreeUnOp) + // by adding non-node fields to unary or binary operator. + GTK_NOVALUE = 0x20, // node does not produce a value + GTK_NOTLIR = 0x40, // node is not allowed in LIR + GTK_NOCONTAIN = 0x80, // this node is a value, but may not be contained }; /*****************************************************************************/ @@ -686,6 +666,17 @@ inline GenTreeDebugFlags& operator &=(GenTreeDebugFlags& a, GenTreeDebugFlags b) // clang-format on +constexpr bool OpersAreContiguous(genTreeOps firstOper, genTreeOps secondOper) +{ + return (firstOper + 1) == secondOper; +} + +template +constexpr bool OpersAreContiguous(genTreeOps firstOper, genTreeOps secondOper, Opers... otherOpers) +{ + return OpersAreContiguous(firstOper, secondOper) && OpersAreContiguous(secondOper, otherOpers...); +} + #ifndef HOST_64BIT #include #endif @@ -1043,7 +1034,7 @@ struct GenTree int gtUseNum; // use-ordered traversal within the function #endif - static const unsigned short gtOperKindTable[]; + static const unsigned char gtOperKindTable[]; static unsigned OperKind(unsigned gtOper) { @@ -1160,12 +1151,13 @@ struct GenTree static bool OperIsConst(genTreeOps gtOper) { - return (OperKind(gtOper) & GTK_CONST) != 0; + static_assert_no_msg(OpersAreContiguous(GT_CNS_INT, GT_CNS_LNG, GT_CNS_DBL, GT_CNS_STR)); + return (GT_CNS_INT <= gtOper) && (gtOper <= GT_CNS_STR); } bool OperIsConst() const { - return (OperKind(gtOper) & GTK_CONST) != 0; + return OperIsConst(gtOper); } static bool OperIsLeaf(genTreeOps gtOper) @@ -1178,17 +1170,11 @@ struct GenTree return (OperKind(gtOper) & GTK_LEAF) != 0; } - static bool OperIsCompare(genTreeOps gtOper) - { - return (OperKind(gtOper) & GTK_RELOP) != 0; - } - static bool OperIsLocal(genTreeOps gtOper) { - bool result = (OperKind(gtOper) & GTK_LOCAL) != 0; - assert(result == (gtOper == GT_LCL_VAR || gtOper == GT_PHI_ARG || gtOper == GT_LCL_FLD || - gtOper == GT_STORE_LCL_VAR || gtOper == GT_STORE_LCL_FLD)); - return result; + static_assert_no_msg( + OpersAreContiguous(GT_PHI_ARG, GT_LCL_VAR, GT_LCL_FLD, GT_STORE_LCL_VAR, GT_STORE_LCL_FLD)); + return (GT_PHI_ARG <= gtOper) && (gtOper <= GT_STORE_LCL_FLD); } static bool OperIsLocalAddr(genTreeOps gtOper) @@ -1364,19 +1350,15 @@ struct GenTree return OperIsLocalRead(OperGet()); } - bool OperIsCompare() const - { - return (OperKind(gtOper) & GTK_RELOP) != 0; - } - - static bool OperIsLogical(genTreeOps gtOper) + static bool OperIsCompare(genTreeOps gtOper) { - return (OperKind(gtOper) & GTK_LOGOP) != 0; + static_assert_no_msg(OpersAreContiguous(GT_EQ, GT_NE, GT_LT, GT_LE, GT_GE, GT_GT, GT_TEST_EQ, GT_TEST_NE)); + return (GT_EQ <= gtOper) && (gtOper <= GT_TEST_NE); } - bool OperIsLogical() const + bool OperIsCompare() const { - return (OperKind(gtOper) & GTK_LOGOP) != 0; + return OperIsCompare(OperGet()); } static bool OperIsShift(genTreeOps gtOper) @@ -1498,16 +1480,6 @@ struct GenTree return OperIsSimple(gtOper); } - static bool OperIsRelop(genTreeOps gtOper) - { - return (OperKind(gtOper) & GTK_RELOP) != 0; - } - - bool OperIsRelop() const - { - return OperIsRelop(gtOper); - } - #ifdef FEATURE_SIMD bool isCommutativeSIMDIntrinsic(); #else // ! @@ -1732,6 +1704,8 @@ struct GenTree inline bool IsIntegralConst(ssize_t constVal) const; inline bool IsIntegralConstVector(ssize_t constVal) const; inline bool IsSIMDZero() const; + inline bool IsFloatPositiveZero() const; + inline bool IsVectorZero() const; inline bool IsBoxedValue(); @@ -1945,16 +1919,7 @@ struct GenTree // where Y is an arbitrary tree, and X is a lclVar. unsigned IsLclVarUpdateTree(GenTree** otherTree, genTreeOps* updateOper); - // If returns "true", "this" may represent the address of a static or instance field - // (or a field of such a field, in the case of an object field of type struct). - // If returns "true", then either "*pObj" is set to the object reference, - // or "*pStatic" is set to the baseAddr or offset to be added to the "*pFldSeq" - // Only one of "*pObj" or "*pStatic" will be set, the other one will be null. - // The boolean return value only indicates that "this" *may* be a field address - // -- the field sequence must also be checked. - // If it is a field address, the field sequence will be a sequence of length >= 1, - // starting with an instance or static field, and optionally continuing with struct fields. - bool IsFieldAddr(Compiler* comp, GenTree** pObj, GenTree** pStatic, FieldSeqNode** pFldSeq); + bool IsFieldAddr(Compiler* comp, GenTree** pBaseAddr, FieldSeqNode** pFldSeq); // Requires "this" to be the address of an array (the child of a GT_IND labeled with GTF_IND_ARR_INDEX). // Sets "pArr" to the node representing the array (either an array object pointer, or perhaps a byref to the some @@ -2134,7 +2099,7 @@ struct GenTree inline bool IsCnsFltOrDbl() const; - inline bool IsCnsNonZeroFltOrDbl(); + inline bool IsCnsNonZeroFltOrDbl() const; bool IsIconHandle() const { @@ -3649,11 +3614,6 @@ struct GenTreeField : public GenTreeUnOp GenTreeField(var_types type, GenTree* obj, CORINFO_FIELD_HANDLE fldHnd, DWORD offs) : GenTreeUnOp(GT_FIELD, type, obj), gtFldHnd(fldHnd), gtFldOffset(offs), gtFldMayOverlap(false) { - if (obj != nullptr) - { - gtFlags |= (obj->gtFlags & GTF_ALL_EFFECT); - } - #ifdef FEATURE_READYTORUN gtFieldLookup.addr = nullptr; #endif @@ -3665,7 +3625,7 @@ struct GenTreeField : public GenTreeUnOp } #endif - // The object this field belongs to. May be "nullptr", e. g. for static fields. + // The object this field belongs to. Will be "nullptr" for static fields. // Note that this is an address, i. e. for struct fields it will be ADDR(STRUCT). GenTree* GetFldObj() const { @@ -7692,6 +7652,79 @@ inline bool GenTree::IsSIMDZero() const return false; } +//------------------------------------------------------------------- +// IsFloatPositiveZero: returns true if this is exactly a const float value of postive zero (+0.0) +// +// Returns: +// True if this represents a const floating-point value of exactly positive zero (+0.0). +// Will return false if the value is negative zero (-0.0). +// +inline bool GenTree::IsFloatPositiveZero() const +{ + return !(IsCnsNonZeroFltOrDbl()); +} + +//------------------------------------------------------------------- +// IsVectorZero: returns true if this is an integral or floating-point (SIMD or HW intrinsic) vector +// with all its elements equal to zero. +// +// Returns: +// True if this represents an integral or floating-point const (SIMD or HW intrinsic) vector with all its elements +// equal to zero. +// +// TODO: We already have IsSIMDZero() and IsIntegralConstVector(0), +// however, IsSIMDZero() does not cover hardware intrinsics, and IsIntegralConstVector(0) does not cover floating +// point. In order to not risk adverse behaviour by modifying those, this function 'IsVectorZero' was introduced. +// At some point, it makes sense to normalize this logic to be a single function call rather than have several +// separate ones; preferably this one. +inline bool GenTree::IsVectorZero() const +{ +#ifdef FEATURE_SIMD + if (gtOper == GT_SIMD) + { + const GenTreeSIMD* node = AsSIMD(); + + if (node->GetSIMDIntrinsicId() == SIMDIntrinsicInit) + { + return (node->Op(1)->IsIntegralConst(0) || node->Op(1)->IsFloatPositiveZero()); + } + } +#endif + +#ifdef FEATURE_HW_INTRINSICS + if (gtOper == GT_HWINTRINSIC) + { + const GenTreeHWIntrinsic* node = AsHWIntrinsic(); + const var_types simdBaseType = node->GetSimdBaseType(); + + if (varTypeIsIntegral(simdBaseType) || varTypeIsFloating(simdBaseType)) + { + const NamedIntrinsic intrinsicId = node->GetHWIntrinsicId(); + + if (node->GetOperandCount() == 0) + { +#if defined(TARGET_XARCH) + return (intrinsicId == NI_Vector128_get_Zero) || (intrinsicId == NI_Vector256_get_Zero); +#elif defined(TARGET_ARM64) + return (intrinsicId == NI_Vector64_get_Zero) || (intrinsicId == NI_Vector128_get_Zero); +#endif // !TARGET_XARCH && !TARGET_ARM64 + } + else if ((node->GetOperandCount() == 1) && + (node->Op(1)->IsIntegralConst(0) || node->Op(1)->IsFloatPositiveZero())) + { +#if defined(TARGET_XARCH) + return (intrinsicId == NI_Vector128_Create) || (intrinsicId == NI_Vector256_Create); +#elif defined(TARGET_ARM64) + return (intrinsicId == NI_Vector64_Create) || (intrinsicId == NI_Vector128_Create); +#endif // !TARGET_XARCH && !TARGET_ARM64 + } + } + } +#endif // FEATURE_HW_INTRINSICS + + return false; +} + inline bool GenTree::IsBoxedValue() { assert(gtOper != GT_BOX || AsBox()->BoxOp() != nullptr); @@ -8370,7 +8403,7 @@ inline bool GenTree::IsCnsFltOrDbl() const return OperGet() == GT_CNS_DBL; } -inline bool GenTree::IsCnsNonZeroFltOrDbl() +inline bool GenTree::IsCnsNonZeroFltOrDbl() const { if (OperGet() == GT_CNS_DBL) { diff --git a/src/coreclr/jit/gtlist.h b/src/coreclr/jit/gtlist.h index 0fec37b70b2a7..5a5afe6aad050 100644 --- a/src/coreclr/jit/gtlist.h +++ b/src/coreclr/jit/gtlist.h @@ -16,15 +16,22 @@ GTNODE(NONE , char ,0,GTK_SPECIAL) //----------------------------------------------------------------------------- -// Leaf nodes (i.e. these nodes have no sub-operands): +// Nodes related to locals: //----------------------------------------------------------------------------- -GTNODE(LCL_VAR , GenTreeLclVar ,0,(GTK_LEAF|GTK_LOCAL)) // local variable -GTNODE(LCL_FLD , GenTreeLclFld ,0,(GTK_LEAF|GTK_LOCAL)) // field in a non-primitive variable +GTNODE(PHI , GenTreePhi ,0,GTK_SPECIAL) // phi node for ssa. +GTNODE(PHI_ARG , GenTreePhiArg ,0,GTK_LEAF) // phi(phiarg, phiarg, phiarg) +GTNODE(LCL_VAR , GenTreeLclVar ,0,GTK_LEAF) // local variable +GTNODE(LCL_FLD , GenTreeLclFld ,0,GTK_LEAF) // field in a non-primitive variable +GTNODE(STORE_LCL_VAR , GenTreeLclVar ,0,(GTK_UNOP|GTK_NOVALUE)) // store to local variable +GTNODE(STORE_LCL_FLD , GenTreeLclFld ,0,(GTK_UNOP|GTK_NOVALUE)) // store to a part of the variable GTNODE(LCL_VAR_ADDR , GenTreeLclVar ,0,GTK_LEAF) // address of local variable GTNODE(LCL_FLD_ADDR , GenTreeLclFld ,0,GTK_LEAF) // address of field in a non-primitive variable -GTNODE(STORE_LCL_VAR , GenTreeLclVar ,0,(GTK_UNOP|GTK_LOCAL|GTK_NOVALUE)) // store to local variable -GTNODE(STORE_LCL_FLD , GenTreeLclFld ,0,(GTK_UNOP|GTK_LOCAL|GTK_NOVALUE)) // store to field in a non-primitive variable + +//----------------------------------------------------------------------------- +// Leaf nodes (i.e. these nodes have no sub-operands): +//----------------------------------------------------------------------------- + GTNODE(CATCH_ARG , GenTree ,0,GTK_LEAF) // Exception object in a catch block GTNODE(LABEL , GenTree ,0,GTK_LEAF) // Jump-target GTNODE(FTN_ADDR , GenTreeFptrVal ,0,GTK_LEAF) // Address of a function @@ -34,10 +41,10 @@ GTNODE(RET_EXPR , GenTreeRetExpr ,0,GTK_LEAF|GTK_NOTLIR) // Place // Constant nodes: //----------------------------------------------------------------------------- -GTNODE(CNS_INT , GenTreeIntCon ,0,(GTK_LEAF|GTK_CONST)) -GTNODE(CNS_LNG , GenTreeLngCon ,0,(GTK_LEAF|GTK_CONST)) -GTNODE(CNS_DBL , GenTreeDblCon ,0,(GTK_LEAF|GTK_CONST)) -GTNODE(CNS_STR , GenTreeStrCon ,0,(GTK_LEAF|GTK_CONST)) +GTNODE(CNS_INT , GenTreeIntCon ,0,GTK_LEAF) +GTNODE(CNS_LNG , GenTreeLngCon ,0,GTK_LEAF) +GTNODE(CNS_DBL , GenTreeDblCon ,0,GTK_LEAF) +GTNODE(CNS_STR , GenTreeStrCon ,0,GTK_LEAF) //----------------------------------------------------------------------------- // Unary operators (1 operand): @@ -110,9 +117,9 @@ GTNODE(MOD , GenTreeOp ,0,GTK_BINOP) GTNODE(UDIV , GenTreeOp ,0,GTK_BINOP) GTNODE(UMOD , GenTreeOp ,0,GTK_BINOP) -GTNODE(OR , GenTreeOp ,1,(GTK_BINOP|GTK_LOGOP)) -GTNODE(XOR , GenTreeOp ,1,(GTK_BINOP|GTK_LOGOP)) -GTNODE(AND , GenTreeOp ,1,(GTK_BINOP|GTK_LOGOP)) +GTNODE(OR , GenTreeOp ,1,GTK_BINOP) +GTNODE(XOR , GenTreeOp ,1,GTK_BINOP) +GTNODE(AND , GenTreeOp ,1,GTK_BINOP) GTNODE(LSH , GenTreeOp ,0,GTK_BINOP) GTNODE(RSH , GenTreeOp ,0,GTK_BINOP) @@ -121,12 +128,12 @@ GTNODE(ROL , GenTreeOp ,0,GTK_BINOP) GTNODE(ROR , GenTreeOp ,0,GTK_BINOP) GTNODE(ASG , GenTreeOp ,0,(GTK_BINOP|GTK_NOTLIR)) -GTNODE(EQ , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) -GTNODE(NE , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) -GTNODE(LT , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) -GTNODE(LE , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) -GTNODE(GE , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) -GTNODE(GT , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) +GTNODE(EQ , GenTreeOp ,0,GTK_BINOP) +GTNODE(NE , GenTreeOp ,0,GTK_BINOP) +GTNODE(LT , GenTreeOp ,0,GTK_BINOP) +GTNODE(LE , GenTreeOp ,0,GTK_BINOP) +GTNODE(GE , GenTreeOp ,0,GTK_BINOP) +GTNODE(GT , GenTreeOp ,0,GTK_BINOP) // These are similar to GT_EQ/GT_NE but they generate "test" instead of "cmp" instructions. // Currently these are generated during lowering for code like ((x & y) eq|ne 0) only on @@ -135,8 +142,8 @@ GTNODE(GT , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) // codegen which emits a "test reg, reg" instruction, that would be more difficult to do // during lowering because the source operand is used twice so it has to be a lclvar. // Because of this there is no need to also add GT_TEST_LT/LE/GE/GT opers. -GTNODE(TEST_EQ , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) -GTNODE(TEST_NE , GenTreeOp ,0,(GTK_BINOP|GTK_RELOP)) +GTNODE(TEST_EQ , GenTreeOp ,0,GTK_BINOP) +GTNODE(TEST_NE , GenTreeOp ,0,GTK_BINOP) GTNODE(COMMA , GenTreeOp ,0,(GTK_BINOP|GTK_NOTLIR)) @@ -259,13 +266,6 @@ GTNODE(RETFILT , GenTreeOp ,0,(GTK_UNOP|GTK_NOVALUE)) // end GTNODE(END_LFIN , GenTreeVal ,0,(GTK_LEAF|GTK_NOVALUE)) // end locally-invoked finally #endif // !FEATURE_EH_FUNCLETS -//----------------------------------------------------------------------------- -// Nodes used for optimizations. -//----------------------------------------------------------------------------- - -GTNODE(PHI , GenTreePhi ,0,GTK_SPECIAL) // phi node for ssa. -GTNODE(PHI_ARG , GenTreePhiArg ,0,(GTK_LEAF|GTK_LOCAL)) // phi(phiarg, phiarg, phiarg) - //----------------------------------------------------------------------------- // Nodes used by Lower to generate a closer CPU representation of other nodes //----------------------------------------------------------------------------- diff --git a/src/coreclr/jit/hwintrinsic.cpp b/src/coreclr/jit/hwintrinsic.cpp index 41eb6605856a8..dfde343fe52cb 100644 --- a/src/coreclr/jit/hwintrinsic.cpp +++ b/src/coreclr/jit/hwintrinsic.cpp @@ -283,7 +283,7 @@ NamedIntrinsic HWIntrinsicInfo::lookupId(Compiler* comp, return NI_Illegal; } - bool isIsaSupported = comp->compHWIntrinsicDependsOn(isa) && comp->compSupportsHWIntrinsic(isa); + bool isIsaSupported = comp->compSupportsHWIntrinsic(isa); if ((strcmp(methodName, "get_IsSupported") == 0) || (strcmp(methodName, "get_IsHardwareAccelerated") == 0)) { @@ -555,7 +555,7 @@ GenTree* Compiler::addRangeCheckForHWIntrinsic(GenTree* immOp, int immLowerBound // true iff the given instruction set is enabled via configuration (environment variables, etc.). bool Compiler::compSupportsHWIntrinsic(CORINFO_InstructionSet isa) { - return JitConfig.EnableHWIntrinsic() && (featureSIMD || HWIntrinsicInfo::isScalarIsa(isa)) && + return compHWIntrinsicDependsOn(isa) && (featureSIMD || HWIntrinsicInfo::isScalarIsa(isa)) && ( #ifdef DEBUG JitConfig.EnableIncompleteISAClass() || diff --git a/src/coreclr/jit/hwintrinsicarm64.cpp b/src/coreclr/jit/hwintrinsicarm64.cpp index 69902ac7f30da..0c1b01e64ed93 100644 --- a/src/coreclr/jit/hwintrinsicarm64.cpp +++ b/src/coreclr/jit/hwintrinsicarm64.cpp @@ -332,7 +332,7 @@ GenTree* Compiler::impSpecialIntrinsic(NamedIntrinsic intrinsic, assert(numArgs >= 0); - const var_types simdBaseType = JitType2PreciseVarType(simdBaseJitType); + var_types simdBaseType = JitType2PreciseVarType(simdBaseJitType); assert(varTypeIsArithmetic(simdBaseType)); GenTree* retNode = nullptr; @@ -652,6 +652,189 @@ GenTree* Compiler::impSpecialIntrinsic(NamedIntrinsic intrinsic, break; } + case NI_Vector64_ExtractMostSignificantBits: + case NI_Vector128_ExtractMostSignificantBits: + { + assert(sig->numArgs == 1); + + // ARM64 doesn't have a single instruction that performs the behavior so we'll emulate it instead. + // To do this, we effectively perform the following steps: + // 1. tmp = input & 0x80 ; and the input to clear all but the most significant bit + // 2. tmp = tmp >> index ; right shift each element by its index + // 3. tmp = sum(tmp) ; sum the elements together + + // For byte/sbyte, we also need to handle the fact that we can only shift by up to 8 + // but for Vector128, we have 16 elements to handle. In that scenario, we will simply + // extract both scalars, and combine them via: (upper << 8) | lower + + var_types simdType = getSIMDTypeForSize(simdSize); + + op1 = impSIMDPopStack(simdType); + + GenTree* vectorCreateOp1 = nullptr; + GenTree* vectorCreateOp2 = nullptr; + CorInfoType vectorCreateType = varTypeIsUnsigned(simdBaseType) ? CORINFO_TYPE_ULONG : CORINFO_TYPE_LONG; + + switch (simdBaseType) + { + case TYP_BYTE: + case TYP_UBYTE: + { + op2 = gtNewIconNode(0x80); + vectorCreateOp1 = gtNewLconNode(0x00FFFEFDFCFBFAF9); + + if (simdSize == 16) + { + vectorCreateOp2 = gtNewLconNode(0x00FFFEFDFCFBFAF9); + } + break; + } + + case TYP_SHORT: + case TYP_USHORT: + { + op2 = gtNewIconNode(0x8000); + vectorCreateOp1 = gtNewLconNode(0xFFF4FFF3FFF2FFF1); + + if (simdSize == 16) + { + vectorCreateOp2 = gtNewLconNode(0xFFF8FFF7FFF6FFF5); + } + break; + } + + case TYP_INT: + case TYP_UINT: + { + op2 = gtNewIconNode(0x80000000); + vectorCreateOp1 = gtNewLconNode(0xFFFFFFE2FFFFFFE1); + + if (simdSize == 16) + { + vectorCreateOp2 = gtNewLconNode(0xFFFFFFE4FFFFFFE3); + } + break; + } + + case TYP_LONG: + case TYP_ULONG: + { + op2 = gtNewLconNode(0x8000000000000000); + vectorCreateOp1 = gtNewLconNode(0xFFFFFFFFFFFFFFC1); + + if (simdSize == 16) + { + vectorCreateOp2 = gtNewLconNode(0xFFFFFFFFFFFFFFC2); + } + break; + } + + case TYP_FLOAT: + { + op2 = gtNewIconNode(0x80000000); + simdBaseType = TYP_INT; + simdBaseJitType = CORINFO_TYPE_INT; + vectorCreateOp1 = gtNewLconNode(0xFFFFFFE2FFFFFFE1); + + if (simdSize == 16) + { + vectorCreateOp2 = gtNewLconNode(0xFFFFFFE4FFFFFFE3); + } + break; + } + + case TYP_DOUBLE: + { + op2 = gtNewLconNode(0x8000000000000000); + simdBaseType = TYP_LONG; + simdBaseJitType = CORINFO_TYPE_LONG; + vectorCreateOp1 = gtNewLconNode(0xFFFFFFFFFFFFFFC1); + + if (simdSize == 16) + { + vectorCreateOp2 = gtNewLconNode(0xFFFFFFFFFFFFFFC2); + } + break; + } + + default: + { + unreached(); + } + } + + if (simdSize == 16) + { + op3 = gtNewSimdHWIntrinsicNode(simdType, vectorCreateOp1, vectorCreateOp2, NI_Vector128_Create, + vectorCreateType, simdSize); + } + else + { + op3 = + gtNewSimdHWIntrinsicNode(simdType, vectorCreateOp1, NI_Vector64_Create, vectorCreateType, simdSize); + } + + op1 = gtNewSimdHWIntrinsicNode(simdType, op1, op2, NI_AdvSimd_And, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + + op1 = gtNewSimdHWIntrinsicNode(simdType, op1, op3, NI_AdvSimd_ShiftLogical, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + + if (varTypeIsByte(simdBaseType) && (simdSize == 16)) + { + CORINFO_CLASS_HANDLE clsHnd = gtGetStructHandleForSIMD(simdType, simdBaseJitType); + + op1 = impCloneExpr(op1, &op2, clsHnd, (unsigned)CHECK_SPILL_ALL, + nullptr DEBUGARG("Clone op1 for vector extractmostsignificantbits")); + + op1 = gtNewSimdHWIntrinsicNode(TYP_SIMD8, op1, NI_Vector128_GetLower, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + op1 = gtNewSimdHWIntrinsicNode(TYP_SIMD8, op1, NI_AdvSimd_Arm64_AddAcross, simdBaseJitType, 8, + /* isSimdAsHWIntrinsic */ false); + op1 = gtNewSimdHWIntrinsicNode(simdBaseType, op1, NI_Vector64_ToScalar, simdBaseJitType, 8, + /* isSimdAsHWIntrinsic */ false); + op1 = gtNewCastNode(TYP_INT, op1, /* isUnsigned */ true, simdBaseType); + + GenTree* zero = gtNewSimdHWIntrinsicNode(retType, NI_Vector128_get_Zero, simdBaseJitType, simdSize); + ssize_t index = 8 / genTypeSize(simdBaseType); + + op2 = gtNewSimdHWIntrinsicNode(simdType, op2, zero, gtNewIconNode(index), NI_AdvSimd_ExtractVector128, + simdBaseJitType, simdSize, /* isSimdAsHWIntrinsic */ false); + op2 = gtNewSimdHWIntrinsicNode(TYP_SIMD8, op2, NI_Vector128_GetLower, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + op2 = gtNewSimdHWIntrinsicNode(TYP_SIMD8, op2, NI_AdvSimd_Arm64_AddAcross, simdBaseJitType, 8, + /* isSimdAsHWIntrinsic */ false); + op2 = gtNewSimdHWIntrinsicNode(simdBaseType, op2, NI_Vector64_ToScalar, simdBaseJitType, 8, + /* isSimdAsHWIntrinsic */ false); + op2 = gtNewCastNode(TYP_INT, op2, /* isUnsigned */ true, simdBaseType); + + op2 = gtNewOperNode(GT_LSH, TYP_INT, op2, gtNewIconNode(8)); + retNode = gtNewOperNode(GT_OR, TYP_INT, op1, op2); + } + else + { + if (!varTypeIsLong(simdBaseType)) + { + op1 = gtNewSimdHWIntrinsicNode(TYP_SIMD8, op1, NI_AdvSimd_Arm64_AddAcross, simdBaseJitType, + simdSize, /* isSimdAsHWIntrinsic */ false); + } + else if (simdSize == 16) + { + op1 = gtNewSimdHWIntrinsicNode(TYP_SIMD8, op1, NI_AdvSimd_Arm64_AddPairwiseScalar, simdBaseJitType, + simdSize, /* isSimdAsHWIntrinsic */ false); + } + + retNode = gtNewSimdHWIntrinsicNode(simdBaseType, op1, NI_Vector64_ToScalar, simdBaseJitType, 8, + /* isSimdAsHWIntrinsic */ false); + + if ((simdBaseType != TYP_INT) && (simdBaseType != TYP_UINT)) + { + retNode = gtNewCastNode(TYP_INT, retNode, /* isUnsigned */ true, simdBaseType); + } + } + break; + } + case NI_Vector64_Floor: case NI_Vector128_Floor: { @@ -874,6 +1057,164 @@ GenTree* Compiler::impSpecialIntrinsic(NamedIntrinsic intrinsic, break; } + case NI_Vector64_Load: + case NI_Vector128_Load: + { + assert(sig->numArgs == 1); + + op1 = impPopStack().val; + + if (op1->OperIs(GT_CAST)) + { + // Although the API specifies a pointer, if what we have is a BYREF, that's what + // we really want, so throw away the cast. + if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) + { + op1 = op1->gtGetOp1(); + } + } + + NamedIntrinsic loadIntrinsic = NI_Illegal; + + if (simdSize == 16) + { + loadIntrinsic = NI_AdvSimd_LoadVector128; + } + else + { + loadIntrinsic = NI_AdvSimd_LoadVector64; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, loadIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector64_LoadAligned: + case NI_Vector128_LoadAligned: + { + assert(sig->numArgs == 1); + + if (!opts.MinOpts()) + { + // ARM64 doesn't have aligned loads, but aligned loads are only validated to be + // aligned during minopts, so only skip the intrinsic handling if we're minopts + break; + } + + op1 = impPopStack().val; + + if (op1->OperIs(GT_CAST)) + { + // Although the API specifies a pointer, if what we have is a BYREF, that's what + // we really want, so throw away the cast. + if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) + { + op1 = op1->gtGetOp1(); + } + } + + NamedIntrinsic loadIntrinsic = NI_Illegal; + + if (simdSize == 16) + { + loadIntrinsic = NI_AdvSimd_LoadVector128; + } + else + { + loadIntrinsic = NI_AdvSimd_LoadVector64; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, loadIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector64_LoadAlignedNonTemporal: + case NI_Vector128_LoadAlignedNonTemporal: + { + assert(sig->numArgs == 1); + + if (!opts.MinOpts()) + { + // ARM64 doesn't have aligned loads, but aligned loads are only validated to be + // aligned during minopts, so only skip the intrinsic handling if we're minopts + break; + } + + op1 = impPopStack().val; + + if (op1->OperIs(GT_CAST)) + { + // Although the API specifies a pointer, if what we have is a BYREF, that's what + // we really want, so throw away the cast. + if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) + { + op1 = op1->gtGetOp1(); + } + } + + // ARM64 has non-temporal loads (LDNP) but we don't currently support them + + NamedIntrinsic loadIntrinsic = NI_Illegal; + + if (simdSize == 16) + { + loadIntrinsic = NI_AdvSimd_LoadVector128; + } + else + { + loadIntrinsic = NI_AdvSimd_LoadVector64; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, loadIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector64_LoadUnsafe: + case NI_Vector128_LoadUnsafe: + { + if (sig->numArgs == 2) + { + op2 = impPopStack().val; + } + else + { + assert(sig->numArgs == 1); + } + + op1 = impPopStack().val; + + if (op1->OperIs(GT_CAST)) + { + // Although the API specifies a pointer, if what we have is a BYREF, that's what + // we really want, so throw away the cast. + if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) + { + op1 = op1->gtGetOp1(); + } + } + + if (sig->numArgs == 2) + { + op3 = gtNewIconNode(genTypeSize(simdBaseType), op2->TypeGet()); + op2 = gtNewOperNode(GT_MUL, op2->TypeGet(), op2, op3); + op1 = gtNewOperNode(GT_ADD, op1->TypeGet(), op1, op2); + } + + NamedIntrinsic loadIntrinsic = NI_Illegal; + + if (simdSize == 16) + { + loadIntrinsic = NI_AdvSimd_LoadVector128; + } + else + { + loadIntrinsic = NI_AdvSimd_LoadVector64; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, loadIntrinsic, simdBaseJitType, simdSize); + break; + } + case NI_Vector64_Max: case NI_Vector128_Max: { @@ -1001,6 +1342,45 @@ GenTree* Compiler::impSpecialIntrinsic(NamedIntrinsic intrinsic, break; } + case NI_Vector64_ShiftLeft: + case NI_Vector128_ShiftLeft: + { + assert(sig->numArgs == 2); + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + retNode = gtNewSimdBinOpNode(GT_LSH, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + break; + } + + case NI_Vector64_ShiftRightArithmetic: + case NI_Vector128_ShiftRightArithmetic: + { + assert(sig->numArgs == 2); + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + retNode = gtNewSimdBinOpNode(GT_RSH, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + break; + } + + case NI_Vector64_ShiftRightLogical: + case NI_Vector128_ShiftRightLogical: + { + assert(sig->numArgs == 2); + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + retNode = gtNewSimdBinOpNode(GT_RSZ, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + break; + } + case NI_Vector64_Sqrt: case NI_Vector128_Sqrt: { @@ -1014,6 +1394,94 @@ GenTree* Compiler::impSpecialIntrinsic(NamedIntrinsic intrinsic, break; } + case NI_Vector64_Store: + case NI_Vector128_Store: + { + assert(sig->numArgs == 2); + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + retNode = gtNewSimdHWIntrinsicNode(retType, op2, op1, NI_AdvSimd_Store, simdBaseJitType, simdSize); + break; + } + + case NI_Vector64_StoreAligned: + case NI_Vector128_StoreAligned: + { + assert(sig->numArgs == 2); + + if (!opts.MinOpts()) + { + // ARM64 doesn't have aligned stores, but aligned stores are only validated to be + // aligned during minopts, so only skip the intrinsic handling if we're minopts + break; + } + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + retNode = gtNewSimdHWIntrinsicNode(retType, op2, op1, NI_AdvSimd_Store, simdBaseJitType, simdSize); + break; + } + + case NI_Vector64_StoreAlignedNonTemporal: + case NI_Vector128_StoreAlignedNonTemporal: + { + assert(sig->numArgs == 2); + + if (!opts.MinOpts()) + { + // ARM64 doesn't have aligned stores, but aligned stores are only validated to be + // aligned during minopts, so only skip the intrinsic handling if we're minopts + break; + } + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + // ARM64 has non-temporal stores (STNP) but we don't currently support them + + retNode = gtNewSimdHWIntrinsicNode(retType, op2, op1, NI_AdvSimd_Store, simdBaseJitType, simdSize); + break; + } + + case NI_Vector64_StoreUnsafe: + case NI_Vector128_StoreUnsafe: + { + if (sig->numArgs == 3) + { + op3 = impPopStack().val; + } + else + { + assert(sig->numArgs == 2); + } + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + if (sig->numArgs == 3) + { + op3 = gtNewIconNode(genTypeSize(simdBaseType), op2->TypeGet()); + op2 = gtNewOperNode(GT_MUL, op2->TypeGet(), op2, op3); + op2 = gtNewOperNode(GT_ADD, op1->TypeGet(), op1, op2); + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op2, op1, NI_AdvSimd_Store, simdBaseJitType, simdSize); + break; + } + + case NI_Vector64_Sum: + case NI_Vector128_Sum: + { + assert(sig->numArgs == 1); + + op1 = impSIMDPopStack(retType); + retNode = gtNewSimdSumNode(retType, op1, simdBaseJitType, simdSize, /* isSimdAsHWIntrinsic */ false); + break; + } + case NI_Vector64_WidenLower: case NI_Vector128_WidenLower: { diff --git a/src/coreclr/jit/hwintrinsiccodegenarm64.cpp b/src/coreclr/jit/hwintrinsiccodegenarm64.cpp index 706b988f049e5..e4b9a1326680c 100644 --- a/src/coreclr/jit/hwintrinsiccodegenarm64.cpp +++ b/src/coreclr/jit/hwintrinsiccodegenarm64.cpp @@ -496,6 +496,29 @@ void CodeGen::genHWIntrinsic(GenTreeHWIntrinsic* node) GetEmitter()->emitIns_R_R_R(ins, emitSize, targetReg, op1Reg, op2Reg, opt); break; + case NI_AdvSimd_CompareEqual: + case NI_AdvSimd_Arm64_CompareEqual: + case NI_AdvSimd_Arm64_CompareEqualScalar: + if (intrin.op1->isContained()) + { + assert(HWIntrinsicInfo::SupportsContainment(intrin.id)); + assert(intrin.op1->IsVectorZero()); + + GetEmitter()->emitIns_R_R(ins, emitSize, targetReg, op2Reg, opt); + } + else if (intrin.op2->isContained()) + { + assert(HWIntrinsicInfo::SupportsContainment(intrin.id)); + assert(intrin.op2->IsVectorZero()); + + GetEmitter()->emitIns_R_R(ins, emitSize, targetReg, op1Reg, opt); + } + else + { + GetEmitter()->emitIns_R_R_R(ins, emitSize, targetReg, op1Reg, op2Reg, opt); + } + break; + case NI_AdvSimd_AbsoluteCompareLessThan: case NI_AdvSimd_AbsoluteCompareLessThanOrEqual: case NI_AdvSimd_CompareLessThan: diff --git a/src/coreclr/jit/hwintrinsiclistarm64.h b/src/coreclr/jit/hwintrinsiclistarm64.h index 9360ea2a4c369..e119a38948a05 100644 --- a/src/coreclr/jit/hwintrinsiclistarm64.h +++ b/src/coreclr/jit/hwintrinsiclistarm64.h @@ -46,6 +46,7 @@ HARDWARE_INTRINSIC(Vector64, Dot, HARDWARE_INTRINSIC(Vector64, Equals, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, EqualsAll, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, EqualsAny, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, ExtractMostSignificantBits, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, Floor, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, get_AllBitsSet, 8, 0, {INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni}, HW_Category_Helper, HW_Flag_SpecialCodeGen|HW_Flag_SpecialImport) HARDWARE_INTRINSIC(Vector64, get_Count, 8, 0, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_NoCodeGen|HW_Flag_SpecialImport) @@ -63,6 +64,10 @@ HARDWARE_INTRINSIC(Vector64, LessThanAny, HARDWARE_INTRINSIC(Vector64, LessThanOrEqual, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, LessThanOrEqualAll, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, LessThanOrEqualAny, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, Load, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, LoadAligned, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, LoadAlignedNonTemporal, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, LoadUnsafe, 8, -1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, Max, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, Min, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, Multiply, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) @@ -81,8 +86,16 @@ HARDWARE_INTRINSIC(Vector64, op_OnesComplement, HARDWARE_INTRINSIC(Vector64, op_Subtraction, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, op_UnaryNegation, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, op_UnaryPlus, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) -HARDWARE_INTRINSIC(Vector64, Subtract, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, ShiftLeft, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, ShiftRightArithmetic, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, ShiftRightLogical, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, Sqrt, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, Store, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, StoreAligned, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, StoreAlignedNonTemporal, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, StoreUnsafe, 8, -1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, Subtract, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector64, Sum, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector64, ToScalar, 8, 1, {INS_smov, INS_umov, INS_smov, INS_umov, INS_smov, INS_umov, INS_umov, INS_umov, INS_dup, INS_dup}, HW_Category_SIMD, HW_Flag_BaseTypeFromFirstArg|HW_Flag_SIMDScalar|HW_Flag_SpecialCodeGen) HARDWARE_INTRINSIC(Vector64, ToVector128, 8, 1, {INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov}, HW_Category_SIMD, HW_Flag_SpecialCodeGen) HARDWARE_INTRINSIC(Vector64, ToVector128Unsafe, 8, 1, {INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov, INS_mov}, HW_Category_SIMD, HW_Flag_SpecialCodeGen) @@ -131,6 +144,7 @@ HARDWARE_INTRINSIC(Vector128, Dot, HARDWARE_INTRINSIC(Vector128, Equals, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, EqualsAll, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, EqualsAny, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, ExtractMostSignificantBits, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Floor, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, get_AllBitsSet, 16, 0, {INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni, INS_mvni}, HW_Category_Helper, HW_Flag_SpecialCodeGen|HW_Flag_SpecialImport) HARDWARE_INTRINSIC(Vector128, get_Count, 16, 0, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_NoCodeGen|HW_Flag_SpecialImport) @@ -150,6 +164,10 @@ HARDWARE_INTRINSIC(Vector128, LessThanAny, HARDWARE_INTRINSIC(Vector128, LessThanOrEqual, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, LessThanOrEqualAll, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, LessThanOrEqualAny, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, Load, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, LoadAligned, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, LoadAlignedNonTemporal, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, LoadUnsafe, 16, -1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Max, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Min, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Multiply, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) @@ -168,8 +186,16 @@ HARDWARE_INTRINSIC(Vector128, op_OnesComplement, HARDWARE_INTRINSIC(Vector128, op_Subtraction, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, op_UnaryNegation, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, op_UnaryPlus, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) -HARDWARE_INTRINSIC(Vector128, Subtract, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, ShiftLeft, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, ShiftRightArithmetic, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, ShiftRightLogical, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Sqrt, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, Store, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, StoreAligned, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, StoreAlignedNonTemporal, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, StoreUnsafe, 16, -1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, Subtract, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, Sum, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, ToScalar, 16, 1, {INS_smov, INS_umov, INS_smov, INS_umov, INS_smov, INS_umov, INS_umov, INS_umov, INS_dup, INS_dup}, HW_Category_SIMD, HW_Flag_BaseTypeFromFirstArg|HW_Flag_SIMDScalar|HW_Flag_SpecialCodeGen) HARDWARE_INTRINSIC(Vector128, WidenLower, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen|HW_Flag_BaseTypeFromFirstArg) HARDWARE_INTRINSIC(Vector128, WidenUpper, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen|HW_Flag_BaseTypeFromFirstArg) @@ -214,7 +240,7 @@ HARDWARE_INTRINSIC(AdvSimd, BitwiseClear, HARDWARE_INTRINSIC(AdvSimd, BitwiseSelect, -1, 3, {INS_bsl, INS_bsl, INS_bsl, INS_bsl, INS_bsl, INS_bsl, INS_bsl, INS_bsl, INS_bsl, INS_bsl}, HW_Category_SIMD, HW_Flag_SpecialCodeGen) HARDWARE_INTRINSIC(AdvSimd, Ceiling, -1, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_frintp, INS_invalid}, HW_Category_SIMD, HW_Flag_NoFlag) HARDWARE_INTRINSIC(AdvSimd, CeilingScalar, 8, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_frintp, INS_frintp}, HW_Category_SIMD, HW_Flag_SIMDScalar) -HARDWARE_INTRINSIC(AdvSimd, CompareEqual, -1, 2, {INS_cmeq, INS_cmeq, INS_cmeq, INS_cmeq, INS_cmeq, INS_cmeq, INS_invalid, INS_invalid, INS_fcmeq, INS_invalid}, HW_Category_SIMD, HW_Flag_Commutative) +HARDWARE_INTRINSIC(AdvSimd, CompareEqual, -1, 2, {INS_cmeq, INS_cmeq, INS_cmeq, INS_cmeq, INS_cmeq, INS_cmeq, INS_invalid, INS_invalid, INS_fcmeq, INS_invalid}, HW_Category_SIMD, HW_Flag_Commutative|HW_Flag_SpecialCodeGen|HW_Flag_SupportsContainment) HARDWARE_INTRINSIC(AdvSimd, CompareGreaterThan, -1, 2, {INS_cmgt, INS_cmhi, INS_cmgt, INS_cmhi, INS_cmgt, INS_cmhi, INS_invalid, INS_invalid, INS_fcmgt, INS_invalid}, HW_Category_SIMD, HW_Flag_NoFlag) HARDWARE_INTRINSIC(AdvSimd, CompareGreaterThanOrEqual, -1, 2, {INS_cmge, INS_cmhs, INS_cmge, INS_cmhs, INS_cmge, INS_cmhs, INS_invalid, INS_invalid, INS_fcmge, INS_invalid}, HW_Category_SIMD, HW_Flag_NoFlag) HARDWARE_INTRINSIC(AdvSimd, CompareLessThan, -1, 2, {INS_cmgt, INS_cmhi, INS_cmgt, INS_cmhi, INS_cmgt, INS_cmhi, INS_invalid, INS_invalid, INS_fcmgt, INS_invalid}, HW_Category_SIMD, HW_Flag_SpecialCodeGen) @@ -466,8 +492,8 @@ HARDWARE_INTRINSIC(AdvSimd_Arm64, AddPairwiseScalar, HARDWARE_INTRINSIC(AdvSimd_Arm64, AddSaturate, -1, 2, {INS_suqadd, INS_usqadd, INS_suqadd, INS_usqadd, INS_suqadd, INS_usqadd, INS_suqadd, INS_usqadd, INS_invalid, INS_invalid}, HW_Category_SIMD, HW_Flag_BaseTypeFromFirstArg|HW_Flag_HasRMWSemantics) HARDWARE_INTRINSIC(AdvSimd_Arm64, AddSaturateScalar, 8, 2, {INS_sqadd, INS_uqadd, INS_sqadd, INS_uqadd, INS_sqadd, INS_uqadd, INS_suqadd, INS_usqadd, INS_invalid, INS_invalid}, HW_Category_SIMD, HW_Flag_BaseTypeFromFirstArg|HW_Flag_HasRMWSemantics|HW_Flag_SIMDScalar|HW_Flag_SpecialCodeGen) HARDWARE_INTRINSIC(AdvSimd_Arm64, Ceiling, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_frintp}, HW_Category_SIMD, HW_Flag_NoFlag) -HARDWARE_INTRINSIC(AdvSimd_Arm64, CompareEqual, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_cmeq, INS_cmeq, INS_invalid, INS_fcmeq}, HW_Category_SIMD, HW_Flag_Commutative) -HARDWARE_INTRINSIC(AdvSimd_Arm64, CompareEqualScalar, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_cmeq, INS_cmeq, INS_fcmeq, INS_fcmeq}, HW_Category_SIMD, HW_Flag_Commutative|HW_Flag_SIMDScalar) +HARDWARE_INTRINSIC(AdvSimd_Arm64, CompareEqual, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_cmeq, INS_cmeq, INS_invalid, INS_fcmeq}, HW_Category_SIMD, HW_Flag_Commutative|HW_Flag_SpecialCodeGen|HW_Flag_SupportsContainment) +HARDWARE_INTRINSIC(AdvSimd_Arm64, CompareEqualScalar, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_cmeq, INS_cmeq, INS_fcmeq, INS_fcmeq}, HW_Category_SIMD, HW_Flag_Commutative|HW_Flag_SIMDScalar|HW_Flag_SpecialCodeGen|HW_Flag_SupportsContainment) HARDWARE_INTRINSIC(AdvSimd_Arm64, CompareGreaterThan, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_cmgt, INS_cmhi, INS_invalid, INS_fcmgt}, HW_Category_SIMD, HW_Flag_NoFlag) HARDWARE_INTRINSIC(AdvSimd_Arm64, CompareGreaterThanOrEqual, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_cmge, INS_cmhs, INS_invalid, INS_fcmge}, HW_Category_SIMD, HW_Flag_NoFlag) HARDWARE_INTRINSIC(AdvSimd_Arm64, CompareGreaterThanOrEqualScalar, 8, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_cmge, INS_cmhs, INS_fcmge, INS_fcmge}, HW_Category_SIMD, HW_Flag_SIMDScalar) diff --git a/src/coreclr/jit/hwintrinsiclistxarch.h b/src/coreclr/jit/hwintrinsiclistxarch.h index 827a5a8686f3c..95ab714ae6334 100644 --- a/src/coreclr/jit/hwintrinsiclistxarch.h +++ b/src/coreclr/jit/hwintrinsiclistxarch.h @@ -63,6 +63,7 @@ HARDWARE_INTRINSIC(Vector128, Dot, HARDWARE_INTRINSIC(Vector128, Equals, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, EqualsAll, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, EqualsAny, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, ExtractMostSignificantBits, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Floor, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, get_AllBitsSet, 16, 0, {INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_cmpps, INS_cmpps}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoContainment|HW_Flag_NoRMWSemantics) HARDWARE_INTRINSIC(Vector128, get_Count, 16, 0, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) @@ -80,6 +81,10 @@ HARDWARE_INTRINSIC(Vector128, LessThanAny, HARDWARE_INTRINSIC(Vector128, LessThanOrEqual, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, LessThanOrEqualAll, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, LessThanOrEqualAny, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, Load, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, LoadAligned, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, LoadAlignedNonTemporal, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, LoadUnsafe, 16, -1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Max, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Min, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Multiply, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) @@ -98,8 +103,16 @@ HARDWARE_INTRINSIC(Vector128, op_OnesComplement, HARDWARE_INTRINSIC(Vector128, op_Subtraction, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, op_UnaryNegation, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, op_UnaryPlus, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) -HARDWARE_INTRINSIC(Vector128, Subtract, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, ShiftLeft, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, ShiftRightArithmetic, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, ShiftRightLogical, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, Sqrt, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, Store, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, StoreAligned, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, StoreAlignedNonTemporal, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, StoreUnsafe, 16, -1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, Subtract, 16, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector128, Sum, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector128, ToScalar, 16, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_movss, INS_movsdsse2}, HW_Category_SimpleSIMD, HW_Flag_SpecialImport|HW_Flag_SpecialCodeGen|HW_Flag_BaseTypeFromFirstArg|HW_Flag_NoRMWSemantics) HARDWARE_INTRINSIC(Vector128, ToVector256, 16, 1, {INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movups, INS_movupd}, HW_Category_SimpleSIMD, HW_Flag_SpecialImport|HW_Flag_SpecialCodeGen|HW_Flag_BaseTypeFromFirstArg|HW_Flag_NoRMWSemantics) HARDWARE_INTRINSIC(Vector128, ToVector256Unsafe, 16, 1, {INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movdqu, INS_movups, INS_movupd}, HW_Category_SimpleSIMD, HW_Flag_SpecialImport|HW_Flag_SpecialCodeGen|HW_Flag_BaseTypeFromFirstArg|HW_Flag_NoRMWSemantics) @@ -146,6 +159,7 @@ HARDWARE_INTRINSIC(Vector256, Dot, HARDWARE_INTRINSIC(Vector256, Equals, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, EqualsAll, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, EqualsAny, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, ExtractMostSignificantBits, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, Floor, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, get_AllBitsSet, 32, 0, {INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_pcmpeqd, INS_cmpps, INS_cmpps}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoContainment|HW_Flag_NoRMWSemantics) HARDWARE_INTRINSIC(Vector256, get_Count, 32, 0, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) @@ -164,6 +178,10 @@ HARDWARE_INTRINSIC(Vector256, LessThanAny, HARDWARE_INTRINSIC(Vector256, LessThanOrEqual, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, LessThanOrEqualAll, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, LessThanOrEqualAny, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, Load, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, LoadAligned, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, LoadAlignedNonTemporal, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, LoadUnsafe, 32, -1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, Max, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, Min, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, Multiply, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) @@ -182,8 +200,16 @@ HARDWARE_INTRINSIC(Vector256, op_OnesComplement, HARDWARE_INTRINSIC(Vector256, op_Subtraction, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, op_UnaryNegation, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, op_UnaryPlus, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) -HARDWARE_INTRINSIC(Vector256, Subtract, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, ShiftLeft, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, ShiftRightArithmetic, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, ShiftRightLogical, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, Sqrt, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, Store, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, StoreAligned, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, StoreAlignedNonTemporal, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, StoreUnsafe, 32, -1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, Subtract, 32, 2, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) +HARDWARE_INTRINSIC(Vector256, Sum, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen) HARDWARE_INTRINSIC(Vector256, ToScalar, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_movss, INS_movsdsse2}, HW_Category_SimpleSIMD, HW_Flag_SpecialImport|HW_Flag_SpecialCodeGen|HW_Flag_BaseTypeFromFirstArg|HW_Flag_NoRMWSemantics) HARDWARE_INTRINSIC(Vector256, WidenLower, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen|HW_Flag_BaseTypeFromFirstArg) HARDWARE_INTRINSIC(Vector256, WidenUpper, 32, 1, {INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid, INS_invalid}, HW_Category_Helper, HW_Flag_SpecialImport|HW_Flag_NoCodeGen|HW_Flag_BaseTypeFromFirstArg) diff --git a/src/coreclr/jit/hwintrinsicxarch.cpp b/src/coreclr/jit/hwintrinsicxarch.cpp index a0eceba4a8a0f..e6f499588c528 100644 --- a/src/coreclr/jit/hwintrinsicxarch.cpp +++ b/src/coreclr/jit/hwintrinsicxarch.cpp @@ -1035,6 +1035,39 @@ GenTree* Compiler::impBaseIntrinsic(NamedIntrinsic intrinsic, break; } + case NI_Vector128_ExtractMostSignificantBits: + case NI_Vector256_ExtractMostSignificantBits: + { + assert(sig->numArgs == 1); + + if ((simdSize != 32) || varTypeIsFloating(simdBaseType) || compExactlyDependsOn(InstructionSet_AVX2)) + { + var_types simdType = getSIMDTypeForSize(simdSize); + + op1 = impSIMDPopStack(simdType); + + NamedIntrinsic moveMaskIntrinsic = NI_Illegal; + + if (simdBaseType == TYP_FLOAT) + { + moveMaskIntrinsic = (simdSize == 32) ? NI_AVX_MoveMask : NI_SSE_MoveMask; + } + else if (simdBaseType == TYP_DOUBLE) + { + moveMaskIntrinsic = (simdSize == 32) ? NI_AVX_MoveMask : NI_SSE2_MoveMask; + } + else + { + moveMaskIntrinsic = (simdSize == 32) ? NI_AVX2_MoveMask : NI_SSE2_MoveMask; + simdBaseJitType = varTypeIsUnsigned(simdBaseType) ? CORINFO_TYPE_UBYTE : CORINFO_TYPE_BYTE; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, moveMaskIntrinsic, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + } + break; + } + case NI_Vector128_Floor: case NI_Vector256_Floor: { @@ -1326,6 +1359,183 @@ GenTree* Compiler::impBaseIntrinsic(NamedIntrinsic intrinsic, break; } + case NI_Vector128_Load: + case NI_Vector256_Load: + { + assert(sig->numArgs == 1); + + op1 = impPopStack().val; + + if (op1->OperIs(GT_CAST)) + { + // Although the API specifies a pointer, if what we have is a BYREF, that's what + // we really want, so throw away the cast. + if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) + { + op1 = op1->gtGetOp1(); + } + } + + NamedIntrinsic loadIntrinsic = NI_Illegal; + + if (simdSize == 32) + { + loadIntrinsic = NI_AVX_LoadVector256; + } + else if (simdBaseType != TYP_FLOAT) + { + loadIntrinsic = NI_SSE2_LoadVector128; + } + else + { + loadIntrinsic = NI_SSE_LoadVector128; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, loadIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector128_LoadAligned: + case NI_Vector256_LoadAligned: + { + assert(sig->numArgs == 1); + + op1 = impPopStack().val; + + if (op1->OperIs(GT_CAST)) + { + // Although the API specifies a pointer, if what we have is a BYREF, that's what + // we really want, so throw away the cast. + if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) + { + op1 = op1->gtGetOp1(); + } + } + + NamedIntrinsic loadIntrinsic = NI_Illegal; + + if (simdSize == 32) + { + loadIntrinsic = NI_AVX_LoadAlignedVector256; + } + else if (simdBaseType != TYP_FLOAT) + { + loadIntrinsic = NI_SSE2_LoadAlignedVector128; + } + else + { + loadIntrinsic = NI_SSE_LoadAlignedVector128; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, loadIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector128_LoadAlignedNonTemporal: + case NI_Vector256_LoadAlignedNonTemporal: + { + assert(sig->numArgs == 1); + + if ((simdSize == 16) && !compOpportunisticallyDependsOn(InstructionSet_SSE41)) + { + // Vector128 requires at least SSE4.1 + break; + } + else if ((simdSize == 32) && !compOpportunisticallyDependsOn(InstructionSet_AVX2)) + { + // Vector256 requires at least AVX2 + break; + } + + op1 = impPopStack().val; + + if (op1->OperIs(GT_CAST)) + { + // Although the API specifies a pointer, if what we have is a BYREF, that's what + // we really want, so throw away the cast. + if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) + { + op1 = op1->gtGetOp1(); + } + } + + NamedIntrinsic loadIntrinsic = NI_Illegal; + + if (simdSize == 32) + { + loadIntrinsic = NI_AVX2_LoadAlignedVector256NonTemporal; + } + else + { + loadIntrinsic = NI_SSE41_LoadAlignedVector128NonTemporal; + } + + // float and double don't have actual instructions for non-temporal loads + // so we'll just use the equivalent integer instruction instead. + + if (simdBaseType == TYP_FLOAT) + { + simdBaseJitType = CORINFO_TYPE_INT; + } + else if (simdBaseType == TYP_DOUBLE) + { + simdBaseJitType = CORINFO_TYPE_LONG; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, loadIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector128_LoadUnsafe: + case NI_Vector256_LoadUnsafe: + { + if (sig->numArgs == 2) + { + op2 = impPopStack().val; + } + else + { + assert(sig->numArgs == 1); + } + + op1 = impPopStack().val; + + if (op1->OperIs(GT_CAST)) + { + // Although the API specifies a pointer, if what we have is a BYREF, that's what + // we really want, so throw away the cast. + if (op1->gtGetOp1()->TypeGet() == TYP_BYREF) + { + op1 = op1->gtGetOp1(); + } + } + + if (sig->numArgs == 2) + { + op3 = gtNewIconNode(genTypeSize(simdBaseType), op2->TypeGet()); + op2 = gtNewOperNode(GT_MUL, op2->TypeGet(), op2, op3); + op1 = gtNewOperNode(GT_ADD, op1->TypeGet(), op1, op2); + } + + NamedIntrinsic loadIntrinsic = NI_Illegal; + + if (simdSize == 32) + { + loadIntrinsic = NI_AVX_LoadVector256; + } + else if (simdBaseType != TYP_FLOAT) + { + loadIntrinsic = NI_SSE2_LoadVector128; + } + else + { + loadIntrinsic = NI_SSE_LoadVector128; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op1, loadIntrinsic, simdBaseJitType, simdSize); + break; + } + case NI_Vector128_Max: case NI_Vector256_Max: { @@ -1487,6 +1697,72 @@ GenTree* Compiler::impBaseIntrinsic(NamedIntrinsic intrinsic, break; } + case NI_Vector128_ShiftLeft: + case NI_Vector256_ShiftLeft: + { + assert(sig->numArgs == 2); + + if (varTypeIsByte(simdBaseType)) + { + // byte and sbyte would require more work to support + break; + } + + if ((simdSize != 32) || compExactlyDependsOn(InstructionSet_AVX2)) + { + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + retNode = gtNewSimdBinOpNode(GT_LSH, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + } + break; + } + + case NI_Vector128_ShiftRightArithmetic: + case NI_Vector256_ShiftRightArithmetic: + { + assert(sig->numArgs == 2); + + if (varTypeIsByte(simdBaseType) || varTypeIsLong(simdBaseType)) + { + // byte, sbyte, long, and ulong would require more work to support + break; + } + + if ((simdSize != 32) || compExactlyDependsOn(InstructionSet_AVX2)) + { + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + retNode = gtNewSimdBinOpNode(GT_RSH, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + } + break; + } + + case NI_Vector128_ShiftRightLogical: + case NI_Vector256_ShiftRightLogical: + { + assert(sig->numArgs == 2); + + if (varTypeIsByte(simdBaseType)) + { + // byte and sbyte would require more work to support + break; + } + + if ((simdSize != 32) || compExactlyDependsOn(InstructionSet_AVX2)) + { + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + retNode = gtNewSimdBinOpNode(GT_RSZ, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ false); + } + break; + } + case NI_Vector128_Sqrt: case NI_Vector256_Sqrt: { @@ -1500,6 +1776,157 @@ GenTree* Compiler::impBaseIntrinsic(NamedIntrinsic intrinsic, break; } + case NI_Vector128_Store: + case NI_Vector256_Store: + { + assert(sig->numArgs == 2); + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + NamedIntrinsic storeIntrinsic = NI_Illegal; + + if (simdSize == 32) + { + storeIntrinsic = NI_AVX_Store; + } + else if (simdBaseType != TYP_FLOAT) + { + storeIntrinsic = NI_SSE2_Store; + } + else + { + storeIntrinsic = NI_SSE_Store; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op2, op1, storeIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector128_StoreAligned: + case NI_Vector256_StoreAligned: + { + assert(sig->numArgs == 2); + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + NamedIntrinsic storeIntrinsic = NI_Illegal; + + if (simdSize == 32) + { + storeIntrinsic = NI_AVX_StoreAligned; + } + else if (simdBaseType != TYP_FLOAT) + { + storeIntrinsic = NI_SSE2_StoreAligned; + } + else + { + storeIntrinsic = NI_SSE_StoreAligned; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op2, op1, storeIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector128_StoreAlignedNonTemporal: + case NI_Vector256_StoreAlignedNonTemporal: + { + assert(sig->numArgs == 2); + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + NamedIntrinsic storeIntrinsic = NI_Illegal; + + if (simdSize == 32) + { + storeIntrinsic = NI_AVX_StoreAlignedNonTemporal; + } + else if (simdBaseType != TYP_FLOAT) + { + storeIntrinsic = NI_SSE2_StoreAlignedNonTemporal; + } + else + { + storeIntrinsic = NI_SSE_StoreAlignedNonTemporal; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op2, op1, storeIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector128_StoreUnsafe: + case NI_Vector256_StoreUnsafe: + { + if (sig->numArgs == 3) + { + op3 = impPopStack().val; + } + else + { + assert(sig->numArgs == 2); + } + + op2 = impPopStack().val; + op1 = impSIMDPopStack(retType); + + if (sig->numArgs == 3) + { + op3 = gtNewIconNode(genTypeSize(simdBaseType), op2->TypeGet()); + op2 = gtNewOperNode(GT_MUL, op2->TypeGet(), op2, op3); + op2 = gtNewOperNode(GT_ADD, op1->TypeGet(), op1, op2); + } + + NamedIntrinsic storeIntrinsic = NI_Illegal; + + if (simdSize == 32) + { + storeIntrinsic = NI_AVX_Store; + } + else if (simdBaseType != TYP_FLOAT) + { + storeIntrinsic = NI_SSE2_Store; + } + else + { + storeIntrinsic = NI_SSE_Store; + } + + retNode = gtNewSimdHWIntrinsicNode(retType, op2, op1, storeIntrinsic, simdBaseJitType, simdSize); + break; + } + + case NI_Vector128_Sum: + case NI_Vector256_Sum: + { + assert(sig->numArgs == 1); + + if (varTypeIsFloating(simdBaseType)) + { + if (!compOpportunisticallyDependsOn(InstructionSet_SSE3)) + { + // Floating-point types require SSE3.HorizontalAdd + break; + } + } + else if (!compOpportunisticallyDependsOn(InstructionSet_SSSE3)) + { + // Integral types require SSSE3.HorizontalAdd + break; + } + else if (varTypeIsByte(simdBaseType) || varTypeIsLong(simdBaseType)) + { + // byte, sbyte, long, and ulong all would require more work to support + break; + } + + op1 = impSIMDPopStack(retType); + retNode = gtNewSimdSumNode(retType, op1, simdBaseJitType, simdSize, /* isSimdAsHWIntrinsic */ false); + break; + } + case NI_Vector128_ToScalar: case NI_Vector256_ToScalar: { diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index 33e5443c1eee4..08597695cf2d4 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -3879,19 +3879,25 @@ GenTree* Compiler::impIntrinsic(GenTree* newobjThis, return new (this, GT_LABEL) GenTree(GT_LABEL, TYP_I_IMPL); } - if (((ni == NI_System_Runtime_CompilerServices_RuntimeHelpers_CreateSpan) || - (ni == NI_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray)) && - IsTargetAbi(CORINFO_CORERT_ABI)) + switch (ni) { // CreateSpan must be expanded for NativeAOT - mustExpand = true; - } + case NI_System_Runtime_CompilerServices_RuntimeHelpers_CreateSpan: + case NI_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray: + mustExpand |= IsTargetAbi(CORINFO_CORERT_ABI); + break; - if ((ni == NI_System_ByReference_ctor) || (ni == NI_System_ByReference_get_Value) || - (ni == NI_System_Activator_AllocatorOf) || (ni == NI_System_Activator_DefaultConstructorOf) || - (ni == NI_System_Object_MethodTableOf) || (ni == NI_System_EETypePtr_EETypePtrOf)) - { - mustExpand = true; + case NI_System_ByReference_ctor: + case NI_System_ByReference_get_Value: + case NI_System_Activator_AllocatorOf: + case NI_System_Activator_DefaultConstructorOf: + case NI_System_Object_MethodTableOf: + case NI_System_EETypePtr_EETypePtrOf: + mustExpand = true; + break; + + default: + break; } GenTree* retNode = nullptr; @@ -3935,29 +3941,19 @@ GenTree* Compiler::impIntrinsic(GenTree* newobjThis, case NI_System_String_get_Length: { GenTree* op1 = impPopStack().val; - if (opts.OptimizationEnabled()) + if (op1->OperIs(GT_CNS_STR)) { - if (op1->OperIs(GT_CNS_STR)) + // Optimize `ldstr + String::get_Length()` to CNS_INT + // e.g. "Hello".Length => 5 + GenTreeIntCon* iconNode = gtNewStringLiteralLength(op1->AsStrCon()); + if (iconNode != nullptr) { - // Optimize `ldstr + String::get_Length()` to CNS_INT - // e.g. "Hello".Length => 5 - GenTreeIntCon* iconNode = gtNewStringLiteralLength(op1->AsStrCon()); - if (iconNode != nullptr) - { - retNode = iconNode; - break; - } + retNode = iconNode; + break; } - GenTreeArrLen* arrLen = gtNewArrLen(TYP_INT, op1, OFFSETOF__CORINFO_String__stringLen, compCurBB); - op1 = arrLen; - } - else - { - /* Create the expression "*(str_addr + stringLengthOffset)" */ - op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1, - gtNewIconNode(OFFSETOF__CORINFO_String__stringLen, TYP_I_IMPL)); - op1 = gtNewOperNode(GT_IND, TYP_INT, op1); } + GenTreeArrLen* arrLen = gtNewArrLen(TYP_INT, op1, OFFSETOF__CORINFO_String__stringLen, compCurBB); + op1 = arrLen; // Getting the length of a null string should throw op1->gtFlags |= GTF_EXCEPT; @@ -4007,6 +4003,26 @@ GenTree* Compiler::impIntrinsic(GenTree* newobjThis, break; } + case NI_System_Runtime_CompilerServices_RuntimeHelpers_IsKnownConstant: + { + GenTree* op1 = impPopStack().val; + if (op1->OperIsConst()) + { + // op1 is a known constant, replace with 'true'. + retNode = gtNewIconNode(1); + JITDUMP("\nExpanding RuntimeHelpers.IsKnownConstant to true early\n"); + // We can also consider FTN_ADDR and typeof(T) here + } + else + { + // op1 is not a known constant, we'll do the expansion in morph + retNode = new (this, GT_INTRINSIC) GenTreeIntrinsic(TYP_INT, op1, ni, method); + JITDUMP("\nConverting RuntimeHelpers.IsKnownConstant to:\n"); + DISPTREE(retNode); + } + break; + } + case NI_System_Activator_AllocatorOf: case NI_System_Activator_DefaultConstructorOf: case NI_System_Object_MethodTableOf: @@ -4283,7 +4299,7 @@ GenTree* Compiler::impIntrinsic(GenTree* newobjThis, case NI_System_Threading_Thread_get_ManagedThreadId: { - if (opts.OptimizationEnabled() && impStackTop().val->OperIs(GT_RET_EXPR)) + if (impStackTop().val->OperIs(GT_RET_EXPR)) { GenTreeCall* call = impStackTop().val->AsRetExpr()->gtInlineCandidate->AsCall(); if (call->gtCallMoreFlags & GTF_CALL_M_SPECIAL_INTRINSIC) @@ -4306,7 +4322,7 @@ GenTree* Compiler::impIntrinsic(GenTree* newobjThis, case NI_System_Threading_Interlocked_Or: case NI_System_Threading_Interlocked_And: { - if (opts.OptimizationEnabled() && compOpportunisticallyDependsOn(InstructionSet_Atomics)) + if (compOpportunisticallyDependsOn(InstructionSet_Atomics)) { assert(sig->numArgs == 2); GenTree* op2 = impPopStack().val; @@ -5352,6 +5368,10 @@ NamedIntrinsic Compiler::lookupNamedIntrinsic(CORINFO_METHOD_HANDLE method) { result = NI_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray; } + else if (strcmp(methodName, "IsKnownConstant") == 0) + { + result = NI_System_Runtime_CompilerServices_RuntimeHelpers_IsKnownConstant; + } } else if (strncmp(namespaceName, "System.Runtime.Intrinsics", 25) == 0) { @@ -8130,6 +8150,23 @@ GenTree* Compiler::impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedT CORINFO_FIELD_INFO* pFieldInfo, var_types lclTyp) { + // Ordinary static fields never overlap. RVA statics, however, can overlap (if they're + // mapped to the same ".data" declaration). That said, such mappings only appear to be + // possible with ILASM, and in ILASM-produced (ILONLY) images, RVA statics are always + // read-only (using "stsfld" on them is UB). In mixed-mode assemblies, RVA statics can + // be mutable, but the only current producer of such images, the C++/CLI compiler, does + // not appear to support mapping different fields to the same address. So we will say + // that "mutable overlapping RVA statics" are UB as well. If this ever changes, code in + // morph and value numbering will need to be updated to respect "gtFldMayOverlap" and + // "NotAField FldSeq". + + // For statics that are not "boxed", the initial address tree will contain the field sequence. + // For those that are, we will attach it later, when adding the indirection for the box, since + // that tree will represent the true address. + bool isBoxedStatic = (pFieldInfo->fieldFlags & CORINFO_FLG_FIELD_STATIC_IN_HEAP) != 0; + FieldSeqNode* innerFldSeq = + !isBoxedStatic ? GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField) : FieldSeqStore::NotAField(); + GenTree* op1; switch (pFieldInfo->fieldAccessor) @@ -8161,10 +8198,7 @@ GenTree* Compiler::impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedT } op1 = gtNewHelperCallNode(pFieldInfo->helper, type, gtNewCallArgs(op1)); - - FieldSeqNode* fs = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField); - op1 = gtNewOperNode(GT_ADD, type, op1, - new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, pFieldInfo->offset, fs)); + op1 = gtNewOperNode(GT_ADD, type, op1, gtNewIconNode(pFieldInfo->offset, innerFldSeq)); } break; @@ -8191,11 +8225,7 @@ GenTree* Compiler::impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedT op1 = fgGetStaticsCCtorHelper(pResolvedToken->hClass, pFieldInfo->helper); } - { - FieldSeqNode* fs = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField); - op1 = gtNewOperNode(GT_ADD, op1->TypeGet(), op1, - new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, pFieldInfo->offset, fs)); - } + op1 = gtNewOperNode(GT_ADD, op1->TypeGet(), op1, gtNewIconNode(pFieldInfo->offset, innerFldSeq)); break; } @@ -8222,9 +8252,7 @@ GenTree* Compiler::impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedT op1->gtFlags |= callFlags; op1->AsCall()->setEntryPoint(pFieldInfo->fieldLookup); - FieldSeqNode* fs = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField); - op1 = gtNewOperNode(GT_ADD, type, op1, - new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, pFieldInfo->offset, fs)); + op1 = gtNewOperNode(GT_ADD, type, op1, gtNewIconNode(pFieldInfo->offset, innerFldSeq)); #else unreached(); #endif // FEATURE_READYTORUN @@ -8243,20 +8271,9 @@ GenTree* Compiler::impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedT // We should always be able to access this static's address directly. assert(pFldAddr == nullptr); - GenTreeFlags handleKind; - if ((pFieldInfo->fieldFlags & CORINFO_FLG_FIELD_STATIC_IN_HEAP) != 0) - { - handleKind = GTF_ICON_STATIC_BOX_PTR; - } - else - { - handleKind = GTF_ICON_STATIC_HDL; - } - - FieldSeqNode* fldSeq = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField); - // Create the address node. - op1 = gtNewIconHandleNode((size_t)fldAddr, handleKind, fldSeq); + GenTreeFlags handleKind = isBoxedStatic ? GTF_ICON_STATIC_BOX_PTR : GTF_ICON_STATIC_HDL; + op1 = gtNewIconHandleNode((size_t)fldAddr, handleKind, innerFldSeq); #ifdef DEBUG op1->AsIntCon()->gtTargetHandle = op1->AsIntCon()->gtIconVal; #endif @@ -8276,14 +8293,12 @@ GenTree* Compiler::impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedT op1->gtFlags |= GTF_FLD_INITCLASS; } - if (pFieldInfo->fieldFlags & CORINFO_FLG_FIELD_STATIC_IN_HEAP) + if (isBoxedStatic) { - op1->gtType = TYP_REF; // points at boxed object - FieldSeqNode* firstElemFldSeq = - GetFieldSeqStore()->CreateSingleton(FieldSeqStore::FirstElemPseudoField); - op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1, - new (this, GT_CNS_INT) - GenTreeIntCon(TYP_I_IMPL, TARGET_POINTER_SIZE, firstElemFldSeq)); + FieldSeqNode* outerFldSeq = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField); + + op1->ChangeType(TYP_REF); // points at boxed object + op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1, gtNewIconNode(TARGET_POINTER_SIZE, outerFldSeq)); if (varTypeIsStruct(lclTyp)) { @@ -8304,15 +8319,14 @@ GenTree* Compiler::impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedT } } - if (pFieldInfo->fieldFlags & CORINFO_FLG_FIELD_STATIC_IN_HEAP) + if (isBoxedStatic) { + FieldSeqNode* outerFldSeq = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField); + op1 = gtNewOperNode(GT_IND, TYP_REF, op1); op1->gtFlags |= (GTF_IND_INVARIANT | GTF_IND_NONFAULTING | GTF_IND_NONNULL); - FieldSeqNode* fldSeq = GetFieldSeqStore()->CreateSingleton(FieldSeqStore::FirstElemPseudoField); - - op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1, - new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, TARGET_POINTER_SIZE, fldSeq)); + op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1, gtNewIconNode(TARGET_POINTER_SIZE, outerFldSeq)); } if (!(access & CORINFO_ACCESS_ADDRESS)) @@ -10772,7 +10786,7 @@ void Compiler::impImportLeave(BasicBlock* block) * scope */ exitBlock = fgNewBBinRegion(BBJ_EHCATCHRET, 0, XTnum + 1, step); - assert(step->bbJumpKind == BBJ_ALWAYS || step->bbJumpKind == BBJ_EHCATCHRET); + assert(step->KindIs(BBJ_ALWAYS, BBJ_EHCATCHRET)); step->bbJumpDest = exitBlock; // the previous step (maybe a call to a nested finally, or a nested catch // exit) returns to this block step->bbJumpDest->bbRefs++; @@ -10880,7 +10894,7 @@ void Compiler::impImportLeave(BasicBlock* block) // never returns to the call-to-finally call, and the finally-protected 'try' region doesn't appear on // stack walks.) - assert(step->bbJumpKind == BBJ_ALWAYS || step->bbJumpKind == BBJ_EHCATCHRET); + assert(step->KindIs(BBJ_ALWAYS, BBJ_EHCATCHRET)); #if FEATURE_EH_CALLFINALLY_THUNKS if (step->bbJumpKind == BBJ_EHCATCHRET) @@ -11792,28 +11806,30 @@ void Compiler::impImportBlockCode(BasicBlock* block) #ifdef FEATURE_ON_STACK_REPLACEMENT - // Are there any places in the method where we might add a patchpoint? + // Is OSR enabled? // - if (compHasBackwardJump) + if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_TIER0) && (JitConfig.TC_OnStackReplacement() > 0)) { - // Is OSR enabled? + // We don't inline at Tier0, if we do, we may need rethink our approach. + // Could probably support inlines that don't introduce flow. + // + assert(!compIsForInlining()); + + // OSR is not yet supported for methods with explicit tail calls. + // + // But we also do not have to switch these methods to be optimized as we should be + // able to avoid getting trapped in Tier0 code by normal call counting. + // So instead, just suppress adding patchpoints. // - if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_TIER0) && (JitConfig.TC_OnStackReplacement() > 0)) + if (!compTailPrefixSeen) { - // OSR is not yet supported for methods with explicit tail calls. - // - // But we also may not switch methods to be optimized as we should be - // able to avoid getting trapped in Tier0 code by normal call counting. - // So instead, just suppress adding patchpoints. + assert(compCanHavePatchpoints()); + + // The normaly policy is only to add patchpoints to the targets of lexically + // backwards branches. // - if (!compTailPrefixSeen) + if (compHasBackwardJump) { - assert(compCanHavePatchpoints()); - - // We don't inline at Tier0, if we do, we may need rethink our approach. - // Could probably support inlines that don't introduce flow. - assert(!compIsForInlining()); - // Is the start of this block a suitable patchpoint? // if (((block->bbFlags & BBF_BACKWARD_JUMP_TARGET) != 0) && (verCurrentState.esStackDepth == 0)) @@ -11826,12 +11842,64 @@ void Compiler::impImportBlockCode(BasicBlock* block) setMethodHasPatchpoint(); } } + else + { + // Should not see backward branch targets w/o backwards branches + assert((block->bbFlags & BBF_BACKWARD_JUMP_TARGET) == 0); + } } - } - else - { - // Should not see backward branch targets w/o backwards branches - assert((block->bbFlags & BBF_BACKWARD_JUMP_TARGET) == 0); + +#ifdef DEBUG + // As a stress test, we can place patchpoints at the start of any block + // that is a stack empty point and is not within a handler. + // + // Todo: enable for mid-block stack empty points too. + // + const int offsetOSR = JitConfig.JitOffsetOnStackReplacement(); + const int randomOSR = JitConfig.JitRandomOnStackReplacement(); + const bool tryOffsetOSR = offsetOSR >= 0; + const bool tryRandomOSR = randomOSR > 0; + + if ((tryOffsetOSR || tryRandomOSR) && (verCurrentState.esStackDepth == 0) && !block->hasHndIndex() && + ((block->bbFlags & BBF_PATCHPOINT) == 0)) + { + // Block start can have a patchpoint. See if we should add one. + // + bool addPatchpoint = false; + + // Specific offset? + // + if (tryOffsetOSR) + { + if (impCurOpcOffs == (unsigned)offsetOSR) + { + addPatchpoint = true; + } + } + // Random? + // + else + { + // Reuse the random inliner's random state. + // Note m_inlineStrategy is always created, even if we're not inlining. + // + CLRRandom* const random = impInlineRoot()->m_inlineStrategy->GetRandom(randomOSR); + const int randomValue = (int)random->Next(100); + + addPatchpoint = (randomValue < randomOSR); + } + + if (addPatchpoint) + { + block->bbFlags |= BBF_PATCHPOINT; + setMethodHasPatchpoint(); + } + + JITDUMP("\n** %s patchpoint%s added to " FMT_BB " (il offset %u)\n", tryOffsetOSR ? "offset" : "random", + addPatchpoint ? "" : " not", block->bbNum, impCurOpcOffs); + } + +#endif // DEBUG } // Mark stack-empty rare blocks to be considered for partial compilation. diff --git a/src/coreclr/jit/inline.def b/src/coreclr/jit/inline.def index a28daf4e980fd..a519471a3caec 100644 --- a/src/coreclr/jit/inline.def +++ b/src/coreclr/jit/inline.def @@ -70,6 +70,8 @@ INLINE_OBSERVATION(ARG_FEEDS_CONSTANT_TEST, bool, "argument feeds constant t INLINE_OBSERVATION(ARG_FEEDS_TEST, bool, "argument feeds test", INFORMATION, CALLEE) INLINE_OBSERVATION(ARG_FEEDS_CAST, int, "argument feeds castclass or isinst", INFORMATION, CALLEE) INLINE_OBSERVATION(ARG_FEEDS_RANGE_CHECK, bool, "argument feeds range check", INFORMATION, CALLEE) +INLINE_OBSERVATION(ARG_FEEDS_ISCONST, bool, "argument feeds IsKnownConstant", INFORMATION, CALLEE) +INLINE_OBSERVATION(CONST_ARG_FEEDS_ISCONST, bool, "const argument feeds IsKnownConstant", INFORMATION, CALLEE) INLINE_OBSERVATION(ARG_STRUCT, int, "arg is a struct passed by value", INFORMATION, CALLEE) INLINE_OBSERVATION(RETURNS_STRUCT, bool, "returns a struct by value", INFORMATION, CALLEE) INLINE_OBSERVATION(ARG_STRUCT_FIELD_ACCESS, int, "ldfld/stfld over arg (struct)", INFORMATION, CALLEE) diff --git a/src/coreclr/jit/inlinepolicy.cpp b/src/coreclr/jit/inlinepolicy.cpp index 1ec47378872d5..0ea9135b82c24 100644 --- a/src/coreclr/jit/inlinepolicy.cpp +++ b/src/coreclr/jit/inlinepolicy.cpp @@ -326,6 +326,14 @@ void DefaultPolicy::NoteBool(InlineObservation obs, bool value) m_ArgFeedsRangeCheck++; break; + case InlineObservation::CALLEE_CONST_ARG_FEEDS_ISCONST: + m_ConstArgFeedsIsKnownConst = true; + break; + + case InlineObservation::CALLEE_ARG_FEEDS_ISCONST: + m_ArgFeedsIsKnownConst = true; + break; + case InlineObservation::CALLEE_UNSUPPORTED_OPCODE: propagate = true; break; @@ -727,6 +735,15 @@ double DefaultPolicy::DetermineMultiplier() JITDUMP("\nInline candidate has arg that feeds range check. Multiplier increased to %g.", multiplier); } + if (m_ConstArgFeedsIsKnownConst || (m_ArgFeedsIsKnownConst && m_IsPrejitRoot)) + { + // if we use RuntimeHelpers.IsKnownConstant we most likely expect our function to be always inlined + // at least in the case of constant arguments. In IsPrejitRoot we don't have callsite info so let's + // assume we have a constant here in order to avoid "baked" noinline + multiplier += 20; + JITDUMP("\nConstant argument feeds RuntimeHelpers.IsKnownConstant. Multiplier increased to %g.", multiplier); + } + if (m_ConstantArgFeedsConstantTest > 0) { multiplier += 3.0; @@ -1371,7 +1388,7 @@ void ExtendedDefaultPolicy::NoteInt(InlineObservation obs, int value) { SetNever(InlineObservation::CALLEE_DOES_NOT_RETURN); } - else if (!m_IsForceInline && !m_HasProfile) + else if (!m_IsForceInline && !m_HasProfile && !m_ConstArgFeedsIsKnownConst && !m_ArgFeedsIsKnownConst) { unsigned bbLimit = (unsigned)JitConfig.JitExtDefaultPolicyMaxBB(); if (m_IsPrejitRoot) @@ -1381,6 +1398,7 @@ void ExtendedDefaultPolicy::NoteInt(InlineObservation obs, int value) bbLimit += 5 + m_Switch * 10; } bbLimit += m_FoldableBranch + m_FoldableSwitch * 10; + if ((unsigned)value > bbLimit) { SetNever(InlineObservation::CALLEE_TOO_MANY_BASIC_BLOCKS); @@ -2638,6 +2656,8 @@ void DiscretionaryPolicy::DumpData(FILE* file) const fprintf(file, ",%u", m_ArgFeedsConstantTest); fprintf(file, ",%u", m_MethodIsMostlyLoadStore ? 1 : 0); fprintf(file, ",%u", m_ArgFeedsRangeCheck); + fprintf(file, ",%u", m_ConstArgFeedsIsKnownConst ? 1 : 0); + fprintf(file, ",%u", m_ArgFeedsIsKnownConst ? 1 : 0); fprintf(file, ",%u", m_ConstantArgFeedsConstantTest); fprintf(file, ",%d", m_CalleeNativeSizeEstimate); fprintf(file, ",%d", m_CallsiteNativeSizeEstimate); diff --git a/src/coreclr/jit/inlinepolicy.h b/src/coreclr/jit/inlinepolicy.h index f5f200e9f5bd7..05e8539982ee8 100644 --- a/src/coreclr/jit/inlinepolicy.h +++ b/src/coreclr/jit/inlinepolicy.h @@ -110,6 +110,8 @@ class DefaultPolicy : public LegalPolicy , m_CallsiteIsInLoop(false) , m_IsNoReturn(false) , m_IsNoReturnKnown(false) + , m_ConstArgFeedsIsKnownConst(false) + , m_ArgFeedsIsKnownConst(false) { // empty } @@ -178,6 +180,8 @@ class DefaultPolicy : public LegalPolicy bool m_CallsiteIsInLoop : 1; bool m_IsNoReturn : 1; bool m_IsNoReturnKnown : 1; + bool m_ConstArgFeedsIsKnownConst : 1; + bool m_ArgFeedsIsKnownConst : 1; }; // ExtendedDefaultPolicy is a slightly more aggressive variant of diff --git a/src/coreclr/jit/instrsarm64.h b/src/coreclr/jit/instrsarm64.h index c89b006a41897..d4e7ef5b10c8d 100644 --- a/src/coreclr/jit/instrsarm64.h +++ b/src/coreclr/jit/instrsarm64.h @@ -312,8 +312,8 @@ INST4(neg, "neg", 0, IF_EN4G, 0x4B0003E0, 0x4B0003E0, INST4(cmeq, "cmeq", 0, IF_EN4H, 0x7EE08C00, 0x2E208C00, 0x5E209800, 0x0E209800) // cmeq Vd,Vn,Vm DV_3E 01111110111mmmmm 100011nnnnnddddd 7EE0 8C00 Vd,Vn,Vm (scalar) // cmeq Vd,Vn,Vm DV_3A 0Q101110XX1mmmmm 100011nnnnnddddd 2E20 8C00 Vd,Vn,Vm (vector) - // cmeq Vd,Vn DV_2L 01011110XX100000 100110nnnnnddddd 5E20 9800 Vd,Vn (scalar) - // cmeq Vd,Vn DV_2M 0Q001110XX100000 100110nnnnnddddd 0E20 9800 Vd,Vn (vector) + // cmeq Vd,Vn,#0 DV_2L 01011110XX100000 100110nnnnnddddd 5E20 9800 Vd,Vn,#0 (scalar - with zero) + // cmeq Vd,Vn,#0 DV_2M 0Q001110XX100000 100110nnnnnddddd 0E20 9800 Vd,Vn,#0 (vector - with zero) INST4(cmge, "cmge", 0, IF_EN4H, 0x5EE03C00, 0x0E203C00, 0x7E208800, 0x2E208800) // cmge Vd,Vn,Vm DV_3E 01011110111mmmmm 001111nnnnnddddd 5EE0 3C00 Vd,Vn,Vm (scalar) @@ -331,8 +331,8 @@ INST4(cmgt, "cmgt", 0, IF_EN4H, 0x5EE03400, 0x0E203400, INST4(fcmeq, "fcmeq", 0, IF_EN4I, 0x5E20E400, 0x0E20E400, 0x5EA0D800, 0x0EA0D800) // fcmeq Vd,Vn,Vm DV_3D 010111100X1mmmmm 111001nnnnnddddd 5E20 E400 Vd Vn Vm (scalar) // fcmeq Vd,Vn,Vm DV_3B 0Q0011100X1mmmmm 111001nnnnnddddd 0E20 E400 Vd,Vn,Vm (vector) - // fcmeq Vd,Vn DV_2G 010111101X100000 110110nnnnnddddd 5EA0 D800 Vd Vn (scalar) - // fcmeq Vd,Vn DV_2A 0Q0011101X100000 110110nnnnnddddd 0EA0 D800 Vd Vn (vector) + // fcmeq Vd,Vn,#0 DV_2G 010111101X100000 110110nnnnnddddd 5EA0 D800 Vd Vn,#0 (scalar - with zero) + // fcmeq Vd,Vn,#0 DV_2A 0Q0011101X100000 110110nnnnnddddd 0EA0 D800 Vd Vn,#0 (vector - with zero) INST4(fcmge, "fcmge", 0, IF_EN4I, 0x7E20E400, 0x2E20E400, 0x7EA0C800, 0x2EA0C800) // fcmge Vd,Vn,Vm DV_3D 011111100X1mmmmm 111001nnnnnddddd 7E20 E400 Vd Vn Vm (scalar) diff --git a/src/coreclr/jit/jit.h b/src/coreclr/jit/jit.h index c9e8d0732a467..1a1af89490d62 100644 --- a/src/coreclr/jit/jit.h +++ b/src/coreclr/jit/jit.h @@ -284,7 +284,8 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX typedef class ICorJitInfo* COMP_HANDLE; -const CORINFO_CLASS_HANDLE NO_CLASS_HANDLE = (CORINFO_CLASS_HANDLE) nullptr; +const CORINFO_CLASS_HANDLE NO_CLASS_HANDLE = nullptr; +const CORINFO_FIELD_HANDLE NO_FIELD_HANDLE = nullptr; /*****************************************************************************/ diff --git a/src/coreclr/jit/jitconfigvalues.h b/src/coreclr/jit/jitconfigvalues.h index 73b71a07a8c49..4fc4594c6fb2b 100644 --- a/src/coreclr/jit/jitconfigvalues.h +++ b/src/coreclr/jit/jitconfigvalues.h @@ -279,70 +279,12 @@ CONFIG_INTEGER(AltJitAssertOnNYI, W("AltJitAssertOnNYI"), 0) // Controls the Alt #else // !defined(TARGET_ARM64) && !defined(TARGET_X86) CONFIG_INTEGER(AltJitAssertOnNYI, W("AltJitAssertOnNYI"), 1) // Controls the AltJit behavior of NYI stuff #endif // defined(TARGET_ARM64) || defined(TARGET_X86) -/// -/// JIT Hardware Intrinsics -/// -#if defined(TARGET_X86) || defined(TARGET_AMD64) -CONFIG_INTEGER(EnableSSE3_4, W("EnableSSE3_4"), 1) // Enable SSE3, SSSE3, SSE 4.1 and 4.2 instruction set as default -#endif - -#if defined(TARGET_AMD64) || defined(TARGET_X86) -// Enable AVX instruction set for wide operations as default. When both AVX and SSE3_4 are set, we will use the most -// capable instruction set available which will prefer AVX over SSE3/4. -CONFIG_INTEGER(EnableHWIntrinsic, W("EnableHWIntrinsic"), 1) // Enable Base -CONFIG_INTEGER(EnableSSE, W("EnableSSE"), 1) // Enable SSE -CONFIG_INTEGER(EnableSSE2, W("EnableSSE2"), 1) // Enable SSE2 -CONFIG_INTEGER(EnableSSE3, W("EnableSSE3"), 1) // Enable SSE3 -CONFIG_INTEGER(EnableSSSE3, W("EnableSSSE3"), 1) // Enable SSSE3 -CONFIG_INTEGER(EnableSSE41, W("EnableSSE41"), 1) // Enable SSE41 -CONFIG_INTEGER(EnableSSE42, W("EnableSSE42"), 1) // Enable SSE42 -CONFIG_INTEGER(EnableAVX, W("EnableAVX"), 1) // Enable AVX -CONFIG_INTEGER(EnableAVX2, W("EnableAVX2"), 1) // Enable AVX2 -CONFIG_INTEGER(EnableAVXVNNI, W("EnableAVXVNNI"), 1) // Enable AVXVNNI -CONFIG_INTEGER(EnableFMA, W("EnableFMA"), 1) // Enable FMA -CONFIG_INTEGER(EnableAES, W("EnableAES"), 1) // Enable AES -CONFIG_INTEGER(EnableBMI1, W("EnableBMI1"), 1) // Enable BMI1 -CONFIG_INTEGER(EnableBMI2, W("EnableBMI2"), 1) // Enable BMI2 -CONFIG_INTEGER(EnableLZCNT, W("EnableLZCNT"), 1) // Enable AES -CONFIG_INTEGER(EnablePCLMULQDQ, W("EnablePCLMULQDQ"), 1) // Enable PCLMULQDQ -CONFIG_INTEGER(EnablePOPCNT, W("EnablePOPCNT"), 1) // Enable POPCNT -#else // !defined(TARGET_AMD64) && !defined(TARGET_X86) -// Enable AVX instruction set for wide operations as default -CONFIG_INTEGER(EnableAVX, W("EnableAVX"), 0) -#endif // !defined(TARGET_AMD64) && !defined(TARGET_X86) CONFIG_INTEGER(EnableEHWriteThru, W("EnableEHWriteThru"), 1) // Enable the register allocator to support EH-write thru: // partial enregistration of vars exposed on EH boundaries CONFIG_INTEGER(EnableMultiRegLocals, W("EnableMultiRegLocals"), 1) // Enable the enregistration of locals that are // defined or used in a multireg context. -// clang-format off - -#if defined(TARGET_ARM64) -CONFIG_INTEGER(EnableHWIntrinsic, W("EnableHWIntrinsic"), 1) -CONFIG_INTEGER(EnableArm64Aes, W("EnableArm64Aes"), 1) -CONFIG_INTEGER(EnableArm64Atomics, W("EnableArm64Atomics"), 1) -CONFIG_INTEGER(EnableArm64Crc32, W("EnableArm64Crc32"), 1) -CONFIG_INTEGER(EnableArm64Dcpop, W("EnableArm64Dcpop"), 1) -CONFIG_INTEGER(EnableArm64Dp, W("EnableArm64Dp"), 1) -CONFIG_INTEGER(EnableArm64Fcma, W("EnableArm64Fcma"), 1) -CONFIG_INTEGER(EnableArm64Fp, W("EnableArm64Fp"), 1) -CONFIG_INTEGER(EnableArm64Fp16, W("EnableArm64Fp16"), 1) -CONFIG_INTEGER(EnableArm64Jscvt, W("EnableArm64Jscvt"), 1) -CONFIG_INTEGER(EnableArm64Lrcpc, W("EnableArm64Lrcpc"), 1) -CONFIG_INTEGER(EnableArm64Pmull, W("EnableArm64Pmull"), 1) -CONFIG_INTEGER(EnableArm64Sha1, W("EnableArm64Sha1"), 1) -CONFIG_INTEGER(EnableArm64Sha256, W("EnableArm64Sha256"), 1) -CONFIG_INTEGER(EnableArm64Sha512, W("EnableArm64Sha512"), 1) -CONFIG_INTEGER(EnableArm64Sha3, W("EnableArm64Sha3"), 1) -CONFIG_INTEGER(EnableArm64AdvSimd, W("EnableArm64AdvSimd"), 1) -CONFIG_INTEGER(EnableArm64AdvSimd_v81, W("EnableArm64AdvSimd_v81"), 1) -CONFIG_INTEGER(EnableArm64AdvSimd_Fp16, W("EnableArm64AdvSimd_Fp16"), 1) -CONFIG_INTEGER(EnableArm64Sm3, W("EnableArm64Sm3"), 1) -CONFIG_INTEGER(EnableArm64Sm4, W("EnableArm64Sm4"), 1) -CONFIG_INTEGER(EnableArm64Sve, W("EnableArm64Sve"), 1) -#endif // defined(TARGET_ARM64) - // clang-format on #ifdef FEATURE_SIMD @@ -521,6 +463,12 @@ CONFIG_INTEGER(TC_OnStackReplacement, W("TC_OnStackReplacement"), 0) CONFIG_INTEGER(TC_OnStackReplacement_InitialCounter, W("TC_OnStackReplacement_InitialCounter"), 1000) // Enable partial compilation for Tier0 methods CONFIG_INTEGER(TC_PartialCompilation, W("TC_PartialCompilation"), 0) +#if defined(DEBUG) +// Randomly sprinkle patchpoints. Value is the likelyhood any given stack-empty point becomes a patchpoint. +CONFIG_INTEGER(JitRandomOnStackReplacement, W("JitRandomOnStackReplacement"), 0) +// Place patchpoint at the specified IL offset, if possible. Overrides random placement. +CONFIG_INTEGER(JitOffsetOnStackReplacement, W("JitOffsetOnStackReplacement"), -1) +#endif // debug #if defined(DEBUG) CONFIG_STRING(JitEnableOsrRange, W("JitEnableOsrRange")) // Enable osr for only some methods diff --git a/src/coreclr/jit/lclvars.cpp b/src/coreclr/jit/lclvars.cpp index 7b329e0a86a46..eb76cd663f287 100644 --- a/src/coreclr/jit/lclvars.cpp +++ b/src/coreclr/jit/lclvars.cpp @@ -305,7 +305,9 @@ void Compiler::lvaInitTypeRef() JITDUMP("-- V%02u is OSR exposed\n", varNum); varDsc->lvHasLdAddrOp = 1; - if (varDsc->lvType != TYP_STRUCT) // Why does it apply only to non-structs? + // todo: Why does it apply only to non-structs? + // + if (!varTypeIsStruct(varDsc) && !varTypeIsSIMD(varDsc)) { lvaSetVarAddrExposed(varNum DEBUGARG(AddressExposedReason::OSR_EXPOSED)); } diff --git a/src/coreclr/jit/lir.cpp b/src/coreclr/jit/lir.cpp index 97f9e4f4807d2..81d03b93f7b34 100644 --- a/src/coreclr/jit/lir.cpp +++ b/src/coreclr/jit/lir.cpp @@ -1636,7 +1636,7 @@ void LIR::InsertBeforeTerminator(BasicBlock* block, LIR::Range&& range) LIR::Range& blockRange = LIR::AsRange(block); GenTree* insertionPoint = nullptr; - if ((block->bbJumpKind == BBJ_COND) || (block->bbJumpKind == BBJ_SWITCH) || (block->bbJumpKind == BBJ_RETURN)) + if (block->KindIs(BBJ_COND, BBJ_SWITCH, BBJ_RETURN)) { insertionPoint = blockRange.LastNode(); assert(insertionPoint != nullptr); diff --git a/src/coreclr/jit/loopcloning.cpp b/src/coreclr/jit/loopcloning.cpp index b97bc84c6cebf..bdd8d763aa4c7 100644 --- a/src/coreclr/jit/loopcloning.cpp +++ b/src/coreclr/jit/loopcloning.cpp @@ -767,7 +767,7 @@ BasicBlock* LoopCloneContext::CondToStmtInBlock(Compiler* { noway_assert(conds.Size() > 0); assert(slowHead != nullptr); - assert((insertAfter->bbJumpKind == BBJ_NONE) || (insertAfter->bbJumpKind == BBJ_COND)); + assert(insertAfter->KindIs(BBJ_NONE, BBJ_COND)); // Choose how to generate the conditions const bool generateOneConditionPerBlock = true; @@ -1631,7 +1631,7 @@ bool Compiler::optIsLoopClonable(unsigned loopInd) return false; } - if (!(loop.lpTestTree->OperKind() & GTK_RELOP) || !(loop.lpTestTree->gtFlags & GTF_RELOP_ZTT)) + if (!loop.lpTestTree->OperIsCompare() || !(loop.lpTestTree->gtFlags & GTF_RELOP_ZTT)) { JITDUMP("Loop cloning: rejecting loop " FMT_LP ". Loop inversion NOT present, loop test [%06u] may not protect " "entry from head.\n", @@ -1847,7 +1847,7 @@ void Compiler::optCloneLoop(unsigned loopInd, LoopCloneContext* context) // X BasicBlock* h = loop.lpHead; - if (h->bbJumpKind != BBJ_NONE && h->bbJumpKind != BBJ_ALWAYS) + if (!h->KindIs(BBJ_NONE, BBJ_ALWAYS)) { // Make a new block to be the unique entry to the loop. JITDUMP("Create new unique single-successor entry to loop\n"); diff --git a/src/coreclr/jit/lower.cpp b/src/coreclr/jit/lower.cpp index ae5a41c52e682..06d42a37f986f 100644 --- a/src/coreclr/jit/lower.cpp +++ b/src/coreclr/jit/lower.cpp @@ -2534,7 +2534,7 @@ GenTree* Lowering::OptimizeConstCompare(GenTree* cmp) #ifdef TARGET_ARM64 (op2Value == 0) && cmp->OperIs(GT_EQ, GT_NE, GT_GT) && #endif - (castOp->OperIs(GT_CALL, GT_LCL_VAR) || castOp->OperIsLogical() + (castOp->OperIs(GT_CALL, GT_LCL_VAR) || castOp->OperIs(GT_OR, GT_XOR, GT_AND) #ifdef TARGET_XARCH || IsContainableMemoryOp(castOp) #endif @@ -2555,7 +2555,7 @@ GenTree* Lowering::OptimizeConstCompare(GenTree* cmp) op2->gtType = castToType; #endif // If we have any contained memory ops on castOp, they must now not be contained. - if (castOp->OperIsLogical()) + if (castOp->OperIs(GT_OR, GT_XOR, GT_AND)) { GenTree* op1 = castOp->gtGetOp1(); if ((op1 != nullptr) && !op1->IsCnsIntOrI()) diff --git a/src/coreclr/jit/lowerarmarch.cpp b/src/coreclr/jit/lowerarmarch.cpp index 58301b37b887b..192c4abfc4386 100644 --- a/src/coreclr/jit/lowerarmarch.cpp +++ b/src/coreclr/jit/lowerarmarch.cpp @@ -53,7 +53,7 @@ bool Lowering::IsContainableImmed(GenTree* parentNode, GenTree* childNode) const if (!varTypeIsFloating(parentNode->TypeGet())) { #ifdef TARGET_ARM64 - if (parentNode->OperIsRelop() && childNode->IsFPZero()) + if (parentNode->OperIsCompare() && childNode->IsFPZero()) { // Contain 0.0 constant in fcmp on arm64 // TODO: Enable for arm too (vcmp) @@ -293,6 +293,8 @@ void Lowering::LowerBlockStore(GenTreeBlk* blkNode) GenTree* src = blkNode->Data(); unsigned size = blkNode->Size(); + const bool isDstAddrLocal = dstAddr->OperIsLocalAddr(); + if (blkNode->OperIsInitBlkOp()) { if (src->OperIs(GT_INIT_VAL)) @@ -306,7 +308,18 @@ void Lowering::LowerBlockStore(GenTreeBlk* blkNode) blkNode->SetOper(GT_STORE_BLK); } - if (!blkNode->OperIs(GT_STORE_DYN_BLK) && (size <= INITBLK_UNROLL_LIMIT) && src->OperIs(GT_CNS_INT)) + unsigned initBlockUnrollLimit = INITBLK_UNROLL_LIMIT; + +#ifdef TARGET_ARM64 + if (isDstAddrLocal) + { + // Since dstAddr points to the stack CodeGen can use more optimal + // quad-word store SIMD instructions for InitBlock. + initBlockUnrollLimit = INITBLK_LCL_UNROLL_LIMIT; + } +#endif + + if (!blkNode->OperIs(GT_STORE_DYN_BLK) && (size <= initBlockUnrollLimit) && src->OperIs(GT_CNS_INT)) { blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindUnroll; @@ -353,19 +366,39 @@ void Lowering::LowerBlockStore(GenTreeBlk* blkNode) assert(src->OperIs(GT_IND, GT_LCL_VAR, GT_LCL_FLD)); src->SetContained(); + bool isSrcAddrLocal = false; + if (src->OperIs(GT_IND)) { + GenTree* srcAddr = src->AsIndir()->Addr(); // TODO-Cleanup: Make sure that GT_IND lowering didn't mark the source address as contained. // Sometimes the GT_IND type is a non-struct type and then GT_IND lowering may contain the // address, not knowing that GT_IND is part of a block op that has containment restrictions. - src->AsIndir()->Addr()->ClearContained(); + srcAddr->ClearContained(); + isSrcAddrLocal = srcAddr->OperIsLocalAddr(); } - else if (src->OperIs(GT_LCL_VAR)) + else + { + isSrcAddrLocal = true; + + if (src->OperIs(GT_LCL_VAR)) + { + // TODO-1stClassStructs: for now we can't work with STORE_BLOCK source in register. + const unsigned srcLclNum = src->AsLclVar()->GetLclNum(); + comp->lvaSetVarDoNotEnregister(srcLclNum DEBUGARG(DoNotEnregisterReason::BlockOp)); + } + } + + unsigned copyBlockUnrollLimit = CPBLK_UNROLL_LIMIT; + +#ifdef TARGET_ARM64 + if (isSrcAddrLocal && isDstAddrLocal) { - // TODO-1stClassStructs: for now we can't work with STORE_BLOCK source in register. - const unsigned srcLclNum = src->AsLclVar()->GetLclNum(); - comp->lvaSetVarDoNotEnregister(srcLclNum DEBUGARG(DoNotEnregisterReason::BlockOp)); + // Since both srcAddr and dstAddr point to the stack CodeGen can use more optimal + // quad-word load and store SIMD instructions for CopyBlock. + copyBlockUnrollLimit = CPBLK_LCL_UNROLL_LIMIT; } +#endif if (blkNode->OperIs(GT_STORE_OBJ)) { @@ -373,7 +406,7 @@ void Lowering::LowerBlockStore(GenTreeBlk* blkNode) { blkNode->SetOper(GT_STORE_BLK); } - else if (dstAddr->OperIsLocalAddr() && (size <= CPBLK_UNROLL_LIMIT)) + else if (isDstAddrLocal && (size <= copyBlockUnrollLimit)) { // If the size is small enough to unroll then we need to mark the block as non-interruptible // to actually allow unrolling. The generated code does not report GC references loaded in the @@ -389,7 +422,7 @@ void Lowering::LowerBlockStore(GenTreeBlk* blkNode) blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindUnroll; } - else if (blkNode->OperIs(GT_STORE_BLK) && (size <= CPBLK_UNROLL_LIMIT)) + else if (blkNode->OperIs(GT_STORE_BLK) && (size <= copyBlockUnrollLimit)) { blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindUnroll; @@ -490,7 +523,6 @@ void Lowering::LowerCast(GenTree* tree) GenTree* op1 = tree->AsOp()->gtOp1; var_types dstType = tree->CastToType(); var_types srcType = genActualType(op1->TypeGet()); - var_types tmpType = TYP_UNDEF; if (varTypeIsFloating(srcType)) { @@ -501,16 +533,6 @@ void Lowering::LowerCast(GenTree* tree) assert(!varTypeIsSmall(srcType)); - if (tmpType != TYP_UNDEF) - { - GenTree* tmp = comp->gtNewCastNode(tmpType, op1, tree->IsUnsigned(), tmpType); - tmp->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT)); - - tree->gtFlags &= ~GTF_UNSIGNED; - tree->AsOp()->gtOp1 = tmp; - BlockRange().InsertAfter(op1, tmp); - } - // Now determine if we have operands that should be contained. ContainCheckCast(tree->AsCast()); } @@ -1853,6 +1875,21 @@ void Lowering::ContainCheckHWIntrinsic(GenTreeHWIntrinsic* node) MakeSrcContained(node, intrin.op4); break; + case NI_AdvSimd_CompareEqual: + case NI_AdvSimd_Arm64_CompareEqual: + case NI_AdvSimd_Arm64_CompareEqualScalar: + { + if (intrin.op1->IsVectorZero()) + { + MakeSrcContained(node, intrin.op1); + } + else if (intrin.op2->IsVectorZero()) + { + MakeSrcContained(node, intrin.op2); + } + break; + } + case NI_Vector64_CreateScalarUnsafe: case NI_Vector128_CreateScalarUnsafe: case NI_AdvSimd_DuplicateToVector64: diff --git a/src/coreclr/jit/lsra.cpp b/src/coreclr/jit/lsra.cpp index 9308836ff78fc..f1e97f9692d9a 100644 --- a/src/coreclr/jit/lsra.cpp +++ b/src/coreclr/jit/lsra.cpp @@ -2808,7 +2808,7 @@ regNumber LinearScan::allocateReg(Interval* currentInterval, bool wasAssigned = regSelector->foundUnassignedReg() && (assignedInterval != nullptr) && (assignedInterval->physReg == foundReg); unassignPhysReg(availablePhysRegRecord ARM_ARG(currentInterval->registerType)); - if (regSelector->isMatchingConstant()) + if (regSelector->isMatchingConstant() && compiler->opts.OptimizationEnabled()) { assert(assignedInterval->isConstant); refPosition->treeNode->SetReuseRegVal(); @@ -6415,7 +6415,7 @@ void LinearScan::insertUpperVectorRestore(GenTree* tree, else { JITDUMP("at end of " FMT_BB ":\n", block->bbNum); - if (block->bbJumpKind == BBJ_COND || block->bbJumpKind == BBJ_SWITCH) + if (block->KindIs(BBJ_COND, BBJ_SWITCH)) { noway_assert(!blockRange.IsEmpty()); @@ -6427,7 +6427,7 @@ void LinearScan::insertUpperVectorRestore(GenTree* tree, } else { - assert(block->bbJumpKind == BBJ_NONE || block->bbJumpKind == BBJ_ALWAYS); + assert(block->KindIs(BBJ_NONE, BBJ_ALWAYS)); blockRange.InsertAtEnd(LIR::SeqTree(compiler, simdNode)); } } @@ -7291,7 +7291,7 @@ void LinearScan::insertMove( { // Put the copy at the bottom GenTree* lastNode = blockRange.LastNode(); - if (block->bbJumpKind == BBJ_COND || block->bbJumpKind == BBJ_SWITCH) + if (block->KindIs(BBJ_COND, BBJ_SWITCH)) { noway_assert(!blockRange.IsEmpty()); @@ -7359,7 +7359,7 @@ void LinearScan::insertSwap( { // Put the copy at the bottom // If there's a branch, make an embedded statement that executes just prior to the branch - if (block->bbJumpKind == BBJ_COND || block->bbJumpKind == BBJ_SWITCH) + if (block->KindIs(BBJ_COND, BBJ_SWITCH)) { noway_assert(!blockRange.IsEmpty()); @@ -7371,7 +7371,7 @@ void LinearScan::insertSwap( } else { - assert(block->bbJumpKind == BBJ_NONE || block->bbJumpKind == BBJ_ALWAYS); + assert(block->KindIs(BBJ_NONE, BBJ_ALWAYS)); blockRange.InsertAtEnd(std::move(swapRange)); } } diff --git a/src/coreclr/jit/lsra.h b/src/coreclr/jit/lsra.h index 1b549424f0fc4..052c3f93999a3 100644 --- a/src/coreclr/jit/lsra.h +++ b/src/coreclr/jit/lsra.h @@ -1772,7 +1772,7 @@ class LinearScan : public LinearScanInterface // The following keep track of information about internal (temporary register) intervals // during the building of a single node. - static const int MaxInternalCount = 4; + static const int MaxInternalCount = 5; RefPosition* internalDefs[MaxInternalCount]; int internalCount = 0; bool setInternalRegsDelayFree; diff --git a/src/coreclr/jit/lsraarm64.cpp b/src/coreclr/jit/lsraarm64.cpp index 73b971ec5932f..796a9e8126e6f 100644 --- a/src/coreclr/jit/lsraarm64.cpp +++ b/src/coreclr/jit/lsraarm64.cpp @@ -1091,55 +1091,52 @@ int LinearScan::BuildHWIntrinsic(GenTreeHWIntrinsic* intrinsicTree) } } } - else + else if (intrin.op2 != nullptr) { - if (intrin.op2 != nullptr) - { - // RMW intrinsic operands doesn't have to be delayFree when they can be assigned the same register as op1Reg - // (i.e. a register that corresponds to read-modify-write operand) and one of them is the last use. + // RMW intrinsic operands doesn't have to be delayFree when they can be assigned the same register as op1Reg + // (i.e. a register that corresponds to read-modify-write operand) and one of them is the last use. - assert(intrin.op1 != nullptr); + assert(intrin.op1 != nullptr); - bool forceOp2DelayFree = false; - if ((intrin.id == NI_Vector64_GetElement) || (intrin.id == NI_Vector128_GetElement)) + bool forceOp2DelayFree = false; + if ((intrin.id == NI_Vector64_GetElement) || (intrin.id == NI_Vector128_GetElement)) + { + if (!intrin.op2->IsCnsIntOrI() && (!intrin.op1->isContained() || intrin.op1->OperIsLocal())) { - if (!intrin.op2->IsCnsIntOrI() && (!intrin.op1->isContained() || intrin.op1->OperIsLocal())) - { - // If the index is not a constant and the object is not contained or is a local - // we will need a general purpose register to calculate the address - // internal register must not clobber input index - // TODO-Cleanup: An internal register will never clobber a source; this code actually - // ensures that the index (op2) doesn't interfere with the target. - buildInternalIntRegisterDefForNode(intrinsicTree); - forceOp2DelayFree = true; - } - - if (!intrin.op2->IsCnsIntOrI() && !intrin.op1->isContained()) - { - // If the index is not a constant or op1 is in register, - // we will use the SIMD temp location to store the vector. - var_types requiredSimdTempType = (intrin.id == NI_Vector64_GetElement) ? TYP_SIMD8 : TYP_SIMD16; - compiler->getSIMDInitTempVarNum(requiredSimdTempType); - } + // If the index is not a constant and the object is not contained or is a local + // we will need a general purpose register to calculate the address + // internal register must not clobber input index + // TODO-Cleanup: An internal register will never clobber a source; this code actually + // ensures that the index (op2) doesn't interfere with the target. + buildInternalIntRegisterDefForNode(intrinsicTree); + forceOp2DelayFree = true; } - if (forceOp2DelayFree) - { - srcCount += BuildDelayFreeUses(intrin.op2); - } - else + if (!intrin.op2->IsCnsIntOrI() && !intrin.op1->isContained()) { - srcCount += isRMW ? BuildDelayFreeUses(intrin.op2, intrin.op1) : BuildOperandUses(intrin.op2); + // If the index is not a constant or op1 is in register, + // we will use the SIMD temp location to store the vector. + var_types requiredSimdTempType = (intrin.id == NI_Vector64_GetElement) ? TYP_SIMD8 : TYP_SIMD16; + compiler->getSIMDInitTempVarNum(requiredSimdTempType); } + } - if (intrin.op3 != nullptr) - { - srcCount += isRMW ? BuildDelayFreeUses(intrin.op3, intrin.op1) : BuildOperandUses(intrin.op3); + if (forceOp2DelayFree) + { + srcCount += BuildDelayFreeUses(intrin.op2); + } + else + { + srcCount += isRMW ? BuildDelayFreeUses(intrin.op2, intrin.op1) : BuildOperandUses(intrin.op2); + } - if (intrin.op4 != nullptr) - { - srcCount += isRMW ? BuildDelayFreeUses(intrin.op4, intrin.op1) : BuildOperandUses(intrin.op4); - } + if (intrin.op3 != nullptr) + { + srcCount += isRMW ? BuildDelayFreeUses(intrin.op3, intrin.op1) : BuildOperandUses(intrin.op3); + + if (intrin.op4 != nullptr) + { + srcCount += isRMW ? BuildDelayFreeUses(intrin.op4, intrin.op1) : BuildOperandUses(intrin.op4); } } } diff --git a/src/coreclr/jit/lsraarmarch.cpp b/src/coreclr/jit/lsraarmarch.cpp index ef7a2d0440aa4..f85cb81d9e8c3 100644 --- a/src/coreclr/jit/lsraarmarch.cpp +++ b/src/coreclr/jit/lsraarmarch.cpp @@ -694,36 +694,40 @@ int LinearScan::BuildBlockStore(GenTreeBlk* blkNode) { buildInternalIntRegisterDefForNode(blkNode); #ifdef TARGET_ARM64 - const bool dstAddrMayNeedReg = dstAddr->isContained(); - const bool srcAddrMayNeedReg = src->OperIs(GT_LCL_VAR, GT_LCL_FLD) || - ((srcAddrOrFill != nullptr) && srcAddrOrFill->isContained()); + const bool canUseLoadStorePairIntRegsInstrs = (size >= 2 * REGSIZE_BYTES); - if (srcAddrMayNeedReg && dstAddrMayNeedReg) + if (canUseLoadStorePairIntRegsInstrs) { - // The following allocates an additional integer register in a case - // when a load instruction and a store instruction cannot be encoded. + // CodeGen can use ldp/stp instructions sequence. buildInternalIntRegisterDefForNode(blkNode); - // In this case, CodeGen will use a SIMD register for copying. - buildInternalFloatRegisterDefForNode(blkNode, internalFloatRegCandidates()); - // And in case of a larger block size, two SIMD registers. - if (size >= 2 * REGSIZE_BYTES) - { - buildInternalFloatRegisterDefForNode(blkNode, internalFloatRegCandidates()); - } } - else if (srcAddrMayNeedReg || dstAddrMayNeedReg) + + const bool isSrcAddrLocal = src->OperIs(GT_LCL_VAR, GT_LCL_FLD) || + ((srcAddrOrFill != nullptr) && srcAddrOrFill->OperIsLocalAddr()); + const bool isDstAddrLocal = dstAddr->OperIsLocalAddr(); + + // CodeGen can use 16-byte SIMD ldp/stp for larger block sizes + // only when both source and destination base address registers have known alignment. + // This is the case, when both registers are either sp or fp. + bool canUse16ByteWideInstrs = isSrcAddrLocal && isDstAddrLocal && (size >= 2 * FP_REGSIZE_BYTES); + + // Note that the SIMD registers allocation is speculative - LSRA doesn't know at this point + // whether CodeGen will use SIMD registers (i.e. if such instruction sequence will be more optimal). + // Therefore, it must allocate an additional integer register anyway. + if (canUse16ByteWideInstrs) { - if (size >= 2 * REGSIZE_BYTES) - { - buildInternalFloatRegisterDefForNode(blkNode, internalFloatRegCandidates()); - buildInternalFloatRegisterDefForNode(blkNode, internalFloatRegCandidates()); - } - else - { - buildInternalIntRegisterDefForNode(blkNode); - } + buildInternalFloatRegisterDefForNode(blkNode, internalFloatRegCandidates()); + buildInternalFloatRegisterDefForNode(blkNode, internalFloatRegCandidates()); } - else if (size >= 2 * REGSIZE_BYTES) + + const bool srcAddrMayNeedReg = + isSrcAddrLocal || ((srcAddrOrFill != nullptr) && srcAddrOrFill->isContained()); + const bool dstAddrMayNeedReg = isDstAddrLocal || dstAddr->isContained(); + + // The following allocates an additional integer register in a case + // when a load instruction and a store instruction cannot be encoded using offset + // from a corresponding base register. + if (srcAddrMayNeedReg && dstAddrMayNeedReg) { buildInternalIntRegisterDefForNode(blkNode); } diff --git a/src/coreclr/jit/lsrabuild.cpp b/src/coreclr/jit/lsrabuild.cpp index adf2a3be3f16b..d58f1996091fa 100644 --- a/src/coreclr/jit/lsrabuild.cpp +++ b/src/coreclr/jit/lsrabuild.cpp @@ -3078,6 +3078,15 @@ int LinearScan::BuildOperandUses(GenTree* node, regMaskTP candidates) return 1; } +#ifdef TARGET_ARM64 + // Must happen before OperIsHWIntrinsic case, + // but this occurs when a vector zero node is marked as contained. + if (node->IsVectorZero()) + { + return 0; + } +#endif + #if !defined(TARGET_64BIT) if (node->OperIs(GT_LONG)) { @@ -3164,6 +3173,14 @@ int LinearScan::BuildDelayFreeUses(GenTree* node, GenTree* rmwNode, regMaskTP ca { use = BuildUse(node, candidates); } +#ifdef TARGET_ARM64 + // Must happen before OperIsHWIntrinsic case, + // but this occurs when a vector zero node is marked as contained. + else if (node->IsVectorZero()) + { + return 0; + } +#endif #ifdef FEATURE_HW_INTRINSICS else if (node->OperIsHWIntrinsic()) { @@ -3567,7 +3584,7 @@ int LinearScan::BuildSimple(GenTree* tree) { unsigned kind = tree->OperKind(); int srcCount = 0; - if ((kind & (GTK_CONST | GTK_LEAF)) == 0) + if ((kind & GTK_LEAF) == 0) { assert((kind & GTK_SMPOP) != 0); srcCount = BuildBinaryUses(tree->AsOp()); diff --git a/src/coreclr/jit/morph.cpp b/src/coreclr/jit/morph.cpp index 1ee03c84a398f..f1210b1741dcc 100644 --- a/src/coreclr/jit/morph.cpp +++ b/src/coreclr/jit/morph.cpp @@ -37,7 +37,7 @@ GenTree* Compiler::fgMorphCastIntoHelper(GenTree* tree, int helper, GenTree* ope { return fgMorphTree(tree); } - else if (tree->OperKind() & GTK_CONST) + else if (tree->OperIsConst()) { return fgMorphConst(tree); } @@ -5198,7 +5198,7 @@ GenTree* Compiler::fgMorphArrayIndex(GenTree* tree) asIndex->Arr()->AsStrCon()->gtSconCPX, &length); if ((cnsIndex < length) && (str != nullptr)) { - GenTree* cnsCharNode = gtNewIconNode(str[cnsIndex], elemTyp); + GenTree* cnsCharNode = gtNewIconNode(str[cnsIndex], TYP_INT); INDEBUG(cnsCharNode->gtDebugFlags |= GTF_DEBUG_NODE_MORPHED); return cnsCharNode; } @@ -6248,8 +6248,9 @@ GenTree* Compiler::fgMorphField(GenTree* tree, MorphAddrContext* mac) } else { - // Normal static field reference + assert(!fieldMayOverlap); + // Normal static field reference // // If we can we access the static's address directly // then pFldAddr will be NULL and @@ -6262,6 +6263,12 @@ GenTree* Compiler::fgMorphField(GenTree* tree, MorphAddrContext* mac) // assert(pFldAddr == nullptr); + // For boxed statics, this direct address will be for the box. We have already added + // the indirection for the field itself and attached the sequence, in importation. + bool isBoxedStatic = gtIsStaticFieldPtrToBoxedStruct(tree->TypeGet(), symHnd); + FieldSeqNode* fldSeq = + !isBoxedStatic ? GetFieldSeqStore()->CreateSingleton(symHnd) : FieldSeqStore::NotAField(); + #ifdef TARGET_64BIT bool isStaticReadOnlyInited = false; bool plsSpeculative = true; @@ -6275,11 +6282,8 @@ GenTree* Compiler::fgMorphField(GenTree* tree, MorphAddrContext* mac) // apply GTF_IND_INVARIANT flag and make it hoistable/CSE-friendly if (isStaticReadOnlyInited || (IMAGE_REL_BASED_REL32 != eeGetRelocTypeHint(fldAddr))) { - // The address is not directly addressible, so force it into a - // constant, so we handle it properly - - bool isBoxedStatic = gtIsStaticFieldPtrToBoxedStruct(tree->TypeGet(), symHnd); - GenTreeFlags handleKind = GTF_EMPTY; + // The address is not directly addressible, so force it into a constant, so we handle it properly. + GenTreeFlags handleKind = GTF_EMPTY; if (isBoxedStatic) { handleKind = GTF_ICON_STATIC_BOX_PTR; @@ -6292,8 +6296,7 @@ GenTree* Compiler::fgMorphField(GenTree* tree, MorphAddrContext* mac) { handleKind = GTF_ICON_STATIC_HDL; } - FieldSeqNode* fieldSeq = GetFieldSeqStore()->CreateSingleton(symHnd); - GenTree* addr = gtNewIconHandleNode((size_t)fldAddr, handleKind, fieldSeq); + GenTree* addr = gtNewIconHandleNode((size_t)fldAddr, handleKind, fldSeq); // Translate GTF_FLD_INITCLASS to GTF_ICON_INITCLASS, if we need to. if (((tree->gtFlags & GTF_FLD_INITCLASS) != 0) && !isStaticReadOnlyInited) @@ -6330,9 +6333,7 @@ GenTree* Compiler::fgMorphField(GenTree* tree, MorphAddrContext* mac) static_assert_no_msg(GTF_FLD_INITCLASS == GTF_CLS_VAR_INITCLASS); tree->SetOper(GT_CLS_VAR); tree->AsClsVar()->gtClsVarHnd = symHnd; - FieldSeqNode* fieldSeq = - fieldMayOverlap ? FieldSeqStore::NotAField() : GetFieldSeqStore()->CreateSingleton(symHnd); - tree->AsClsVar()->gtFieldSeq = fieldSeq; + tree->AsClsVar()->gtFieldSeq = fldSeq; } return tree; @@ -9413,12 +9414,12 @@ GenTree* Compiler::fgExpandVirtualVtableCallTarget(GenTreeCall* call) /***************************************************************************** * - * Transform the given GTK_CONST tree for code generation. + * Transform the given constant tree for code generation. */ GenTree* Compiler::fgMorphConst(GenTree* tree) { - assert(tree->OperKind() & GTK_CONST); + assert(tree->OperIsConst()); /* Clear any exception flags or other unnecessary flags * that may have been set before folding this node to a constant */ @@ -11014,7 +11015,7 @@ GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac) noway_assert(op1); - if (op1->OperKind() & GTK_RELOP) + if (op1->OperIsCompare()) { /* Mark the comparison node with GTF_RELOP_JMP_USED so it knows that it does not need to materialize the result as a 0 or 1. */ @@ -11948,7 +11949,7 @@ GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac) return tree; } - else if (tree->OperKind() & GTK_CONST) + else if (tree->OperIsConst()) { return tree; } @@ -12086,7 +12087,7 @@ GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac) COMPARE: - noway_assert(tree->OperKind() & GTK_RELOP); + noway_assert(tree->OperIsCompare()); break; case GT_MUL: @@ -13200,7 +13201,7 @@ GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac) return throwNode; } - noway_assert(op1->OperKind() & GTK_RELOP); + noway_assert(op1->OperIsCompare()); noway_assert(op1->gtFlags & GTF_EXCEPT); // We need to keep op1 for the side-effects. Hang it off @@ -13223,6 +13224,45 @@ GenTree* Compiler::fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac) } break; + case GT_INTRINSIC: + if (tree->AsIntrinsic()->gtIntrinsicName == + NI_System_Runtime_CompilerServices_RuntimeHelpers_IsKnownConstant) + { + // Should be expanded by the time it reaches CSE phase + assert(!optValnumCSE_phase); + + JITDUMP("\nExpanding RuntimeHelpers.IsKnownConstant to "); + if (op1->OperIsConst()) + { + // We're lucky to catch a constant here while importer was not + JITDUMP("true\n"); + DEBUG_DESTROY_NODE(tree, op1); + tree = gtNewIconNode(1); + } + else + { + GenTree* op1SideEffects = nullptr; + gtExtractSideEffList(op1, &op1SideEffects, GTF_ALL_EFFECT); + if (op1SideEffects != nullptr) + { + DEBUG_DESTROY_NODE(tree); + // Keep side-effects of op1 + tree = gtNewOperNode(GT_COMMA, TYP_INT, op1SideEffects, gtNewIconNode(0)); + JITDUMP("false with side effects:\n") + DISPTREE(tree); + } + else + { + JITDUMP("false\n"); + DEBUG_DESTROY_NODE(tree, op1); + tree = gtNewIconNode(0); + } + } + INDEBUG(tree->gtDebugFlags |= GTF_DEBUG_NODE_MORPHED); + return tree; + } + break; + default: break; } @@ -14148,18 +14188,45 @@ GenTree* Compiler::fgMorphSmpOpOptional(GenTreeOp* tree) GenTree* Compiler::fgMorphMultiOp(GenTreeMultiOp* multiOp) { gtUpdateNodeOperSideEffects(multiOp); + + bool dontCseConstArguments = false; +#if defined(FEATURE_HW_INTRINSICS) + // Opportunistically, avoid unexpected CSE for hw intrinsics with IMM arguments + if (multiOp->OperIs(GT_HWINTRINSIC)) + { + NamedIntrinsic hwIntrinsic = multiOp->AsHWIntrinsic()->GetHWIntrinsicId(); +#if defined(TARGET_XARCH) + if (HWIntrinsicInfo::lookupCategory(hwIntrinsic) == HW_Category_IMM) + { + dontCseConstArguments = true; + } +#elif defined(TARGET_ARMARCH) + if (HWIntrinsicInfo::HasImmediateOperand(hwIntrinsic)) + { + dontCseConstArguments = true; + } +#endif + } +#endif + for (GenTree** use : multiOp->UseEdges()) { *use = fgMorphTree(*use); multiOp->gtFlags |= ((*use)->gtFlags & GTF_ALL_EFFECT); + + if (dontCseConstArguments && (*use)->OperIsConst()) + { + (*use)->SetDoNotCSE(); + } } -#if defined(FEATURE_HW_INTRINSICS) && defined(TARGET_XARCH) +#if defined(FEATURE_HW_INTRINSICS) if (opts.OptimizationEnabled() && multiOp->OperIs(GT_HWINTRINSIC)) { GenTreeHWIntrinsic* hw = multiOp->AsHWIntrinsic(); switch (hw->GetHWIntrinsicId()) { +#if defined(TARGET_XARCH) case NI_SSE_Xor: case NI_SSE2_Xor: case NI_AVX_Xor: @@ -14185,6 +14252,36 @@ GenTree* Compiler::fgMorphMultiOp(GenTreeMultiOp* multiOp) } break; } +#endif + + case NI_Vector128_Create: +#if defined(TARGET_XARCH) + case NI_Vector256_Create: +#elif defined(TARGET_ARMARCH) + case NI_Vector64_Create: +#endif + { + bool hwAllArgsAreConst = true; + for (GenTree** use : multiOp->UseEdges()) + { + if (!(*use)->OperIsConst()) + { + hwAllArgsAreConst = false; + break; + } + } + + // Avoid unexpected CSE for constant arguments for Vector_.Create + // but only if all arguments are constants. + if (hwAllArgsAreConst) + { + for (GenTree** use : multiOp->UseEdges()) + { + (*use)->SetDoNotCSE(); + } + } + } + break; default: break; @@ -14725,7 +14822,7 @@ GenTree* Compiler::fgMorphTree(GenTree* tree, MorphAddrContext* mac) /* Is this a constant node? */ - if (kind & GTK_CONST) + if (tree->OperIsConst()) { tree = fgMorphConst(tree); goto DONE; @@ -15008,7 +15105,7 @@ void Compiler::fgMorphTreeDone(GenTree* tree, assert(((tree->gtDebugFlags & GTF_DEBUG_NODE_MORPHED) == 0) && "ERROR: Already morphed this node!"); } - if (tree->OperKind() & GTK_CONST) + if (tree->OperIsConst()) { goto DONE; } @@ -15103,7 +15200,7 @@ bool Compiler::fgFoldConditional(BasicBlock* block) GenTree* cond; cond = condTree->gtEffectiveVal(true); - if (cond->OperKind() & GTK_CONST) + if (cond->OperIsConst()) { /* Yupee - we folded the conditional! * Remove the conditional statement */ @@ -15327,7 +15424,7 @@ bool Compiler::fgFoldConditional(BasicBlock* block) GenTree* cond; cond = condTree->gtEffectiveVal(true); - if (cond->OperKind() & GTK_CONST) + if (cond->OperIsConst()) { /* Yupee - we folded the conditional! * Remove the conditional statement */ @@ -15722,7 +15819,7 @@ void Compiler::fgMorphStmts(BasicBlock* block) { GenTree* op1 = last->AsOp()->gtOp1; - if (op1->OperKind() & GTK_RELOP) + if (op1->OperIsCompare()) { /* Unmark the comparison node with GTF_RELOP_JMP_USED */ op1->gtFlags &= ~GTF_RELOP_JMP_USED; diff --git a/src/coreclr/jit/namedintrinsiclist.h b/src/coreclr/jit/namedintrinsiclist.h index 25733a41a9c9e..7b2108d3edd05 100644 --- a/src/coreclr/jit/namedintrinsiclist.h +++ b/src/coreclr/jit/namedintrinsiclist.h @@ -78,6 +78,7 @@ enum NamedIntrinsic : unsigned short NI_System_Runtime_CompilerServices_RuntimeHelpers_CreateSpan, NI_System_Runtime_CompilerServices_RuntimeHelpers_InitializeArray, + NI_System_Runtime_CompilerServices_RuntimeHelpers_IsKnownConstant, NI_System_String_get_Chars, NI_System_String_get_Length, diff --git a/src/coreclr/jit/optcse.cpp b/src/coreclr/jit/optcse.cpp index b39b2bd1425c4..f16fb917a589d 100644 --- a/src/coreclr/jit/optcse.cpp +++ b/src/coreclr/jit/optcse.cpp @@ -3515,8 +3515,10 @@ bool Compiler::optIsCSEcandidate(GenTree* tree) #if !CSE_CONSTS /* Don't bother with constants */ - if (tree->OperKind() & GTK_CONST) + if (tree->OperIsConst()) + { return false; + } #endif /* Check for some special cases */ diff --git a/src/coreclr/jit/optimizer.cpp b/src/coreclr/jit/optimizer.cpp index ec309793e9376..a6c9ea4d85c68 100644 --- a/src/coreclr/jit/optimizer.cpp +++ b/src/coreclr/jit/optimizer.cpp @@ -302,7 +302,7 @@ void Compiler::optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk) } // We only consider back-edges that are BBJ_COND or BBJ_ALWAYS for loops. - if ((predBlock->bbJumpKind != BBJ_COND) && (predBlock->bbJumpKind != BBJ_ALWAYS)) + if (!predBlock->KindIs(BBJ_COND, BBJ_ALWAYS)) { continue; } @@ -580,12 +580,12 @@ void Compiler::optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmar reportAfter(); } - if ((skipUnmarkLoop == false) && // - ((block->bbJumpKind == BBJ_ALWAYS) || (block->bbJumpKind == BBJ_COND)) && // - block->bbJumpDest->isLoopHead() && // - (block->bbJumpDest->bbNum <= block->bbNum) && // - fgDomsComputed && // - (fgCurBBEpochSize == fgDomBBcount + 1) && // + if ((skipUnmarkLoop == false) && // + block->KindIs(BBJ_ALWAYS, BBJ_COND) && // + block->bbJumpDest->isLoopHead() && // + (block->bbJumpDest->bbNum <= block->bbNum) && // + fgDomsComputed && // + (fgCurBBEpochSize == fgDomBBcount + 1) && // fgReachable(block->bbJumpDest, block)) { optUnmarkLoopBlocks(block->bbJumpDest, block); @@ -847,7 +847,7 @@ bool Compiler::optCheckIterInLoopTest( relop = test->gtGetOp2(); } - noway_assert(relop->OperKind() & GTK_RELOP); + noway_assert(relop->OperIsCompare()); GenTree* opr1 = relop->AsOp()->gtOp1; GenTree* opr2 = relop->AsOp()->gtOp2; @@ -1685,9 +1685,7 @@ class LoopSearch return false; } - if ((bottom->bbJumpKind == BBJ_EHFINALLYRET) || (bottom->bbJumpKind == BBJ_EHFILTERRET) || - (bottom->bbJumpKind == BBJ_EHCATCHRET) || (bottom->bbJumpKind == BBJ_CALLFINALLY) || - (bottom->bbJumpKind == BBJ_SWITCH)) + if (bottom->KindIs(BBJ_EHFINALLYRET, BBJ_EHFILTERRET, BBJ_EHCATCHRET, BBJ_CALLFINALLY, BBJ_SWITCH)) { // BBJ_EHFINALLYRET, BBJ_EHFILTERRET, BBJ_EHCATCHRET, and BBJ_CALLFINALLY can never form a loop. // BBJ_SWITCH that has a backward jump appears only for labeled break. @@ -1829,7 +1827,7 @@ class LoopSearch } } // Can we fall through into the loop? - else if (head->bbJumpKind == BBJ_NONE || head->bbJumpKind == BBJ_COND) + else if (head->KindIs(BBJ_NONE, BBJ_COND)) { // The ENTRY is at the TOP (a do-while loop) return top; @@ -2139,7 +2137,7 @@ class LoopSearch return nullptr; } - if ((newMoveAfter->bbJumpKind == BBJ_ALWAYS) || (newMoveAfter->bbJumpKind == BBJ_COND)) + if (newMoveAfter->KindIs(BBJ_ALWAYS, BBJ_COND)) { unsigned int destNum = newMoveAfter->bbJumpDest->bbNum; if ((destNum >= top->bbNum) && (destNum <= bottom->bbNum) && !loopBlocks.IsMember(destNum)) @@ -2329,8 +2327,8 @@ class LoopSearch } // Make sure we don't leave around a goto-next unless it's marked KEEP_BBJ_ALWAYS. - assert(((block->bbJumpKind != BBJ_COND) && (block->bbJumpKind != BBJ_ALWAYS)) || - (block->bbJumpDest != newNext) || ((block->bbFlags & BBF_KEEP_BBJ_ALWAYS) != 0)); + assert(!block->KindIs(BBJ_COND, BBJ_ALWAYS) || (block->bbJumpDest != newNext) || + ((block->bbFlags & BBF_KEEP_BBJ_ALWAYS) != 0)); return newBlock; } @@ -7574,6 +7572,8 @@ void Compiler::fgCreateLoopPreHeader(unsigned lnum) fgAddRefPred(preHead, predBlock); } } while (++jumpTab, --jumpCnt); + + UpdateSwitchTableTarget(predBlock, entry, preHead); break; default: @@ -7850,24 +7850,16 @@ bool Compiler::optComputeLoopSideEffectsOfBlock(BasicBlock* blk) } else { - // We are only interested in IsFieldAddr()'s fldSeq out parameter. - // - GenTree* obj = nullptr; // unused - GenTree* staticOffset = nullptr; // unused - FieldSeqNode* fldSeq = nullptr; - - if (arg->IsFieldAddr(this, &obj, &staticOffset, &fldSeq) && - (fldSeq != FieldSeqStore::NotAField())) + GenTree* baseAddr = nullptr; + FieldSeqNode* fldSeq = nullptr; + if (arg->IsFieldAddr(this, &baseAddr, &fldSeq)) { - // Get the first (object) field from field seq. GcHeap[field] will yield the "field map". - assert(fldSeq != nullptr); - if (fldSeq->IsFirstElemFieldSeq()) - { - fldSeq = fldSeq->m_next; - assert(fldSeq != nullptr); - } + assert((fldSeq != nullptr) && (fldSeq != FieldSeqStore::NotAField()) && + !fldSeq->IsPseudoField()); - AddModifiedFieldAllContainingLoops(mostNestedLoop, fldSeq->m_fieldHnd); + FieldKindForVN fieldKind = + (baseAddr != nullptr) ? FieldKindForVN::WithBaseAddr : FieldKindForVN::SimpleStatic; + AddModifiedFieldAllContainingLoops(mostNestedLoop, fldSeq->GetFieldHandle(), fieldKind); // Conservatively assume byrefs may alias this object. memoryHavoc |= memoryKindSet(ByrefExposed); } @@ -7893,7 +7885,8 @@ bool Compiler::optComputeLoopSideEffectsOfBlock(BasicBlock* blk) } else if (lhs->OperGet() == GT_CLS_VAR) { - AddModifiedFieldAllContainingLoops(mostNestedLoop, lhs->AsClsVar()->gtClsVarHnd); + AddModifiedFieldAllContainingLoops(mostNestedLoop, lhs->AsClsVar()->gtClsVarHnd, + FieldKindForVN::SimpleStatic); // Conservatively assume byrefs may alias this static field memoryHavoc |= memoryKindSet(ByrefExposed); } @@ -8073,12 +8066,12 @@ void Compiler::AddVariableLivenessAllContainingLoops(unsigned lnum, BasicBlock* } // Adds "fldHnd" to the set of modified fields of "lnum" and any parent loops. -void Compiler::AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd) +void Compiler::AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd, FieldKindForVN fieldKind) { assert(0 <= lnum && lnum < optLoopCount); while (lnum != BasicBlock::NOT_IN_LOOP) { - optLoopTable[lnum].AddModifiedField(this, fldHnd); + optLoopTable[lnum].AddModifiedField(this, fldHnd, fieldKind); lnum = optLoopTable[lnum].lpParent; } } diff --git a/src/coreclr/jit/rangecheck.cpp b/src/coreclr/jit/rangecheck.cpp index 4a475806148b7..56ad0323fd6de 100644 --- a/src/coreclr/jit/rangecheck.cpp +++ b/src/coreclr/jit/rangecheck.cpp @@ -869,7 +869,7 @@ void RangeCheck::MergeAssertion(BasicBlock* block, GenTree* op, Range* pRange DE JITDUMP("Merge assertions from pred " FMT_BB " edge: ", pred->bbNum); Compiler::optDumpAssertionIndices(assertions, "\n"); } - else if ((pred->bbJumpKind == BBJ_COND || pred->bbJumpKind == BBJ_ALWAYS) && pred->bbJumpDest == block) + else if (pred->KindIs(BBJ_COND, BBJ_ALWAYS) && (pred->bbJumpDest == block)) { if (m_pCompiler->bbJtrueAssertionOut != nullptr) { diff --git a/src/coreclr/jit/rationalize.cpp b/src/coreclr/jit/rationalize.cpp index 5e54ca8bd94d4..18503a4ce3c53 100644 --- a/src/coreclr/jit/rationalize.cpp +++ b/src/coreclr/jit/rationalize.cpp @@ -416,13 +416,10 @@ void Rationalizer::RewriteAssignment(LIR::Use& use) } GenTreeSIMD* simdTree = comp->gtNewSIMDNode(simdType, initVal, SIMDIntrinsicInit, simdBaseJitType, genTypeSize(simdType)); - assignment->AsOp()->gtOp2 = simdTree; - value = simdTree; - initVal->gtNext = simdTree; - simdTree->gtPrev = initVal; + assignment->gtOp2 = simdTree; + value = simdTree; - simdTree->gtNext = location; - location->gtPrev = simdTree; + BlockRange().InsertAfter(initVal, simdTree); } } #endif // FEATURE_SIMD diff --git a/src/coreclr/jit/redundantbranchopts.cpp b/src/coreclr/jit/redundantbranchopts.cpp index 5417308a9bd00..e87cf762d1cf4 100644 --- a/src/coreclr/jit/redundantbranchopts.cpp +++ b/src/coreclr/jit/redundantbranchopts.cpp @@ -132,7 +132,7 @@ bool Compiler::optRedundantBranch(BasicBlock* const block) assert(domJumpTree->OperIs(GT_JTRUE)); GenTree* const domCmpTree = domJumpTree->AsOp()->gtGetOp1(); - if (domCmpTree->OperKind() & GTK_RELOP) + if (domCmpTree->OperIsCompare()) { // We can use liberal VNs here, as bounds checks are not yet // manifest explicitly as relops. diff --git a/src/coreclr/jit/simdashwintrinsic.cpp b/src/coreclr/jit/simdashwintrinsic.cpp index 73a4863302581..32a1ce5b66de1 100644 --- a/src/coreclr/jit/simdashwintrinsic.cpp +++ b/src/coreclr/jit/simdashwintrinsic.cpp @@ -509,9 +509,6 @@ GenTree* Compiler::impSimdAsHWIntrinsicSpecial(NamedIntrinsic intrinsic, case NI_VectorT128_Sum: { - // TODO-XArch-CQ: We could support this all the way down to SSE2 and that might be - // worthwhile so we can accelerate cases like byte/sbyte and long/ulong - if (varTypeIsFloating(simdBaseType)) { if (!compOpportunisticallyDependsOn(InstructionSet_SSE3)) @@ -723,60 +720,9 @@ GenTree* Compiler::impSimdAsHWIntrinsicSpecial(NamedIntrinsic intrinsic, } case NI_VectorT128_Sum: - { - GenTree* tmp; - unsigned vectorLength = getSIMDVectorLength(simdSize, simdBaseType); - int haddCount = genLog2(vectorLength); - - NamedIntrinsic horizontalAdd = - varTypeIsFloating(simdBaseType) ? NI_SSE3_HorizontalAdd : NI_SSSE3_HorizontalAdd; - - for (int i = 0; i < haddCount; i++) - { - op1 = impCloneExpr(op1, &tmp, clsHnd, (unsigned)CHECK_SPILL_ALL, - nullptr DEBUGARG("Clone op1 for Vector.Sum")); - op1 = gtNewSimdAsHWIntrinsicNode(simdType, op1, tmp, horizontalAdd, simdBaseJitType, simdSize); - } - - return gtNewSimdAsHWIntrinsicNode(retType, op1, NI_Vector128_ToScalar, simdBaseJitType, simdSize); - } - case NI_VectorT256_Sum: { - // HorizontalAdd combines pairs so we need log2(vectorLength) passes to sum all elements together. - unsigned vectorLength = getSIMDVectorLength(simdSize, simdBaseType); - int haddCount = genLog2(vectorLength) - 1; // Minus 1 because for the last pass we split the vector - // to low / high and add them together. - GenTree* tmp; - NamedIntrinsic horizontalAdd = NI_AVX2_HorizontalAdd; - NamedIntrinsic add = NI_SSE2_Add; - - if (simdBaseType == TYP_DOUBLE) - { - horizontalAdd = NI_AVX_HorizontalAdd; - } - else if (simdBaseType == TYP_FLOAT) - { - horizontalAdd = NI_AVX_HorizontalAdd; - add = NI_SSE_Add; - } - - for (int i = 0; i < haddCount; i++) - { - op1 = impCloneExpr(op1, &tmp, clsHnd, (unsigned)CHECK_SPILL_ALL, - nullptr DEBUGARG("Clone op1 for Vector.Sum")); - op1 = gtNewSimdAsHWIntrinsicNode(simdType, op1, tmp, horizontalAdd, simdBaseJitType, simdSize); - } - - op1 = impCloneExpr(op1, &tmp, clsHnd, (unsigned)CHECK_SPILL_ALL, - nullptr DEBUGARG("Clone op1 for Vector.Sum")); - op1 = gtNewSimdAsHWIntrinsicNode(TYP_SIMD16, op1, gtNewIconNode(0x01, TYP_INT), - NI_AVX_ExtractVector128, simdBaseJitType, simdSize); - - tmp = gtNewSimdAsHWIntrinsicNode(simdType, tmp, NI_Vector256_GetLower, simdBaseJitType, simdSize); - op1 = gtNewSimdAsHWIntrinsicNode(TYP_SIMD16, op1, tmp, add, simdBaseJitType, 16); - - return gtNewSimdAsHWIntrinsicNode(retType, op1, NI_Vector128_ToScalar, simdBaseJitType, 16); + return gtNewSimdSumNode(retType, op1, simdBaseJitType, simdSize, /* isSimdAsHWIntrinsic */ true); } case NI_VectorT128_WidenLower: @@ -842,50 +788,7 @@ GenTree* Compiler::impSimdAsHWIntrinsicSpecial(NamedIntrinsic intrinsic, case NI_VectorT128_Sum: { - GenTree* tmp; - - switch (simdBaseType) - { - case TYP_BYTE: - case TYP_UBYTE: - case TYP_SHORT: - case TYP_USHORT: - case TYP_INT: - case TYP_UINT: - { - tmp = gtNewSimdAsHWIntrinsicNode(simdType, op1, NI_AdvSimd_Arm64_AddAcross, simdBaseJitType, - simdSize); - return gtNewSimdAsHWIntrinsicNode(retType, tmp, NI_Vector64_ToScalar, simdBaseJitType, 8); - } - case TYP_FLOAT: - { - unsigned vectorLength = getSIMDVectorLength(simdSize, simdBaseType); - int haddCount = genLog2(vectorLength); - - for (int i = 0; i < haddCount; i++) - { - op1 = impCloneExpr(op1, &tmp, clsHnd, (unsigned)CHECK_SPILL_ALL, - nullptr DEBUGARG("Clone op1 for Vector.Sum")); - op1 = gtNewSimdAsHWIntrinsicNode(simdType, op1, tmp, NI_AdvSimd_Arm64_AddPairwise, - simdBaseJitType, simdSize); - } - - return gtNewSimdAsHWIntrinsicNode(retType, op1, NI_Vector128_ToScalar, simdBaseJitType, - simdSize); - } - case TYP_DOUBLE: - case TYP_LONG: - case TYP_ULONG: - { - op1 = gtNewSimdAsHWIntrinsicNode(TYP_SIMD8, op1, NI_AdvSimd_Arm64_AddPairwiseScalar, - simdBaseJitType, simdSize); - return gtNewSimdAsHWIntrinsicNode(retType, op1, NI_Vector64_ToScalar, simdBaseJitType, 8); - } - default: - { - unreached(); - } - } + return gtNewSimdSumNode(retType, op1, simdBaseJitType, simdSize, /* isSimdAsHWIntrinsic */ true); } case NI_VectorT128_WidenLower: @@ -1046,6 +949,27 @@ GenTree* Compiler::impSimdAsHWIntrinsicSpecial(NamedIntrinsic intrinsic, /* isSimdAsHWIntrinsic */ true); } + case NI_VectorT128_ShiftLeft: + case NI_VectorT256_ShiftLeft: + { + return gtNewSimdBinOpNode(GT_LSH, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ true); + } + + case NI_VectorT128_ShiftRightArithmetic: + case NI_VectorT256_ShiftRightArithmetic: + { + return gtNewSimdBinOpNode(GT_RSH, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ true); + } + + case NI_VectorT128_ShiftRightLogical: + case NI_VectorT256_ShiftRightLogical: + { + return gtNewSimdBinOpNode(GT_RSZ, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ true); + } + #elif defined(TARGET_ARM64) case NI_Vector2_CreateBroadcast: case NI_Vector3_CreateBroadcast: @@ -1089,6 +1013,24 @@ GenTree* Compiler::impSimdAsHWIntrinsicSpecial(NamedIntrinsic intrinsic, return gtNewSimdBinOpNode(GT_MUL, retType, op1, op2, simdBaseJitType, simdSize, /* isSimdAsHWIntrinsic */ true); } + + case NI_VectorT128_ShiftLeft: + { + return gtNewSimdBinOpNode(GT_LSH, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ true); + } + + case NI_VectorT128_ShiftRightArithmetic: + { + return gtNewSimdBinOpNode(GT_RSH, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ true); + } + + case NI_VectorT128_ShiftRightLogical: + { + return gtNewSimdBinOpNode(GT_RSZ, retType, op1, op2, simdBaseJitType, simdSize, + /* isSimdAsHWIntrinsic */ true); + } #else #error Unsupported platform #endif // !TARGET_XARCH && !TARGET_ARM64 diff --git a/src/coreclr/jit/simdashwintrinsiclistarm64.h b/src/coreclr/jit/simdashwintrinsiclistarm64.h index 82cf2fb182766..382f78346add9 100644 --- a/src/coreclr/jit/simdashwintrinsiclistarm64.h +++ b/src/coreclr/jit/simdashwintrinsiclistarm64.h @@ -138,6 +138,9 @@ SIMD_AS_HWINTRINSIC_ID(VectorT128, op_Explicit, SIMD_AS_HWINTRINSIC_ID(VectorT128, op_Inequality, 2, {NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, op_Multiply, 2, {NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply, NI_Illegal, NI_Illegal, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, op_Subtraction, 2, {NI_AdvSimd_Subtract, NI_AdvSimd_Subtract, NI_AdvSimd_Subtract, NI_AdvSimd_Subtract, NI_AdvSimd_Subtract, NI_AdvSimd_Subtract, NI_AdvSimd_Subtract, NI_AdvSimd_Subtract, NI_AdvSimd_Subtract, NI_AdvSimd_Arm64_Subtract}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT128, ShiftLeft, 2, {NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT128, ShiftRightArithmetic, 2, {NI_VectorT128_ShiftRightArithmetic, NI_Illegal, NI_VectorT128_ShiftRightArithmetic, NI_Illegal, NI_VectorT128_ShiftRightArithmetic, NI_Illegal, NI_VectorT128_ShiftRightArithmetic, NI_Illegal, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT128, ShiftRightLogical, 2, {NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, SquareRoot, 1, {NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_AdvSimd_Arm64_Sqrt, NI_AdvSimd_Arm64_Sqrt}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, Sum, 1, {NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, WidenLower, 1, {NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower}, SimdAsHWIntrinsicFlag::None) diff --git a/src/coreclr/jit/simdashwintrinsiclistxarch.h b/src/coreclr/jit/simdashwintrinsiclistxarch.h index e3147ae9c129a..e407b6d0b7965 100644 --- a/src/coreclr/jit/simdashwintrinsiclistxarch.h +++ b/src/coreclr/jit/simdashwintrinsiclistxarch.h @@ -138,6 +138,9 @@ SIMD_AS_HWINTRINSIC_ID(VectorT128, op_Explicit, SIMD_AS_HWINTRINSIC_ID(VectorT128, op_Inequality, 2, {NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality, NI_Vector128_op_Inequality}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, op_Multiply, 2, {NI_Illegal, NI_Illegal, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply, NI_Illegal, NI_Illegal, NI_VectorT128_op_Multiply, NI_VectorT128_op_Multiply}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, op_Subtraction, 2, {NI_SSE2_Subtract, NI_SSE2_Subtract, NI_SSE2_Subtract, NI_SSE2_Subtract, NI_SSE2_Subtract, NI_SSE2_Subtract, NI_SSE2_Subtract, NI_SSE2_Subtract, NI_SSE_Subtract, NI_SSE2_Subtract}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT128, ShiftLeft, 2, {NI_Illegal, NI_Illegal, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_VectorT128_ShiftLeft, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT128, ShiftRightArithmetic, 2, {NI_Illegal, NI_Illegal, NI_VectorT128_ShiftRightArithmetic, NI_Illegal, NI_VectorT128_ShiftRightArithmetic, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT128, ShiftRightLogical, 2, {NI_Illegal, NI_Illegal, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_VectorT128_ShiftRightLogical, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, SquareRoot, 1, {NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_SSE_Sqrt, NI_SSE2_Sqrt}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, Sum, 1, {NI_Illegal, NI_Illegal, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_VectorT128_Sum, NI_Illegal, NI_Illegal, NI_VectorT128_Sum, NI_VectorT128_Sum}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT128, WidenLower, 1, {NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower, NI_VectorT128_WidenLower}, SimdAsHWIntrinsicFlag::None) @@ -186,6 +189,9 @@ SIMD_AS_HWINTRINSIC_ID(VectorT256, op_Explicit, SIMD_AS_HWINTRINSIC_ID(VectorT256, op_Inequality, 2, {NI_Vector256_op_Inequality, NI_Vector256_op_Inequality, NI_Vector256_op_Inequality, NI_Vector256_op_Inequality, NI_Vector256_op_Inequality, NI_Vector256_op_Inequality, NI_Vector256_op_Inequality, NI_Vector256_op_Inequality, NI_Vector256_op_Inequality, NI_Vector256_op_Inequality}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT256, op_Multiply, 2, {NI_Illegal, NI_Illegal, NI_VectorT256_op_Multiply, NI_VectorT256_op_Multiply, NI_VectorT256_op_Multiply, NI_VectorT256_op_Multiply, NI_Illegal, NI_Illegal, NI_VectorT256_op_Multiply, NI_VectorT256_op_Multiply}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT256, op_Subtraction, 2, {NI_AVX2_Subtract, NI_AVX2_Subtract, NI_AVX2_Subtract, NI_AVX2_Subtract, NI_AVX2_Subtract, NI_AVX2_Subtract, NI_AVX2_Subtract, NI_AVX2_Subtract, NI_AVX_Subtract, NI_AVX_Subtract}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT256, ShiftLeft, 2, {NI_Illegal, NI_Illegal, NI_VectorT256_ShiftLeft, NI_VectorT256_ShiftLeft, NI_VectorT256_ShiftLeft, NI_VectorT256_ShiftLeft, NI_VectorT256_ShiftLeft, NI_VectorT256_ShiftLeft, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT256, ShiftRightArithmetic, 2, {NI_Illegal, NI_Illegal, NI_VectorT256_ShiftRightArithmetic, NI_Illegal, NI_VectorT256_ShiftRightArithmetic, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) +SIMD_AS_HWINTRINSIC_ID(VectorT256, ShiftRightLogical, 2, {NI_Illegal, NI_Illegal, NI_VectorT256_ShiftRightLogical, NI_VectorT256_ShiftRightLogical, NI_VectorT256_ShiftRightLogical, NI_VectorT256_ShiftRightLogical, NI_VectorT256_ShiftRightLogical, NI_VectorT256_ShiftRightLogical, NI_Illegal, NI_Illegal}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT256, SquareRoot, 1, {NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_Illegal, NI_AVX_Sqrt, NI_AVX_Sqrt}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT256, Sum, 1, {NI_Illegal, NI_Illegal, NI_VectorT256_Sum, NI_VectorT256_Sum, NI_VectorT256_Sum, NI_VectorT256_Sum, NI_Illegal, NI_Illegal, NI_VectorT256_Sum, NI_VectorT256_Sum}, SimdAsHWIntrinsicFlag::None) SIMD_AS_HWINTRINSIC_ID(VectorT256, WidenLower, 1, {NI_VectorT256_WidenLower, NI_VectorT256_WidenLower, NI_VectorT256_WidenLower, NI_VectorT256_WidenLower, NI_VectorT256_WidenLower, NI_VectorT256_WidenLower, NI_VectorT256_WidenLower, NI_VectorT256_WidenLower, NI_VectorT256_WidenLower, NI_VectorT256_WidenLower}, SimdAsHWIntrinsicFlag::None) diff --git a/src/coreclr/jit/targetarm64.h b/src/coreclr/jit/targetarm64.h index cdab21582ffce..4cc6b63f73009 100644 --- a/src/coreclr/jit/targetarm64.h +++ b/src/coreclr/jit/targetarm64.h @@ -11,8 +11,10 @@ #define ROUND_FLOAT 0 // Do not round intermed float expression results #define CPU_HAS_BYTE_REGS 0 - #define CPBLK_UNROLL_LIMIT 64 // Upper bound to let the code generator to loop unroll CpBlk. - #define INITBLK_UNROLL_LIMIT 64 // Upper bound to let the code generator to loop unroll InitBlk. + #define CPBLK_UNROLL_LIMIT 64 // Upper bound to let the code generator to loop unroll CpBlk + #define CPBLK_LCL_UNROLL_LIMIT 128 // Upper bound to let the code generator to loop unroll CpBlk (when both srcAddr and dstAddr point to the stack) + #define INITBLK_UNROLL_LIMIT 64 // Upper bound to let the code generator to loop unroll InitBlk + #define INITBLK_LCL_UNROLL_LIMIT 128 // Upper bound to let the code generator to loop unroll InitBlk (when dstAddr points to the stack) #ifdef FEATURE_SIMD #define ALIGN_SIMD_TYPES 1 // whether SIMD type locals are to be aligned diff --git a/src/coreclr/jit/valuenum.cpp b/src/coreclr/jit/valuenum.cpp index 99bf197d8efe3..cc9fb0f38d249 100644 --- a/src/coreclr/jit/valuenum.cpp +++ b/src/coreclr/jit/valuenum.cpp @@ -3889,13 +3889,8 @@ ValueNum ValueNumStore::VNApplySelectors(ValueNumKind vnk, { for (FieldSeqNode* field = fieldSeq; field != nullptr; field = field->m_next) { - // Skip any "FirstElem" pseudo-fields or any "ConstantIndex" pseudo-fields. - if (field->IsPseudoField()) - { - continue; - } - assert(field != FieldSeqStore::NotAField()); + assert(!field->IsPseudoField()); JITDUMP(" VNApplySelectors:\n"); var_types fieldType; @@ -4054,20 +4049,13 @@ ValueNum ValueNumStore::VNApplySelectorsAssign( else { assert(fieldSeq != FieldSeqStore::NotAField()); - - // Skip any "FirstElem" pseudo-fields or any "ConstantIndex" pseudo-fields - // These will occur, at least, in struct static expressions, for method table offsets. - if (fieldSeq->IsPseudoField()) - { - return VNApplySelectorsAssign(vnk, map, fieldSeq->m_next, value, dstIndType); - } + assert(!fieldSeq->IsPseudoField()); if (fieldSeq->m_next == nullptr) { JITDUMP(" VNApplySelectorsAssign:\n"); } - // Otherwise, fldHnd is a real field handle. var_types fieldType; ValueNum fldHndVN = VNForFieldSelector(fieldSeq->GetFieldHandle(), &fieldType); @@ -4240,7 +4228,7 @@ ValueNum ValueNumStore::ExtendPtrVN(GenTree* opA, FieldSeqNode* fldSeq) else if (funcApp.m_func == VNF_PtrToStatic) { ValueNum fldSeqVN = VNForFieldSeq(fldSeq); - res = VNForFunc(TYP_BYREF, VNF_PtrToStatic, FieldSeqVNAppend(funcApp.m_args[0], fldSeqVN)); + res = VNForFunc(TYP_BYREF, VNF_PtrToStatic, funcApp.m_args[0], FieldSeqVNAppend(funcApp.m_args[1], fldSeqVN)); } else if (funcApp.m_func == VNF_PtrToArrElem) { @@ -4663,7 +4651,7 @@ ValueNum ValueNumStore::GetRelatedRelop(ValueNum vn, VN_RELATION_KIND vrk) { const genTreeOps op = (genTreeOps)newFunc; - if (!GenTree::OperIsRelop(op)) + if (!GenTree::OperIsCompare(op)) { return NoVN; } @@ -4700,7 +4688,7 @@ ValueNum ValueNumStore::GetRelatedRelop(ValueNum vn, VN_RELATION_KIND vrk) { const genTreeOps op = (genTreeOps)newFunc; - if (!GenTree::OperIsRelop(op)) + if (!GenTree::OperIsCompare(op)) { return NoVN; } @@ -4767,7 +4755,7 @@ bool ValueNumStore::IsVNRelop(ValueNum vn) else { const genTreeOps op = (genTreeOps)func; - return GenTree::OperIsRelop(op); + return GenTree::OperIsCompare(op); } } @@ -7140,8 +7128,9 @@ ValueNum Compiler::fgMemoryVNForLoopSideEffects(MemoryKind memoryKind, for (Compiler::LoopDsc::FieldHandleSet::KeyIterator ki = fieldsMod->Begin(); !ki.Equal(fieldsMod->End()); ++ki) { - CORINFO_FIELD_HANDLE fldHnd = ki.Get(); - ValueNum fldHndVN = vnStore->VNForHandle(ssize_t(fldHnd), GTF_ICON_FIELD_HDL); + CORINFO_FIELD_HANDLE fldHnd = ki.Get(); + FieldKindForVN fieldKind = ki.GetValue(); + ValueNum fldHndVN = vnStore->VNForHandle(ssize_t(fldHnd), GTF_ICON_FIELD_HDL); #ifdef DEBUG if (verbose) @@ -7152,9 +7141,9 @@ ValueNum Compiler::fgMemoryVNForLoopSideEffects(MemoryKind memoryKind, } #endif // DEBUG - // Instance field maps get a placeholder type - they do not represent "singular" - // values. Static field maps, on the other hand, do, and so must be given proper types. - var_types fldMapType = eeIsFieldStatic(fldHnd) ? eeGetFieldType(fldHnd) : TYP_MEM; + // Instance fields and "complex" statics select "first field maps" + // with a placeholder type. "Simple" statics select their own types. + var_types fldMapType = (fieldKind == FieldKindForVN::WithBaseAddr) ? TYP_MEM : eeGetFieldType(fldHnd); newMemoryVN = vnStore->VNForMapStore(newMemoryVN, fldHndVN, vnStore->VNForExpr(entryBlock, fldMapType)); } @@ -7747,9 +7736,8 @@ void Compiler::fgValueNumberAssignment(GenTreeOp* tree) // Was the argument of the GT_IND the address of a local, handled above? if (!wasLocal) { - GenTree* obj = nullptr; - GenTree* staticOffset = nullptr; - FieldSeqNode* fldSeq = nullptr; + GenTree* baseAddr = nullptr; + FieldSeqNode* fldSeq = nullptr; // Is the LHS an array index expression? if (argIsVNFunc && funcApp.m_func == VNF_PtrToArrElem) @@ -7808,108 +7796,71 @@ void Compiler::fgValueNumberAssignment(GenTreeOp* tree) rhsVNPair.GetLiberal(), lhs->TypeGet()); recordGcHeapStore(tree, heapVN DEBUGARG("ArrIndexAssign (case 2)")); } - else if (arg->IsFieldAddr(this, &obj, &staticOffset, &fldSeq)) + else if (arg->IsFieldAddr(this, &baseAddr, &fldSeq)) { - if (fldSeq == FieldSeqStore::NotAField()) - { - fgMutateGcHeap(tree DEBUGARG("NotAField")); - } - else - { - assert(fldSeq != nullptr); -#ifdef DEBUG - CORINFO_CLASS_HANDLE fldCls = info.compCompHnd->getFieldClass(fldSeq->m_fieldHnd); - if (obj != nullptr) - { - // Make sure that the class containing it is not a value class (as we are expecting - // an instance field) - assert((info.compCompHnd->getClassAttribs(fldCls) & CORINFO_FLG_VALUECLASS) == 0); - assert(staticOffset == nullptr); - } -#endif // DEBUG + assert((fldSeq != nullptr) && (fldSeq != FieldSeqStore::NotAField()) && !fldSeq->IsPseudoField()); - // Get the first (instance or static) field from field seq. GcHeap[field] will yield - // the "field map". - if (fldSeq->IsFirstElemFieldSeq()) - { - fldSeq = fldSeq->m_next; - assert(fldSeq != nullptr); - } - - // The value number from the rhs of the assignment - ValueNum storeVal = rhsVNPair.GetLiberal(); - ValueNum newHeapVN = ValueNumStore::NoVN; + // The value number from the rhs of the assignment + ValueNum storeVal = rhsVNPair.GetLiberal(); + ValueNum newHeapVN = ValueNumStore::NoVN; - // We will check that the final field in the sequence matches 'indType'. - var_types indType = lhs->TypeGet(); - - // when (obj != nullptr) we have an instance field, otherwise a static field - // when (staticOffset != nullptr) it represents a offset into a static or the call to - // Shared Static Base - if ((obj != nullptr) || (staticOffset != nullptr)) - { - var_types firstFieldType; - ValueNum firstFieldSelectorVN = - vnStore->VNForFieldSelector(fldSeq->GetFieldHandle(), &firstFieldType); + // We will check that the final field in the sequence matches 'indType'. + var_types indType = lhs->TypeGet(); - // Construct the "field map" VN. It represents memory state of the first field - // of all objects on the heap. This is our primary map. - ValueNum fldMapVN = vnStore->VNForMapSelect(VNK_Liberal, TYP_MEM, fgCurMemoryVN[GcHeap], - firstFieldSelectorVN); + if (baseAddr != nullptr) + { + // Instance field / "complex" static: heap[field][baseAddr][struct fields...] = storeVal. - ValueNum firstFieldValueSelectorVN = ValueNumStore::NoVN; - if (obj != nullptr) - { - firstFieldValueSelectorVN = vnStore->VNLiberalNormalValue(obj->gtVNPair); - } - else // (staticOffset != nullptr) - { - firstFieldValueSelectorVN = vnStore->VNLiberalNormalValue(staticOffset->gtVNPair); - } + var_types firstFieldType; + ValueNum firstFieldSelectorVN = + vnStore->VNForFieldSelector(fldSeq->GetFieldHandle(), &firstFieldType); - ValueNum newFirstFieldValueVN = ValueNumStore::NoVN; - // Optimization: avoid traversting the maps for the value of the first field if - // we do not need it, which is the case if the rest of the field sequence is empty. - if (fldSeq->m_next == nullptr) - { - newFirstFieldValueVN = vnStore->VNApplySelectorsAssignTypeCoerce(storeVal, indType); - } - else - { - // Construct the ValueNumber for fldMap[obj/offset]. This (struct) - // map represents the specific field we're looking to store to. - ValueNum firstFieldValueVN = - vnStore->VNForMapSelect(VNK_Liberal, firstFieldType, fldMapVN, - firstFieldValueSelectorVN); - - // Construct the maps updating the rest of the fields in the sequence. - newFirstFieldValueVN = - vnStore->VNApplySelectorsAssign(VNK_Liberal, firstFieldValueVN, fldSeq->m_next, - storeVal, indType); - } + // Construct the "field map" VN. It represents memory state of the first field + // of all objects on the heap. This is our primary map. + ValueNum fldMapVN = + vnStore->VNForMapSelect(VNK_Liberal, TYP_MEM, fgCurMemoryVN[GcHeap], firstFieldSelectorVN); - // Finally, construct the new field map... - ValueNum newFldMapVN = - vnStore->VNForMapStore(fldMapVN, firstFieldValueSelectorVN, newFirstFieldValueVN); + ValueNum firstFieldValueSelectorVN = vnStore->VNLiberalNormalValue(baseAddr->gtVNPair); - // ...and a new value for the heap. - newHeapVN = - vnStore->VNForMapStore(fgCurMemoryVN[GcHeap], firstFieldSelectorVN, newFldMapVN); + ValueNum newFirstFieldValueVN = ValueNumStore::NoVN; + // Optimization: avoid traversting the maps for the value of the first field if + // we do not need it, which is the case if the rest of the field sequence is empty. + if (fldSeq->m_next == nullptr) + { + newFirstFieldValueVN = vnStore->VNApplySelectorsAssignTypeCoerce(storeVal, indType); } else { - // Plain static field. - newHeapVN = vnStore->VNApplySelectorsAssign(VNK_Liberal, fgCurMemoryVN[GcHeap], fldSeq, - storeVal, indType); + // Construct the ValueNumber for fldMap[baseAddr]. This (struct) + // map represents the specific field we're looking to store to. + ValueNum firstFieldValueVN = vnStore->VNForMapSelect(VNK_Liberal, firstFieldType, fldMapVN, + firstFieldValueSelectorVN); + + // Construct the maps updating the struct fields in the sequence. + newFirstFieldValueVN = vnStore->VNApplySelectorsAssign(VNK_Liberal, firstFieldValueVN, + fldSeq->m_next, storeVal, indType); } - // It is not strictly necessary to set the lhs value number, - // but the dumps read better with it set to the 'storeVal' that we just computed - lhs->gtVNPair.SetBoth(storeVal); + // Finally, construct the new field map... + ValueNum newFldMapVN = + vnStore->VNForMapStore(fldMapVN, firstFieldValueSelectorVN, newFirstFieldValueVN); - // Update the GcHeap value. - recordGcHeapStore(tree, newHeapVN DEBUGARG("StoreField")); + // ...and a new value for the heap. + newHeapVN = vnStore->VNForMapStore(fgCurMemoryVN[GcHeap], firstFieldSelectorVN, newFldMapVN); } + else + { + // "Simple" static: heap[field][struct fields...] = storeVal. + newHeapVN = vnStore->VNApplySelectorsAssign(VNK_Liberal, fgCurMemoryVN[GcHeap], fldSeq, + storeVal, indType); + } + + // It is not strictly necessary to set the lhs value number, + // but the dumps read better with it set to the 'storeVal' that we just computed + lhs->gtVNPair.SetBoth(storeVal); + + // Update the GcHeap value. + recordGcHeapStore(tree, newHeapVN DEBUGARG("StoreField")); } else { @@ -7957,23 +7908,19 @@ void Compiler::fgValueNumberAssignment(GenTreeOp* tree) fgMutateGcHeap(lhs DEBUGARG("GTF_CLS_VAR - store")); // always change fgCurMemoryVN } - // We model statics as indices into GcHeap (which is a subset of ByrefExposed). - FieldSeqNode* fldSeqForStaticVar = GetFieldSeqStore()->CreateSingleton(lhs->AsClsVar()->gtClsVarHnd); - assert(fldSeqForStaticVar != FieldSeqStore::NotAField()); - - ValueNum storeVal = rhsVNPair.GetLiberal(); // The value number from the rhs of the assignment - storeVal = vnStore->VNApplySelectorsAssign(VNK_Liberal, fgCurMemoryVN[GcHeap], fldSeqForStaticVar, storeVal, - lhs->TypeGet()); + FieldSeqNode* fldSeq = lhs->AsClsVar()->gtFieldSeq; + assert(fldSeq != nullptr); - // It is not strictly necessary to set the lhs value number, - // but the dumps read better with it set to the 'storeVal' that we just computed - lhs->gtVNPair.SetBoth(storeVal); + // We model statics as indices into GcHeap (which is a subset of ByrefExposed). + ValueNum storeVal = rhsVNPair.GetLiberal(); + ValueNum newHeapVN = + vnStore->VNApplySelectorsAssign(VNK_Liberal, fgCurMemoryVN[GcHeap], fldSeq, storeVal, lhs->TypeGet()); // bbMemoryDef must include GcHeap for any block that mutates the GC heap assert((compCurBB->bbMemoryDef & memoryKindSet(GcHeap)) != 0); // Update the field map for the fgCurMemoryVN and SSA for the tree - recordGcHeapStore(tree, storeVal DEBUGARG("Static Field store")); + recordGcHeapStore(tree, newHeapVN DEBUGARG("Static Field store")); } break; @@ -8175,7 +8122,7 @@ void Compiler::fgValueNumberBlockAssignment(GenTree* tree) if (srcAddrFuncApp.m_func == VNF_PtrToStatic) { var_types indType = lclVarTree->TypeGet(); - ValueNum fieldSeqVN = srcAddrFuncApp.m_args[0]; + ValueNum fieldSeqVN = srcAddrFuncApp.m_args[1]; FieldSeqNode* fldSeqForStaticVar = vnStore->FieldSeqVNToFieldSeq(fieldSeqVN); #ifdef DEBUG FieldSeqNode* zeroOffsetFldSeq = nullptr; @@ -8187,6 +8134,8 @@ void Compiler::fgValueNumberBlockAssignment(GenTree* tree) #endif if (fldSeqForStaticVar != FieldSeqStore::NotAField()) { + assert(fldSeqForStaticVar != nullptr); + // We model statics as indices into GcHeap (which is a subset of ByrefExposed). ValueNum selectedStaticVar; size_t structSize = 0; @@ -8645,30 +8594,35 @@ void Compiler::fgValueNumberTree(GenTree* tree) // same. // - ValueNumPair clsVarVNPair; - - // If the static field handle is for a struct type field, then the value of the static - // is a "ref" to the boxed struct -- treat it as the address of the static (we assume that a - // first element offset will be added to get to the actual struct...) + ValueNumPair clsVarVNPair; GenTreeClsVar* clsVar = tree->AsClsVar(); FieldSeqNode* fldSeq = clsVar->gtFieldSeq; assert(fldSeq != nullptr); // We need to have one. + CORINFO_FIELD_HANDLE fieldHnd = clsVar->gtClsVarHnd; + assert(fieldHnd != NO_FIELD_HANDLE); ValueNum selectedStaticVar = ValueNumStore::NoVN; - if (gtIsStaticFieldPtrToBoxedStruct(clsVar->TypeGet(), fldSeq->m_fieldHnd)) + + if (fldSeq == FieldSeqStore::NotAField()) { - clsVarVNPair.SetBoth( - vnStore->VNForFunc(TYP_BYREF, VNF_PtrToStatic, vnStore->VNForFieldSeq(fldSeq))); + // This is the box for a "boxed static" - see "fgMorphField". + assert(gtIsStaticFieldPtrToBoxedStruct(clsVar->TypeGet(), fieldHnd)); + + // We will create an empty field sequence for VNF_PtrToStatic here. We will assume + // the actual sequence will get appended later, when processing the TARGET_POINTER_SIZE + // offset that is always added to this box to get to its payload. + + ValueNum fieldHndVN = vnStore->VNForHandle(ssize_t(fieldHnd), GTF_ICON_FIELD_HDL); + ValueNum fieldSeqVN = vnStore->VNForFieldSeq(nullptr); + clsVarVNPair.SetBoth(vnStore->VNForFunc(TYP_REF, VNF_PtrToStatic, fieldHndVN, fieldSeqVN)); } else { // This is a reference to heap memory. // We model statics as indices into GcHeap (which is a subset of ByrefExposed). - FieldSeqNode* fldSeqForStaticVar = - GetFieldSeqStore()->CreateSingleton(tree->AsClsVar()->gtClsVarHnd); size_t structSize = 0; - selectedStaticVar = vnStore->VNApplySelectors(VNK_Liberal, fgCurMemoryVN[GcHeap], - fldSeqForStaticVar, &structSize); + selectedStaticVar = + vnStore->VNApplySelectors(VNK_Liberal, fgCurMemoryVN[GcHeap], fldSeq, &structSize); selectedStaticVar = vnStore->VNApplySelectorsTypeCheck(selectedStaticVar, tree->TypeGet(), structSize); @@ -8808,12 +8762,11 @@ void Compiler::fgValueNumberTree(GenTree* tree) // a pointer to an object field or array element. Other cases become uses of // the current ByrefExposed value and the pointer value, so that at least we // can recognize redundant loads with no stores between them. - GenTree* addr = tree->AsIndir()->Addr(); - GenTreeLclVarCommon* lclVarTree = nullptr; - FieldSeqNode* fldSeq2 = nullptr; - GenTree* obj = nullptr; - GenTree* staticOffset = nullptr; - bool isVolatile = (tree->gtFlags & GTF_IND_VOLATILE) != 0; + GenTree* addr = tree->AsIndir()->Addr(); + GenTreeLclVarCommon* lclVarTree = nullptr; + FieldSeqNode* fldSeq = nullptr; + GenTree* baseAddr = nullptr; + bool isVolatile = (tree->gtFlags & GTF_IND_VOLATILE) != 0; // See if the addr has any exceptional part. ValueNumPair addrNvnp; @@ -8972,12 +8925,14 @@ void Compiler::fgValueNumberTree(GenTree* tree) else if (vnStore->GetVNFunc(addrNvnp.GetLiberal(), &funcApp) && funcApp.m_func == VNF_PtrToStatic) { var_types indType = tree->TypeGet(); - ValueNum fieldSeqVN = funcApp.m_args[0]; + ValueNum fieldSeqVN = funcApp.m_args[1]; FieldSeqNode* fldSeqForStaticVar = vnStore->FieldSeqVNToFieldSeq(fieldSeqVN); if (fldSeqForStaticVar != FieldSeqStore::NotAField()) { + assert(fldSeqForStaticVar != nullptr); + ValueNum selectedStaticVar; // We model statics as indices into the GcHeap (which is a subset of ByrefExposed). size_t structSize = 0; @@ -8999,74 +8954,48 @@ void Compiler::fgValueNumberTree(GenTree* tree) { fgValueNumberArrIndexVal(tree, &funcApp, addrXvnp.GetLiberal()); } - else if (addr->IsFieldAddr(this, &obj, &staticOffset, &fldSeq2)) + else if (addr->IsFieldAddr(this, &baseAddr, &fldSeq)) { - if (fldSeq2 == FieldSeqStore::NotAField()) - { - tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet())); - } - else if (fldSeq2 != nullptr) - { - if (fldSeq2->IsFirstElemFieldSeq()) - { - fldSeq2 = fldSeq2->m_next; - assert(fldSeq2 != nullptr); - } -#ifdef DEBUG - CORINFO_CLASS_HANDLE fldCls = info.compCompHnd->getFieldClass(fldSeq2->m_fieldHnd); - if (obj != nullptr) - { - // Make sure that the class containing it is not a value class (as we are expecting an - // instance field) - assert((info.compCompHnd->getClassAttribs(fldCls) & CORINFO_FLG_VALUECLASS) == 0); - assert(staticOffset == nullptr); - } -#endif // DEBUG + assert((fldSeq != nullptr) && (fldSeq != FieldSeqStore::NotAField()) && !fldSeq->IsPseudoField()); - // The size of the ultimate value we will select, if it is of a struct type. - size_t structSize = 0; + // The size of the ultimate value we will select, if it is of a struct type. + size_t structSize = 0; + ValueNum valueVN = ValueNumStore::NoVN; + + if (baseAddr != nullptr) + { + // Instance field / "complex" static: heap[field][baseAddr][struct fields...]. // Get the selector for the first field. var_types firstFieldType; ValueNum firstFieldSelectorVN = - vnStore->VNForFieldSelector(fldSeq2->GetFieldHandle(), &firstFieldType, &structSize); + vnStore->VNForFieldSelector(fldSeq->GetFieldHandle(), &firstFieldType, &structSize); ValueNum fldMapVN = vnStore->VNForMapSelect(VNK_Liberal, TYP_MEM, fgCurMemoryVN[GcHeap], firstFieldSelectorVN); - ValueNum firstFieldValueSelectorVN; - if (obj != nullptr) - { - firstFieldValueSelectorVN = vnStore->VNLiberalNormalValue(obj->gtVNPair); - } - else - { - assert(staticOffset != nullptr); - firstFieldValueSelectorVN = vnStore->VNLiberalNormalValue(staticOffset->gtVNPair); - } + ValueNum firstFieldValueSelectorVN = vnStore->VNLiberalNormalValue(baseAddr->gtVNPair); - // Construct the value number for fldMap[obj/offset]. + // Construct the value number for fldMap[baseAddr]. ValueNum firstFieldValueVN = vnStore->VNForMapSelect(VNK_Liberal, firstFieldType, fldMapVN, firstFieldValueSelectorVN); // Finally, account for the rest of the fields in the sequence. - ValueNum valueVN = - vnStore->VNApplySelectors(VNK_Liberal, firstFieldValueVN, fldSeq2->m_next, &structSize); - - valueVN = vnStore->VNApplySelectorsTypeCheck(valueVN, tree->TypeGet(), structSize); - tree->gtVNPair.SetLiberal(valueVN); - - // The conservative value is a new, unique VN. - tree->gtVNPair.SetConservative(vnStore->VNForExpr(compCurBB, tree->TypeGet())); - tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp); + valueVN = + vnStore->VNApplySelectors(VNK_Liberal, firstFieldValueVN, fldSeq->m_next, &structSize); } else { - // Occasionally we do an explicit null test on a REF, so we just dereference it with no - // field sequence. The result is probably unused. - tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet())); - tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp); + // "Simple" static: heap[static][struct fields...]. + valueVN = vnStore->VNApplySelectors(VNK_Liberal, fgCurMemoryVN[GcHeap], fldSeq, &structSize); } + + valueVN = vnStore->VNApplySelectorsTypeCheck(valueVN, tree->TypeGet(), structSize); + tree->gtVNPair.SetLiberal(valueVN); + + // The conservative value is a new, unique VN. + tree->gtVNPair.SetConservative(vnStore->VNForExpr(compCurBB, tree->TypeGet())); + tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp); } else // We don't know where the address points, so it is an ByrefExposed load. { diff --git a/src/coreclr/jit/valuenumfuncs.h b/src/coreclr/jit/valuenumfuncs.h index ac97b94f36a6f..fc10c05398cf0 100644 --- a/src/coreclr/jit/valuenumfuncs.h +++ b/src/coreclr/jit/valuenumfuncs.h @@ -13,10 +13,11 @@ ValueNumFuncDef(MapSelect, 2, false, false, false) // Args: 0: map, 1: key. ValueNumFuncDef(FieldSeq, 2, false, false, false) // Sequence (VN of null == empty) of (VN's of) field handles. ValueNumFuncDef(NotAField, 0, false, false, false) // Value number function for FieldSeqStore::NotAField. -ValueNumFuncDef(PtrToLoc, 2, false, false, false) // Pointer (byref) to a local variable. Args: VN's of: 0: var num, 1: FieldSeq. +ValueNumFuncDef(PtrToLoc, 2, false, true, false) // Pointer (byref) to a local variable. Args: VN's of: 0: var num, 1: FieldSeq. ValueNumFuncDef(PtrToArrElem, 4, false, false, false) // Pointer (byref) to an array element. Args: 0: array elem type eq class var_types value, VN's of: 1: array, 2: index, 3: FieldSeq. -ValueNumFuncDef(PtrToStatic, 1, false, false, false) // Pointer (byref) to a static variable (or possibly a field thereof, if the static variable is a struct). Args: 0: FieldSeq, first element - // of which is the static var. +ValueNumFuncDef(PtrToStatic, 2, false, true, false) // Pointer (byref) to a static variable (or possibly a field thereof, if the static variable is a struct). + // Args: 0: (VN of) the field handle, 1: the field sequence, of which the first element is the static itself. + ValueNumFuncDef(Phi, 2, false, false, false) // A phi function. Only occurs as arg of PhiDef or PhiMemoryDef. Arguments are SSA numbers of var being defined. ValueNumFuncDef(PhiDef, 3, false, false, false) // Args: 0: local var # (or -1 for memory), 1: SSA #, 2: VN of definition. // Wouldn't need this if I'd made memory a regular local variable... @@ -103,7 +104,7 @@ ValueNumFuncDef(Tanh, 1, false, false, false) ValueNumFuncDef(ManagedThreadId, 0, false, false, false) -ValueNumFuncDef(ObjGetType, 1, false, false, false) +ValueNumFuncDef(ObjGetType, 1, false, true, false) ValueNumFuncDef(GetgenericsGcstaticBase, 1, false, true, true) ValueNumFuncDef(GetgenericsNongcstaticBase, 1, false, true, true) ValueNumFuncDef(GetsharedGcstaticBase, 2, false, true, true) diff --git a/src/coreclr/md/enc/metamodelrw.cpp b/src/coreclr/md/enc/metamodelrw.cpp index 28b058b8fe366..34fe8b84e95c8 100644 --- a/src/coreclr/md/enc/metamodelrw.cpp +++ b/src/coreclr/md/enc/metamodelrw.cpp @@ -4116,7 +4116,7 @@ mdToken CMiniMdRW::GetToken( if (pColDef->m_Type <= iCodedTokenMax) { ULONG indexCodedToken = pColDef->m_Type - iCodedToken; - if (indexCodedToken < COUNTOF(g_CodedTokens)) + if (indexCodedToken < ARRAY_SIZE(g_CodedTokens)) { const CCodedTokenDef *pCdTkn = &g_CodedTokens[indexCodedToken]; tkn = decodeToken(GetCol(ixTbl, ixCol, pvRecord), pCdTkn->m_pTokens, pCdTkn->m_cTokens); @@ -4399,7 +4399,7 @@ CMiniMdRW::PutToken( // S_OK or E_UNEXPECTED. if (ColDef.m_Type <= iCodedTokenMax) { ULONG indexCodedToken = ColDef.m_Type - iCodedToken; - if (indexCodedToken < COUNTOF(g_CodedTokens)) + if (indexCodedToken < ARRAY_SIZE(g_CodedTokens)) { const CCodedTokenDef *pCdTkn = &g_CodedTokens[indexCodedToken]; cdTkn = encodeToken(RidFromToken(tk), TypeFromToken(tk), pCdTkn->m_pTokens, pCdTkn->m_cTokens); diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.Publish.targets b/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.Publish.targets index 67efba61efde9..18258d4288b01 100644 --- a/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.Publish.targets +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.Publish.targets @@ -54,6 +54,8 @@ + + diff --git a/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.targets b/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.targets index 265040b43044a..1a3b4a2f740b4 100644 --- a/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.targets +++ b/src/coreclr/nativeaot/BuildIntegration/Microsoft.NETCore.Native.targets @@ -31,6 +31,7 @@ The .NET Foundation licenses this file to you under the MIT license. false true + false @@ -39,7 +40,7 @@ The .NET Foundation licenses this file to you under the MIT license. true true - true + true copyused @@ -117,6 +118,13 @@ The .NET Foundation licenses this file to you under the MIT license. + + + $(NativeIntermediateOutputPath)\%(Filename).ilc.rsp + $(NativeIntermediateOutputPath)\%(Filename).$(IlcOutputFileExt) + + + @@ -187,9 +195,9 @@ The .NET Foundation licenses this file to you under the MIT license. - @@ -284,16 +292,21 @@ The .NET Foundation licenses this file to you under the MIT license. - + + + - - + + @@ -356,7 +369,7 @@ The .NET Foundation licenses this file to you under the MIT license. <_IgnoreLinkerWarnings>false <_IgnoreLinkerWarnings Condition="'$(TargetOS)' == 'OSX'">true - + diff --git a/src/coreclr/nativeaot/Runtime/CommonMacros.h b/src/coreclr/nativeaot/Runtime/CommonMacros.h index bfa6f2e1e3fc7..271980b5c1ad7 100644 --- a/src/coreclr/nativeaot/Runtime/CommonMacros.h +++ b/src/coreclr/nativeaot/Runtime/CommonMacros.h @@ -5,6 +5,7 @@ #define __COMMONMACROS_H__ #include "rhassert.h" +#include #define EXTERN_C extern "C" @@ -33,12 +34,6 @@ #endif // _MSC_VER -#ifndef COUNTOF -template -char (*COUNTOF_helper(_CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray]; -#define COUNTOF(_Array) sizeof(*COUNTOF_helper(_Array)) -#endif // COUNTOF - #ifndef offsetof #define offsetof(s,m) (uintptr_t)( (intptr_t)&reinterpret_cast((((s *)0)->m)) ) #endif // offsetof diff --git a/src/coreclr/nativeaot/Runtime/EHHelpers.cpp b/src/coreclr/nativeaot/Runtime/EHHelpers.cpp index b8108dfa379f9..b888d530c4c5f 100644 --- a/src/coreclr/nativeaot/Runtime/EHHelpers.cpp +++ b/src/coreclr/nativeaot/Runtime/EHHelpers.cpp @@ -92,7 +92,7 @@ COOP_PINVOKE_HELPER(int32_t, RhGetModuleFileName, (HANDLE moduleHandle, _Out_ co COOP_PINVOKE_HELPER(void, RhpCopyContextFromExInfo, (void * pOSContext, int32_t cbOSContext, PAL_LIMITED_CONTEXT * pPalContext)) { UNREFERENCED_PARAMETER(cbOSContext); - ASSERT(cbOSContext >= sizeof(CONTEXT)); + ASSERT((size_t)cbOSContext >= sizeof(CONTEXT)); CONTEXT* pContext = (CONTEXT *)pOSContext; #if defined(UNIX_AMD64_ABI) pContext->Rip = pPalContext->IP; diff --git a/src/coreclr/nativeaot/Runtime/MathHelpers.cpp b/src/coreclr/nativeaot/Runtime/MathHelpers.cpp index dfcd1c194b857..1209e9c554362 100644 --- a/src/coreclr/nativeaot/Runtime/MathHelpers.cpp +++ b/src/coreclr/nativeaot/Runtime/MathHelpers.cpp @@ -33,7 +33,7 @@ EXTERN_C REDHAWK_API float REDHAWK_CALLCONV RhpFltRem(float dividend, float divi if (divisor==0 || !std::isfinite(dividend)) { - return -nanf(0); + return -nanf(""); } else if (!std::isfinite(divisor) && !std::isnan(divisor)) { @@ -57,7 +57,7 @@ EXTERN_C REDHAWK_API double REDHAWK_CALLCONV RhpDblRem(double dividend, double d // if (divisor==0 || !std::isfinite(dividend)) { - return -nan(0); + return -nan(""); } else if (!std::isfinite(divisor) && !std::isnan(divisor)) { diff --git a/src/coreclr/nativeaot/Runtime/RhConfig.cpp b/src/coreclr/nativeaot/Runtime/RhConfig.cpp index da618a85930e0..e68dc4eaf5d46 100644 --- a/src/coreclr/nativeaot/Runtime/RhConfig.cpp +++ b/src/coreclr/nativeaot/Runtime/RhConfig.cpp @@ -118,7 +118,7 @@ uint32_t RhConfig::GetConfigVariable(_In_z_ const TCHAR* configName, const Confi uint32_t iValue; - for (iValue = 0; (iValue < CONFIG_VAL_MAXLEN + 1) && (iValue < (int32_t)cchOutputBuffer); iValue++) + for (iValue = 0; (iValue < CONFIG_VAL_MAXLEN + 1) && (iValue < cchOutputBuffer); iValue++) { outputBuffer[iValue] = configPairs[iSettings].Value[iValue]; diff --git a/src/coreclr/nativeaot/Runtime/gcrhenv.cpp b/src/coreclr/nativeaot/Runtime/gcrhenv.cpp index 7ca20c8ca8d99..2f6f6ea4f7c0c 100644 --- a/src/coreclr/nativeaot/Runtime/gcrhenv.cpp +++ b/src/coreclr/nativeaot/Runtime/gcrhenv.cpp @@ -923,7 +923,7 @@ void GCToEEInterface::DisablePreemptiveGC() Thread* GCToEEInterface::GetThread() { #ifndef DACCESS_COMPILE - return ThreadStore::GetCurrentThread(); + return ThreadStore::GetCurrentThreadIfAvailable(); #else return NULL; #endif diff --git a/src/coreclr/nativeaot/Runtime/rhassert.cpp b/src/coreclr/nativeaot/Runtime/rhassert.cpp index f69a919450b39..4ff9062578f6d 100644 --- a/src/coreclr/nativeaot/Runtime/rhassert.cpp +++ b/src/coreclr/nativeaot/Runtime/rhassert.cpp @@ -52,7 +52,7 @@ void Assert(const char * expr, const char * file, uint32_t line_num, const char char buffer[4096]; - sprintf_s(buffer, COUNTOF(buffer), + sprintf_s(buffer, ARRAY_SIZE(buffer), "--------------------------------------------------\n" "Debug Assertion Violation\n\n" "%s%s%s" diff --git a/src/coreclr/nativeaot/Runtime/stressLog.cpp b/src/coreclr/nativeaot/Runtime/stressLog.cpp index 12df357966d78..2e25b6bcfa792 100644 --- a/src/coreclr/nativeaot/Runtime/stressLog.cpp +++ b/src/coreclr/nativeaot/Runtime/stressLog.cpp @@ -323,7 +323,7 @@ void ThreadStressLog::LogMsg ( uint32_t facility, int cArgs, const char* format, // Asserts in this function cause infinite loops in the asserting mechanism. // Just use debug breaks instead. - ASSERT( cArgs >= 0 && cArgs <= StressMsg::maxArgCnt ); + ASSERT( cArgs >= 0 && (size_t)cArgs <= StressMsg::maxArgCnt ); size_t offs = ((size_t)format - StressLog::theLog.moduleOffset); @@ -373,7 +373,7 @@ void ThreadStressLog::Activate (Thread * pThread) /* static */ void StressLog::LogMsg (unsigned facility, int cArgs, const char* format, ... ) { - _ASSERTE ( cArgs >= 0 && cArgs <= StressMsg::maxArgCnt ); + _ASSERTE ( cArgs >= 0 && (size_t)cArgs <= StressMsg::maxArgCnt ); va_list Args; va_start(Args, format); diff --git a/src/coreclr/nativeaot/Runtime/thread.cpp b/src/coreclr/nativeaot/Runtime/thread.cpp index 2b4a6ccb83a9c..f091318acf641 100644 --- a/src/coreclr/nativeaot/Runtime/thread.cpp +++ b/src/coreclr/nativeaot/Runtime/thread.cpp @@ -607,13 +607,13 @@ static void* GcStressHijackTargets[1] = // static bool Thread::IsHijackTarget(void * address) { - for (int i = 0; i < COUNTOF(NormalHijackTargets); i++) + for (size_t i = 0; i < ARRAY_SIZE(NormalHijackTargets); i++) { if (NormalHijackTargets[i] == address) return true; } #ifdef FEATURE_GC_STRESS - for (int i = 0; i < COUNTOF(GcStressHijackTargets); i++) + for (size_t i = 0; i < ARRAY_SIZE(GcStressHijackTargets); i++) { if (GcStressHijackTargets[i] == address) return true; diff --git a/src/coreclr/nativeaot/Runtime/unix/PalRedhawkUnix.cpp b/src/coreclr/nativeaot/Runtime/unix/PalRedhawkUnix.cpp index f7b876a672145..410222948e18c 100644 --- a/src/coreclr/nativeaot/Runtime/unix/PalRedhawkUnix.cpp +++ b/src/coreclr/nativeaot/Runtime/unix/PalRedhawkUnix.cpp @@ -233,7 +233,7 @@ class UnixEvent TimeSpecAdd(&endTime, milliseconds); } #else -#error Don't know how to perform timed wait on this platform +#error "Don't know how to perform timed wait on this platform" #endif int st = 0; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Math.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Math.CoreRT.cs index 8a53e1588b83d..15b629dbee219 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Math.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Math.CoreRT.cs @@ -16,18 +16,6 @@ namespace System { public static partial class Math { - [Intrinsic] - public static float Abs(float value) - { - return RuntimeImports.fabsf(value); - } - - [Intrinsic] - public static double Abs(double value) - { - return RuntimeImports.fabs(value); - } - [Intrinsic] public static double Acos(double d) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.CoreRT.cs index 788bad4bbc181..06c7ce9fdc1f5 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.CoreRT.cs @@ -213,8 +213,6 @@ private unsafe IntPtr AsRuntimeDefined(in Guid riid) { return (IntPtr)(Dispatches + i); } - - i++; } return IntPtr.Zero; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs index 304f7073e7ec3..a7edbf10d819a 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs @@ -679,18 +679,6 @@ internal struct ConservativelyReportedRegionDesc [RuntimeImport(RuntimeLibrary, "RhpMemoryBarrier")] internal static extern void MemoryBarrier(); - [Intrinsic] - [MethodImplAttribute(MethodImplOptions.InternalCall)] - [RuntimeImport(RuntimeLibrary, "fabs")] - internal static extern double fabs(double x); - - [Intrinsic] - internal static float fabsf(float x) - { - // fabsf is not a real export for some architectures - return (float)fabs(x); - } - [Intrinsic] [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "acos")] diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Windows.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Windows.cs index e9ce1e5590ad7..9f31a0c2c6d9d 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Windows.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Windows.cs @@ -200,11 +200,10 @@ private unsafe bool CreateThread(GCHandle thisThreadHandle) stackSize = AllocationGranularity; } - uint threadId; _osHandle = Interop.Kernel32.CreateThread(IntPtr.Zero, (IntPtr)stackSize, &ThreadEntryPoint, (IntPtr)thisThreadHandle, Interop.Kernel32.CREATE_SUSPENDED | Interop.Kernel32.STACK_SIZE_PARAM_IS_A_RESERVATION, - out threadId); + out _); if (_osHandle.IsInvalid) { diff --git a/src/coreclr/nativeaot/System.Private.Interop/src/Internal/Runtime/CompilerHelpers/RuntimeInteropData.CoreRT.cs b/src/coreclr/nativeaot/System.Private.Interop/src/Internal/Runtime/CompilerHelpers/RuntimeInteropData.CoreRT.cs index 376ee967cd404..1f6fa5f89c83d 100644 --- a/src/coreclr/nativeaot/System.Private.Interop/src/Internal/Runtime/CompilerHelpers/RuntimeInteropData.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.Interop/src/Internal/Runtime/CompilerHelpers/RuntimeInteropData.CoreRT.cs @@ -44,10 +44,9 @@ public override bool TryGetStructUnsafeStructSize(RuntimeTypeHandle structureTyp public override bool TryGetStructFieldOffset(RuntimeTypeHandle structureTypeHandle, string fieldName, out bool structExists, out uint offset) { - ExternalReferencesTable externalReferences; NativeParser entryParser; structExists = false; - if (TryGetStructData(structureTypeHandle, out externalReferences, out entryParser)) + if (TryGetStructData(structureTypeHandle, out _, out entryParser)) { structExists = true; diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/ActivatorImplementation.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/ActivatorImplementation.cs index d5ea4c2dd34de..4370581bd7c6e 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/ActivatorImplementation.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/ActivatorImplementation.cs @@ -88,8 +88,7 @@ public static object CreateInstance( if (binder == null) binder = Type.DefaultBinder; - object state = null; - MethodBase invokeMethod = binder.BindToMethod(bindingAttr, matches.ToArray(), ref args, null, culture, null, out state); + MethodBase invokeMethod = binder.BindToMethod(bindingAttr, matches.ToArray(), ref args, null, culture, null, out object state); if (invokeMethod.GetParametersNoCopy().Length == 0) { if (args.Length != 0) diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.cs index 266f6cba26400..7c5f1b5a926d9 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseInsensitive.cs @@ -99,8 +99,7 @@ private LowLevelDictionary CreateCaseInsensitiveTypeDictionary( foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions) { string fullName = ns + typeDefinitionHandle.GetTypeDefinition(reader).Name.GetString(reader).ToLowerInvariant(); - QHandle existingValue; - if (!dict.TryGetValue(fullName, out existingValue)) + if (!dict.TryGetValue(fullName, out _)) { dict.Add(fullName, new QHandle(reader, typeDefinitionHandle)); } @@ -109,8 +108,7 @@ private LowLevelDictionary CreateCaseInsensitiveTypeDictionary( foreach (TypeForwarderHandle typeForwarderHandle in namespaceDefinition.TypeForwarders) { string fullName = ns + typeForwarderHandle.GetTypeForwarder(reader).Name.GetString(reader).ToLowerInvariant(); - QHandle existingValue; - if (!dict.TryGetValue(fullName, out existingValue)) + if (!dict.TryGetValue(fullName, out _)) { dict.Add(fullName, new QHandle(reader, typeForwarderHandle)); } diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs index 1f9d754916f74..4f20819d1d210 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/Shared.cs @@ -149,11 +149,9 @@ public static bool QualifiesBasedOnParameterCount(this MethodBase methodBase, Bi public static M GetImplicitlyOverriddenBaseClassMember(this M member) where M : MemberInfo { MemberPolicies policies = MemberPolicies.Default; - MethodAttributes visibility; - bool isStatic; bool isVirtual; bool isNewSlot; - policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot); + policies.GetMemberAttributes(member, out _, out _, out isVirtual, out isNewSlot); if (isNewSlot || !isVirtual) { return null; @@ -174,11 +172,8 @@ public static M GetImplicitlyOverriddenBaseClassMember(this M member) where M { continue; } - MethodAttributes candidateVisibility; - bool isCandidateStatic; bool isCandidateVirtual; - bool isCandidateNewSlot; - policies.GetMemberAttributes(member, out candidateVisibility, out isCandidateStatic, out isCandidateVirtual, out isCandidateNewSlot); + policies.GetMemberAttributes(member, out _, out _, out isCandidateVirtual, out _); if (!isCandidateVirtual) { continue; diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/CustomAttributes/RuntimeCustomAttributeData.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/CustomAttributes/RuntimeCustomAttributeData.cs index 7db743d5e8143..555277bed0935 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/CustomAttributes/RuntimeCustomAttributeData.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/CustomAttributes/RuntimeCustomAttributeData.cs @@ -146,11 +146,10 @@ private static string ComputeTypedArgumentString(CustomAttributeTypedArgument ca else if (argumentType.IsArray) { - string result = null; IList array = value as IList; Type elementType = argumentType.GetElementType(); - result = string.Format(@"new {0}[{1}] {{ ", elementType.IsEnum ? elementType.FullName : elementType.Name, array.Count); + string result = string.Format(@"new {0}[{1}] {{ ", elementType.IsEnum ? elementType.FullName : elementType.Name, array.Count); for (int i = 0; i < array.Count; i++) result += string.Format(i == 0 ? "{0}" : ", {0}", ComputeTypedArgumentString(array[i], elementType != typeof(object))); diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/NamespaceChain.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/NamespaceChain.cs index e76abd7d0c026..34b97186d7507 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/NamespaceChain.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/NamespaceChain.cs @@ -21,7 +21,7 @@ internal NamespaceChain(MetadataReader reader, NamespaceDefinitionHandle innerMo { NamespaceDefinition currentNamespaceDefinition = innerMostNamespaceHandle.GetNamespaceDefinition(reader); ConstantStringValueHandle currentNameHandle = currentNamespaceDefinition.Name; - Handle currentNamespaceHandle = innerMostNamespaceHandle.ToHandle(reader); + Handle currentNamespaceHandle; LowLevelList names = new LowLevelList(); for (;;) { diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/ReflectionCoreCallbacksImplementation.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/ReflectionCoreCallbacksImplementation.cs index df5587374683d..77272d3ff2c23 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/ReflectionCoreCallbacksImplementation.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/ReflectionCoreCallbacksImplementation.cs @@ -164,7 +164,6 @@ private FieldInfo GetFieldInfo(RuntimeTypeHandle declaringTypeHandle, FieldHandl { RuntimeTypeInfo contextTypeInfo = declaringTypeHandle.GetTypeForRuntimeTypeHandle(); NativeFormatRuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToNativeFormatRuntimeNamedTypeInfo(); - MetadataReader reader = definingTypeInfo.Reader; // RuntimeFieldHandles always yield FieldInfo's whose ReflectedType equals the DeclaringType. RuntimeTypeInfo reflectedType = contextTypeInfo; diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimePlainConstructorInfo.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimePlainConstructorInfo.cs index 308d09b8efcd5..7e3825048f340 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimePlainConstructorInfo.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/MethodInfos/RuntimePlainConstructorInfo.cs @@ -178,8 +178,7 @@ protected sealed override RuntimeParameterInfo[] RuntimeParameters { get { - RuntimeParameterInfo ignore; - return _lazyParameters ?? (_lazyParameters = RuntimeMethodHelpers.GetRuntimeParameters(ref _common, this, Array.Empty(), out ignore)); + return _lazyParameters ??= RuntimeMethodHelpers.GetRuntimeParameters(ref _common, this, Array.Empty(), out _); } } diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/ParameterInfos/RuntimeFatMethodParameterInfo.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/ParameterInfos/RuntimeFatMethodParameterInfo.cs index 8f92256963e18..8859a0770c499 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/ParameterInfos/RuntimeFatMethodParameterInfo.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/ParameterInfos/RuntimeFatMethodParameterInfo.cs @@ -50,7 +50,7 @@ public sealed override object RawDefaultValue if (rawDefaultValueInfo == null) { object rawDefaultValue; - bool dontCare = GetDefaultValueOrSentinel(raw: true, defaultValue: out rawDefaultValue); + GetDefaultValueOrSentinel(raw: true, defaultValue: out rawDefaultValue); rawDefaultValueInfo = _lazyRawDefaultValueInfo = Tuple.Create(rawDefaultValue); } return rawDefaultValueInfo.Item1; diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.InvokeMember.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.InvokeMember.cs index 40ca73df2b1f4..77dccda7966be 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.InvokeMember.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.InvokeMember.cs @@ -75,7 +75,6 @@ public sealed override object InvokeMember( if (binder == null) binder = DefaultBinder; - bool bDefaultBinder = (binder == DefaultBinder); #endregion #region Delegate to Activator.CreateInstance @@ -320,7 +319,7 @@ public sealed override object InvokeMember( for (int i = 0; i < semiFinalists.Length; i++) { - MethodInfo semiFinalist = null; + MethodInfo semiFinalist; if (isSetProperty) { diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs index 4439bea360a0c..d086fbd41e9c8 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs @@ -1038,8 +1038,8 @@ private static FunctionPointersToOffsets ComputeLdftnReverseLookup_InvokeMap(Nat if (!hasEntrypoint) continue; - uint entryMethodHandleOrNameAndSigRaw = entryParser.GetUnsigned(); - uint entryDeclaringTypeRaw = entryParser.GetUnsigned(); + entryParser.SkipInteger(); // entryMethodHandleOrNameAndSigRaw + entryParser.SkipInteger(); // entryDeclaringTypeRaw IntPtr entryMethodEntrypoint = externalReferences.GetFunctionPointerFromIndex(entryParser.GetUnsigned()); functionPointers.Add(new FunctionPointerOffsetPair(entryMethodEntrypoint, parserOffset)); @@ -1401,8 +1401,7 @@ public unsafe sealed override bool TryGetMethodFromHandle(RuntimeMethodHandle ru // public sealed override bool TryGetMethodFromHandleAndType(RuntimeMethodHandle runtimeMethodHandle, RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { - RuntimeTypeHandle dummy; - return TryGetMethodFromHandle(runtimeMethodHandle, out dummy, out methodHandle, out genericMethodTypeArgumentHandles); + return TryGetMethodFromHandle(runtimeMethodHandle, out _, out methodHandle, out genericMethodTypeArgumentHandles); } // @@ -1410,7 +1409,6 @@ public sealed override bool TryGetMethodFromHandleAndType(RuntimeMethodHandle ru // public unsafe sealed override bool TryGetFieldFromHandle(RuntimeFieldHandle runtimeFieldHandle, out RuntimeTypeHandle declaringTypeHandle, out FieldHandle fieldHandle) { - declaringTypeHandle = default(RuntimeTypeHandle); fieldHandle = default(FieldHandle); string fieldName; @@ -1446,8 +1444,7 @@ public unsafe sealed override bool TryGetFieldFromHandle(RuntimeFieldHandle runt // public sealed override bool TryGetFieldFromHandleAndType(RuntimeFieldHandle runtimeFieldHandle, RuntimeTypeHandle declaringTypeHandle, out FieldHandle fieldHandle) { - RuntimeTypeHandle dummy; - return TryGetFieldFromHandle(runtimeFieldHandle, out dummy, out fieldHandle); + return TryGetFieldFromHandle(runtimeFieldHandle, out _, out fieldHandle); } /// diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/DiagnosticMappingTables.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/DiagnosticMappingTables.cs index 0116d9a4c9e99..d09662aad9514 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/DiagnosticMappingTables.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/DiagnosticMappingTables.cs @@ -62,10 +62,8 @@ public static bool TryGetDiagnosticStringForNamedType(RuntimeTypeHandle runtimeT private static string GetTypeFullNameFromTypeRef(TypeReferenceHandle typeReferenceHandle, MetadataReader reader, List genericParameterOffsets) { - string s = ""; - TypeReference typeReference = typeReferenceHandle.GetTypeReference(reader); - s = typeReference.TypeName.GetString(reader); + string s = typeReference.TypeName.GetString(reader); Handle parentHandle = typeReference.ParentNamespaceOrType; HandleType parentHandleType = parentHandle.HandleType; if (parentHandleType == HandleType.TypeReference) @@ -135,7 +133,7 @@ public static string ConvertBackTickNameToNameWithReducerInputFormat(string type private static string GetTypeFullNameFromTypeDef(TypeDefinitionHandle typeDefinitionHandle, MetadataReader reader, List genericParameterOffsets) { - string s = ""; + string s; TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader); s = typeDefinition.Name.GetString(reader); diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/MissingMetadataExceptionCreator.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/MissingMetadataExceptionCreator.cs index 37adf30ec2646..db347ad0b787b 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/MissingMetadataExceptionCreator.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/PayForPlayExperience/MissingMetadataExceptionCreator.cs @@ -109,7 +109,7 @@ public static string ComputeUsefulPertainantIfPossible(object pertainant) if (pertainant is MethodBase) { MethodBase method = (MethodBase)pertainant; - bool first = true; + bool first; // write out generic parameters if (method.IsConstructedGenericMethod) diff --git a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/MethodNameFormatter.cs b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/MethodNameFormatter.cs index cc5dd065dac28..ebfbab7a8e2c0 100644 --- a/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/MethodNameFormatter.cs +++ b/src/coreclr/nativeaot/System.Private.StackTraceMetadata/src/Internal/StackTraceMetadata/MethodNameFormatter.cs @@ -255,8 +255,12 @@ private void EmitTypeName(Handle typeHandle, bool namespaceQualified) EmitString(typeHandle.ToGenericParameterHandle(_metadataReader).GetGenericParameter(_metadataReader).Name); break; + case HandleType.FunctionPointerSignature: + EmitFunctionPointerTypeName(); + break; + default: - Debug.Assert(false); + Debug.Assert(false, $"Type handle {typeHandle.HandleType} was not handled"); _outputBuilder.Append("???"); break; } @@ -407,6 +411,14 @@ private void EmitPointerTypeName(PointerSignatureHandle pointerSigHandle) _outputBuilder.Append('*'); } + /// + /// Emit function pointer type. + /// + private void EmitFunctionPointerTypeName() + { + _outputBuilder.Append("IntPtr"); + } + /// /// Emit by-reference type. /// diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionParameters.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionParameters.cs index 475b77b482045..2d27a3f35893a 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionParameters.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionParameters.cs @@ -341,10 +341,8 @@ internal void PrepareNextMulticastDelegateCall(int currentIndex) Delegate[] delegateArray = (Delegate[])_delegateData._helperObject; Delegate currentDelegate = delegateArray[currentIndex]; - object helperObject; - IntPtr extraFunctionPointerOrData; IntPtr functionPointer; - RuntimeAugments.GetDelegateData(currentDelegate, out _delegateData._multicastThisPointer, out helperObject, out extraFunctionPointerOrData, out functionPointer); + RuntimeAugments.GetDelegateData(currentDelegate, out _delegateData._multicastThisPointer, out _, out _, out functionPointer); bool forceCalleeHasParamType = UpdateCalleeFunctionPointer(functionPointer); _calleeArgs.SetHasParamTypeAndReset(forceCalleeHasParamType); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs index befeea82355ab..28197a93abd6e 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs @@ -259,8 +259,7 @@ public static unsafe IntPtr GetDelegateThunk(Delegate delegateObject, int thunkK Debug.Assert(RuntimeAugments.IsGenericType(delegateType)); RuntimeTypeHandle[] typeArgs; - RuntimeTypeHandle genericTypeDefHandle; - genericTypeDefHandle = RuntimeAugments.GetGenericInstantiation(delegateType, out typeArgs); + RuntimeAugments.GetGenericInstantiation(delegateType, out typeArgs); Debug.Assert(typeArgs != null && typeArgs.Length > 0); RuntimeSignature invokeMethodSignature; @@ -303,9 +302,8 @@ public static unsafe IntPtr GetDelegateThunk(Delegate delegateObject, int thunkK public static unsafe bool TryGetNonUnboxingFunctionPointerFromUnboxingAndInstantiatingStub(IntPtr potentialStub, RuntimeTypeHandle exactType, out IntPtr nonUnboxingMethod) { IntPtr callConversionId; - IntPtr commonStubDataPtr; object thunkPoolHeap = s_thunkPoolHeap; - if (thunkPoolHeap == null || !RuntimeAugments.TryGetThunkData(thunkPoolHeap, potentialStub, out callConversionId, out commonStubDataPtr)) + if (thunkPoolHeap == null || !RuntimeAugments.TryGetThunkData(thunkPoolHeap, potentialStub, out callConversionId, out _)) { // This isn't a call conversion stub nonUnboxingMethod = IntPtr.Zero; @@ -383,9 +381,8 @@ public static unsafe bool TryGetCallConversionTargetPointerAndInstantiatingArg(I methodTarget = instantiatingArg = IntPtr.Zero; IntPtr callConversionId; - IntPtr commonStubDataPtr; object thunkPoolHeap = s_thunkPoolHeap; - if (thunkPoolHeap == null || !RuntimeAugments.TryGetThunkData(thunkPoolHeap, potentialStub, out callConversionId, out commonStubDataPtr)) + if (thunkPoolHeap == null || !RuntimeAugments.TryGetThunkData(thunkPoolHeap, potentialStub, out callConversionId, out _)) { // This isn't a call conversion stub return false; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs index d1b2421957a23..b4388c891b17a 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs @@ -67,8 +67,7 @@ public static bool TypeUsesReturnBuffer(RuntimeTypeHandle returnType, bool metho CorElementType typeReturnType = thReturnType.GetCorElementType(); bool usesReturnBuffer; - uint fpReturnSizeIgnored; - ArgIterator.ComputeReturnValueTreatment(typeReturnType, thReturnType, methodWithReturnTypeIsVarArg, out usesReturnBuffer, out fpReturnSizeIgnored); + ArgIterator.ComputeReturnValueTreatment(typeReturnType, thReturnType, methodWithReturnTypeIsVarArg, out usesReturnBuffer, out _); return usesReturnBuffer; } diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/EETypeCreator.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/EETypeCreator.cs index aa65aecb53db4..c1ff399482a52 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/EETypeCreator.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/EETypeCreator.cs @@ -1045,7 +1045,7 @@ public static RuntimeTypeHandle CreateEEType(TypeDesc type, TypeBuilderState sta { Debug.Assert(type != null && state != null); - MethodTable* pTemplateEEType = null; + MethodTable* pTemplateEEType; bool requireVtableSlotMapping = false; if (type is PointerType || type is ByRefType) diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ModuleList.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ModuleList.cs index 7a89589ed6cab..f6e52ed013dd2 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ModuleList.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/ModuleList.cs @@ -673,8 +673,7 @@ public void RegisterNewModules(ModuleType moduleType) foreach (TypeManagerHandle moduleHandle in loadedModuleHandles) { // Skip already registered modules. - int oldModuleIndex; - if (_loadedModuleMap.HandleToModuleIndex.TryGetValue(moduleHandle, out oldModuleIndex)) + if (_loadedModuleMap.HandleToModuleIndex.TryGetValue(moduleHandle, out _)) { continue; } diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs index 8d93e08b45b65..7c2d1958a40af 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs @@ -234,8 +234,7 @@ private static void EnsureFieldLayoutLoadedForNonUniversalType(DefType type) // Look up the universal template for this type. Only the universal template has field layout // information, so we have to use it to parse the field layout. NativeLayoutInfoLoadContext universalLayoutLoadContext; - NativeLayoutInfo universalLayoutInfo; - NativeParser typeInfoParser = type.GetOrCreateTypeBuilderState().GetParserForUniversalNativeLayoutInfo(out universalLayoutLoadContext, out universalLayoutInfo); + NativeParser typeInfoParser = type.GetOrCreateTypeBuilderState().GetParserForUniversalNativeLayoutInfo(out universalLayoutLoadContext, out _); if (typeInfoParser.IsNull) throw new TypeBuilder.MissingTemplateException(); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutInfoLoadContext.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutInfoLoadContext.cs index 9dcbbea70bdaa..887a9b9b06289 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutInfoLoadContext.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutInfoLoadContext.cs @@ -173,7 +173,7 @@ internal MethodDesc GetMethod(ref NativeParser parser, out RuntimeSignature meth bool unboxingStub = (flags & MethodFlags.IsUnboxingStub) != 0; - MethodDesc retVal = null; + MethodDesc retVal; if ((flags & MethodFlags.HasInstantiation) != 0) { TypeDesc[] typeArguments = GetTypeSequence(ref parser); @@ -197,9 +197,7 @@ internal MethodDesc GetMethod(ref NativeParser parser, out RuntimeSignature meth internal MethodDesc GetMethod(ref NativeParser parser) { - RuntimeSignature methodSig; - RuntimeSignature methodNameSig; - return GetMethod(ref parser, out methodNameSig, out methodSig); + return GetMethod(ref parser, out _, out _); } internal TypeDesc[] GetTypeSequence(ref NativeParser parser) diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs index 37752ef347200..2a3fa2e363eaf 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs @@ -236,8 +236,7 @@ private InstantiatedMethod TryGetGenericMethodTemplate_Internal(InstantiatedMeth if (nativeLayoutReader == null) continue; - ExternalReferencesTable externalFixupsTable; - NativeHashtable genericMethodTemplatesHashtable = LoadHashtable(moduleInfo, ReflectionMapBlob.GenericMethodsTemplateMap, out externalFixupsTable); + NativeHashtable genericMethodTemplatesHashtable = LoadHashtable(moduleInfo, ReflectionMapBlob.GenericMethodsTemplateMap, out _); if (genericMethodTemplatesHashtable.IsNull) continue; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs index aa1c1b918168b..d7ba8aabd1ee8 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs @@ -1458,8 +1458,7 @@ private void RegisterGenericTypesAndMethods() int typesToRegisterCount = 0; for (int i = 0; i < _typesThatNeedTypeHandles.Count; i++) { - DefType typeAsDefType; - if ((typeAsDefType = _typesThatNeedTypeHandles[i] as DefType) != null) + if (_typesThatNeedTypeHandles[i] is DefType) typesToRegisterCount++; } @@ -1637,8 +1636,6 @@ internal void BuildType(TypeDesc type) internal bool TryComputeFieldOffset(DefType declaringType, uint fieldOrdinal, out int fieldOffset) { - fieldOffset = int.MinValue; - TypeLoaderLogger.WriteLine("Computing offset of field #" + fieldOrdinal.LowLevelToString() + " on type " + declaringType.ToString()); // Get the computed field offset result @@ -2217,9 +2214,8 @@ internal static bool TryGetDelegateInvokeMethodSignature(RuntimeTypeHandle deleg DefType delegateType = (DefType)context.ResolveRuntimeTypeHandle(delegateTypeHandle); Debug.Assert(delegateType.HasInstantiation); - NativeLayoutInfoLoadContext loadContext; NativeLayoutInfo universalLayoutInfo; - NativeParser parser = delegateType.GetOrCreateTypeBuilderState().GetParserForUniversalNativeLayoutInfo(out loadContext, out universalLayoutInfo); + NativeParser parser = delegateType.GetOrCreateTypeBuilderState().GetParserForUniversalNativeLayoutInfo(out _, out universalLayoutInfo); if (!parser.IsNull) { NativeParser sigParser = parser.GetParserForBagElementKind(BagElementKind.DelegateInvokeSignature); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs index 0aa63813f9a8a..8105f9d168754 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs @@ -155,7 +155,7 @@ private void EnsureNativeLayoutInfoComputed() if (!_templateComputed) { // Attempt to compute native layout through as a non-ReadyToRun template - object temp = this.TemplateType; + object _ = this.TemplateType; } if (!_nativeLayoutTokenComputed) { diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericMethodsLookup.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericMethodsLookup.cs index b1f003ed8dab4..f41f37821909d 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericMethodsLookup.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericMethodsLookup.cs @@ -291,8 +291,6 @@ public bool TryLookupGenericMethodDictionaryForComponents(RuntimeTypeHandle decl public bool TryGetGenericMethodComponents(IntPtr methodDictionary, out RuntimeTypeHandle declaringType, out MethodNameAndSignature nameAndSignature, out RuntimeTypeHandle[] genericMethodArgumentHandles) { - nameAndSignature = null; - if (!TryGetDynamicGenericMethodComponents(methodDictionary, out declaringType, out nameAndSignature, out genericMethodArgumentHandles)) if (!TryGetStaticGenericMethodComponents(methodDictionary, out declaringType, out nameAndSignature, out genericMethodArgumentHandles)) return false; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.FieldAccess.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.FieldAccess.cs index 97d5c73f6741e..a0a0854ec2da7 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.FieldAccess.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.FieldAccess.cs @@ -124,8 +124,6 @@ private static unsafe bool TryGetFieldAccessMetadataFromFieldAccessMap( ref FieldAccessMetadata fieldAccessMetadata) { CanonicallyEquivalentEntryLocator canonWrapper = new CanonicallyEquivalentEntryLocator(declaringTypeHandle, canonFormKind); - TypeManagerHandle fieldHandleModule = ModuleList.Instance.GetModuleForMetadataReader(metadataReader); - bool isDynamicType = RuntimeAugments.IsDynamicType(declaringTypeHandle); string fieldName = null; RuntimeTypeHandle declaringTypeHandleDefinition = Instance.GetTypeDefinition(declaringTypeHandle); @@ -190,7 +188,7 @@ private static unsafe bool TryGetFieldAccessMetadataFromFieldAccessMap( continue; } - int fieldOffset = -1; + int fieldOffset; IntPtr fieldAddressCookie = IntPtr.Zero; if (canonFormKind == CanonicalFormKind.Universal) diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs index 37874b76b7457..820ea6ddb7dec 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs @@ -602,9 +602,7 @@ private IntPtr TryGetDefaultConstructorForTypeViaMetadata_Inner(TypeDesc type) MethodDesc defaultConstructor = ((MetadataType)defType).GetDefaultConstructor(); if (defaultConstructor != null) { - IntPtr dummyUnboxingStub; - TypeLoaderEnvironment.MethodAddressType foundAddressType; - TypeLoaderEnvironment.TryGetMethodAddressFromMethodDesc(defaultConstructor, out metadataLookupResult, out dummyUnboxingStub, out foundAddressType); + TypeLoaderEnvironment.TryGetMethodAddressFromMethodDesc(defaultConstructor, out metadataLookupResult, out _, out _); } } } @@ -1605,7 +1603,6 @@ public bool GetMethodEntryPoint(out IntPtr methodEntrypoint, out TDictionaryComp rawMethodEntrypoint = _methodEntrypoint; methodEntrypoint = IntPtr.Zero; - dictionaryComponent = default(TDictionaryComponentType); if (!GetDictionaryComponent(out dictionaryComponent) || !GetMethodEntryPointComponent(dictionaryComponent, out methodEntrypoint)) return false; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MetadataSignatureParsing.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MetadataSignatureParsing.cs index cebdf43051c45..181804eb2e253 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MetadataSignatureParsing.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MetadataSignatureParsing.cs @@ -372,7 +372,7 @@ private bool CompareTypeSigWithType(ref NativeParser parser, TypeManagerHandle m return false; } - RuntimeTypeHandle type1 = default(RuntimeTypeHandle); + RuntimeTypeHandle type1; if (typeSignatureKind == TypeSignatureKind.External) { type1 = SigParsing.GetTypeFromNativeLayoutSignature(ref parser, moduleHandle, startOffset); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.NamedTypeLookup.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.NamedTypeLookup.cs index 697b6c2721498..8d4eab59061d5 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.NamedTypeLookup.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.NamedTypeLookup.cs @@ -292,8 +292,7 @@ public void UnregisterNewNamedTypeRuntimeTypeHandle(QTypeDefinition qTypeDefinit metadataLookupResult.VersionNumber = -1; } - NamedTypeLookupResult runtimeTypeHandleResult; - if (_runtimeTypeHandleToMetadataHashtable.TryGetValue(runtimeTypeHandle, out runtimeTypeHandleResult)) + if (_runtimeTypeHandleToMetadataHashtable.TryGetValue(runtimeTypeHandle, out _)) { metadataLookupResult.GcStaticFields = IntPtr.Zero; metadataLookupResult.NonGcStaticFields = IntPtr.Zero; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.SignatureParsing.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.SignatureParsing.cs index 3820ce7b8cd5d..e27d2336ffcfb 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.SignatureParsing.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.SignatureParsing.cs @@ -123,9 +123,7 @@ public bool TryGetMethodNameAndSignatureFromNativeLayoutSignature(RuntimeSignatu if (parser.IsNull) return false; - RuntimeSignature methodSig; - RuntimeSignature methodNameSig; - nameAndSignature = GetMethodNameAndSignature(ref parser, new TypeManagerHandle(signature.ModuleHandle), out methodNameSig, out methodSig); + nameAndSignature = GetMethodNameAndSignature(ref parser, new TypeManagerHandle(signature.ModuleHandle), out _, out _); return true; } @@ -141,7 +139,7 @@ public bool TryGetMethodNameAndSignaturePointersFromNativeLayoutSignature(TypeMa return false; methodNameSig = RuntimeSignature.CreateFromNativeLayoutSignature(module, parser.Offset); - string methodName = parser.GetString(); + parser.SkipString(); // methodName // Signatures are indirected to through a relative offset so that we don't have to parse them // when not comparing signatures (parsing them requires resolving types and is tremendously @@ -161,9 +159,7 @@ public bool TryGetMethodNameAndSignatureFromNativeLayoutOffset(TypeManagerHandle if (parser.IsNull) return false; - RuntimeSignature methodSig; - RuntimeSignature methodNameSig; - nameAndSignature = GetMethodNameAndSignature(ref parser, moduleHandle, out methodNameSig, out methodSig); + nameAndSignature = GetMethodNameAndSignature(ref parser, moduleHandle, out _, out _); return true; } @@ -295,9 +291,6 @@ internal bool GetCallingConverterDataFromMethodSignature_NativeLayout_Common( out bool[] parametersWithGenericDependentLayout, NativeReader nativeReader) { - hasThis = false; - parameters = null; - NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext(); nativeLayoutContext._module = (NativeFormatModuleInfo)methodSig.GetModuleInfo(); @@ -312,7 +305,10 @@ internal bool GetCallingConverterDataFromMethodSignature_NativeLayout_Common( MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); hasThis = !callingConvention.HasFlag(MethodCallingConvention.Static); - uint numGenArgs = callingConvention.HasFlag(MethodCallingConvention.Generic) ? parser.GetUnsigned() : 0; + if (callingConvention.HasFlag(MethodCallingConvention.Generic)) + { + parser.SkipInteger(); // numGenArgs + } uint parameterCount = parser.GetUnsigned(); parameters = new TypeDesc[parameterCount + 1]; @@ -386,7 +382,10 @@ private bool MethodSignatureHasVarsNeedingCallingConventionConverter_NativeLayou NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(new TypeManagerHandle(methodSig.ModuleHandle)); MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); - uint numGenArgs = callingConvention.HasFlag(MethodCallingConvention.Generic) ? parser.GetUnsigned() : 0; + if (callingConvention.HasFlag(MethodCallingConvention.Generic)) + { + parser.SkipInteger(); // numGenArgs + } uint parameterCount = parser.GetUnsigned(); // Check the return type of the method @@ -639,7 +638,6 @@ private bool CompareTypeSigs(ref NativeParser parser1, NativeFormatModuleInfo mo } uint data2; - uint startOffset2 = parser2.Offset; var typeSignatureKind2 = parser2.GetTypeSignatureKind(out data2); // If parser2 is a lookback type, we need to rewind parser1 to its startOffset1 diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs index 9004db49a1397..361311060cd18 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs @@ -342,7 +342,7 @@ internal unsafe NativeReader GetNativeLayoutInfoReader(TypeManagerHandle moduleH if (t_moduleNativeReaders == null) t_moduleNativeReaders = new LowLevelDictionary(); - NativeReader result = null; + NativeReader result; if (t_moduleNativeReaders.TryGetValue(moduleHandle, out result)) return result; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs index 86dc00e75efc7..a78e0a316aa05 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/RuntimeNoMetadataType.cs @@ -318,8 +318,7 @@ public string NamespaceForDiagnostics { get { - string name, nsName, assemblyName; - GetTypeNameHelper(out name, out nsName, out assemblyName); + GetTypeNameHelper(out _, out string nsName, out _); return nsName; } } @@ -328,8 +327,7 @@ public string NameForDiagnostics { get { - string name, nsName, assemblyName; - GetTypeNameHelper(out name, out nsName, out assemblyName); + GetTypeNameHelper(out string name, out _, out _); return name; } } @@ -338,8 +336,7 @@ public string DiagnosticModuleName { get { - string name, nsName, assemblyName; - GetTypeNameHelper(out name, out nsName, out assemblyName); + GetTypeNameHelper(out _, out _, out string assemblyName); return assemblyName; } } diff --git a/src/coreclr/pal/inc/pal.h b/src/coreclr/pal/inc/pal.h index 237b75275cec9..db22c68fde053 100644 --- a/src/coreclr/pal/inc/pal.h +++ b/src/coreclr/pal/inc/pal.h @@ -345,6 +345,7 @@ typedef __int64 time_t; #define PAL_INITIALIZE_DEBUGGER_EXCEPTIONS 0x10 #define PAL_INITIALIZE_ENSURE_STACK_SIZE 0x20 #define PAL_INITIALIZE_REGISTER_SIGNALS 0x40 +#define PAL_INITIALIZE_REGISTER_ACTIVATION_SIGNAL 0x80 // PAL_Initialize() flags #define PAL_INITIALIZE (PAL_INITIALIZE_SYNC_THREAD | \ @@ -359,7 +360,8 @@ typedef __int64 time_t; PAL_INITIALIZE_REGISTER_SIGTERM_HANDLER | \ PAL_INITIALIZE_DEBUGGER_EXCEPTIONS | \ PAL_INITIALIZE_ENSURE_STACK_SIZE | \ - PAL_INITIALIZE_REGISTER_SIGNALS) + PAL_INITIALIZE_REGISTER_SIGNALS | \ + PAL_INITIALIZE_REGISTER_ACTIVATION_SIGNAL) typedef DWORD (PALAPI_NOEXPORT *PTHREAD_START_ROUTINE)(LPVOID lpThreadParameter); typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; @@ -2842,24 +2844,6 @@ VirtualQuery( #define FillMemory(Destination,Length,Fill) memset((Destination),(Fill),(Length)) #define ZeroMemory(Destination,Length) memset((Destination),0,(Length)) -#define LMEM_FIXED 0x0000 -#define LMEM_MOVEABLE 0x0002 -#define LMEM_ZEROINIT 0x0040 -#define LPTR (LMEM_FIXED | LMEM_ZEROINIT) - -PALIMPORT -HLOCAL -PALAPI -LocalAlloc( - IN UINT uFlags, - IN SIZE_T uBytes); - -PALIMPORT -HLOCAL -PALAPI -LocalFree( - IN HLOCAL hMem); - PALIMPORT BOOL PALAPI @@ -3261,8 +3245,8 @@ FORCEINLINE void PAL_ArmInterlockedOperationBarrier() Function: InterlockedAdd -The InterlockedAdd function adds the value of the specified variable -with another specified value. The function prevents more than one thread +The InterlockedAdd function adds the value of the specified variable +with another specified value. The function prevents more than one thread from using the same variable simultaneously. Parameters @@ -3934,8 +3918,6 @@ PAL_GetCurrentThreadAffinitySet(SIZE_T size, UINT_PTR* data); #define wcspbrk PAL_wcspbrk #define wcscmp PAL_wcscmp #define wcsncpy PAL_wcsncpy -#define wcstok PAL_wcstok -#define wcscspn PAL_wcscspn #define realloc PAL_realloc #define fopen PAL_fopen #define strtok PAL_strtok @@ -4125,8 +4107,6 @@ PALIMPORT DLLEXPORT const WCHAR * __cdecl PAL_wcschr(const WCHAR *, WCHAR); PALIMPORT DLLEXPORT const WCHAR * __cdecl PAL_wcsrchr(const WCHAR *, WCHAR); PALIMPORT WCHAR _WConst_return * __cdecl PAL_wcspbrk(const WCHAR *, const WCHAR *); PALIMPORT DLLEXPORT WCHAR _WConst_return * __cdecl PAL_wcsstr(const WCHAR *, const WCHAR *); -PALIMPORT WCHAR * __cdecl PAL_wcstok(WCHAR *, const WCHAR *); -PALIMPORT DLLEXPORT size_t __cdecl PAL_wcscspn(const WCHAR *, const WCHAR *); PALIMPORT int __cdecl PAL_swprintf(WCHAR *, const WCHAR *, ...); PALIMPORT int __cdecl PAL_vswprintf(WCHAR *, const WCHAR *, va_list); PALIMPORT int __cdecl PAL_swscanf(const WCHAR *, const WCHAR *, ...); diff --git a/src/coreclr/pal/inc/palprivate.h b/src/coreclr/pal/inc/palprivate.h index 097229eb64ef4..f90352b32355e 100644 --- a/src/coreclr/pal/inc/palprivate.h +++ b/src/coreclr/pal/inc/palprivate.h @@ -203,8 +203,6 @@ CompareFileTime( IN CONST FILETIME *lpFileTime1, IN CONST FILETIME *lpFileTime2); -PALIMPORT char * __cdecl _fullpath(char *, const char *, size_t); - /* These are from the file in windows. They are needed for _open_osfhandle.*/ #define _O_RDONLY 0x0000 diff --git a/src/coreclr/pal/inc/rt/sal.h b/src/coreclr/pal/inc/rt/sal.h index 198b46d4a4e06..ef976be402fdc 100644 --- a/src/coreclr/pal/inc/rt/sal.h +++ b/src/coreclr/pal/inc/rt/sal.h @@ -2862,6 +2862,10 @@ of each annotation, see the advanced annotations section. #define __useHeader _Use_decl_anno_impl_ #define __on_failure(annotes) _On_failure_impl_(annotes _SAL_nop_impl_) +#ifndef __has_cpp_attribute +#define __has_cpp_attribute(x) (0) +#endif + #ifndef __fallthrough // [ #if __has_cpp_attribute(fallthrough) #define __fallthrough [[fallthrough]] diff --git a/src/coreclr/pal/src/CMakeLists.txt b/src/coreclr/pal/src/CMakeLists.txt index 4f071b21046b0..a9beb759b892f 100644 --- a/src/coreclr/pal/src/CMakeLists.txt +++ b/src/coreclr/pal/src/CMakeLists.txt @@ -123,7 +123,6 @@ set(SOURCES cruntime/malloc.cpp cruntime/math.cpp cruntime/misc.cpp - cruntime/path.cpp cruntime/printf.cpp cruntime/printfcpp.cpp cruntime/silent_printf.cpp @@ -131,7 +130,6 @@ set(SOURCES cruntime/stringtls.cpp cruntime/thread.cpp cruntime/wchar.cpp - cruntime/wchartls.cpp debug/debug.cpp exception/seh.cpp exception/signal.cpp @@ -145,14 +143,12 @@ set(SOURCES init/pal.cpp init/sxs.cpp loader/module.cpp - loader/modulename.cpp locale/unicode.cpp locale/unicodedata.cpp locale/utf8.cpp map/common.cpp map/map.cpp map/virtual.cpp - memory/local.cpp misc/cgroup.cpp misc/dbgmsg.cpp misc/environ.cpp diff --git a/src/coreclr/pal/src/cruntime/path.cpp b/src/coreclr/pal/src/cruntime/path.cpp deleted file mode 100644 index c25636771bc61..0000000000000 --- a/src/coreclr/pal/src/cruntime/path.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - path.c - -Abstract: - - Implementation of path functions part of Windows runtime library. - -Revision History: - - - ---*/ - -#include "pal/palinternal.h" -#include "pal/dbgmsg.h" -#include "pal/file.h" -#include "pal/printfcpp.hpp" - -#include -#include -#include -#include -#include - -SET_DEFAULT_DEBUG_CHANNEL(CRT); - -/*++ -Function: - _fullpath - -See MSDN doc. - ---*/ -char * -__cdecl -_fullpath( - char *absPath, - const char *relPath, - size_t maxLength) -{ - char realpath_buf[PATH_MAX+1]; - char path_copy[PATH_MAX+1]; - char *retval = NULL; - DWORD cPathCopy = sizeof(path_copy)/sizeof(path_copy[0]); - size_t min_length; - BOOL fBufAllocated = FALSE; - - PERF_ENTRY(_fullpath); - ENTRY("_fullpath (absPath=%p, relPath=%p (%s), maxLength = %lu)\n", - absPath, relPath ? relPath:"NULL", relPath ? relPath:"NULL", maxLength); - - if (strncpy_s(path_copy, sizeof(path_copy), relPath ? relPath : ".", cPathCopy) != SAFECRT_SUCCESS) - { - TRACE("_fullpath: strncpy_s failed!\n"); - goto fullpathExit; - } - - FILEDosToUnixPathA(path_copy); - - if(NULL == realpath(path_copy, realpath_buf)) - { - ERROR("realpath() failed; problem path is '%s'. errno is %d (%s)\n", - realpath_buf, errno, strerror(errno)); - goto fullpathExit; - } - - TRACE("real path is %s\n", realpath_buf); - min_length = strlen(realpath_buf)+1; // +1 for the NULL terminator - - if(NULL == absPath) - { - absPath = static_cast( - PAL_malloc(_MAX_PATH * sizeof(char))); - if (!absPath) - { - ERROR("PAL_malloc failed with error %d\n", errno); - goto fullpathExit; - } - maxLength = _MAX_PATH; - fBufAllocated = TRUE; - } - - if(min_length > maxLength) - { - ERROR("maxLength is %lu, we need at least %lu\n", - maxLength, min_length); - if (fBufAllocated) - { - PAL_free(absPath); - fBufAllocated = FALSE; - } - goto fullpathExit; - } - - strcpy_s(absPath, maxLength, realpath_buf); - retval = absPath; - -fullpathExit: - LOGEXIT("_fullpath returns char * %p\n", retval); - PERF_EXIT(_fullpath); - return retval; -} - - - diff --git a/src/coreclr/pal/src/cruntime/wchar.cpp b/src/coreclr/pal/src/cruntime/wchar.cpp index 5c21d7bd01533..3d887aecdb883 100644 --- a/src/coreclr/pal/src/cruntime/wchar.cpp +++ b/src/coreclr/pal/src/cruntime/wchar.cpp @@ -3,8 +3,6 @@ /*++ - - Module Name: wchar.c @@ -13,11 +11,8 @@ Module Name: Implementation of wide char string functions. - - --*/ - #include "pal/palinternal.h" #include "pal/cruntime.h" #include "pal/dbgmsg.h" @@ -25,7 +20,6 @@ Module Name: #include "pal/thread.hpp" #include "pal/threadsusp.hpp" - #if HAVE_CONFIG_H #include "config.h" #endif @@ -950,46 +944,3 @@ PAL_wcstod( const wchar_16 * nptr, wchar_16 **endptr ) PERF_EXIT(wcstod); return RetVal; } - -/*++ -Function: - PAL_wcscspn - -Finds the number of consecutive characters from the start of the string -that are not in the set. - -Return value: - -The number of characters from the start of the string that are not in -the set. - -Parameters: -string String -strCharSet Set of delimiter characters - ---*/ -size_t -__cdecl -PAL_wcscspn(const wchar_16 *string, const wchar_16 *strCharSet) -{ - const wchar_16 *temp; - size_t count = 0; - - PERF_ENTRY(wcscspn); - - while(*string != 0) - { - for(temp = strCharSet; *temp != 0; temp++) - { - if (*string == *temp) - { - PERF_EXIT(wcscspn); - return count; - } - } - count++; - string++; - } - PERF_EXIT(wcscspn); - return count; -} diff --git a/src/coreclr/pal/src/cruntime/wchartls.cpp b/src/coreclr/pal/src/cruntime/wchartls.cpp deleted file mode 100644 index 35b73359889a5..0000000000000 --- a/src/coreclr/pal/src/cruntime/wchartls.cpp +++ /dev/null @@ -1,125 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - wchartls.c - -Abstract: - - Implementation of wide char string functions that depend on per-thread data - - - ---*/ - -#include "pal/palinternal.h" -#include "pal/thread.hpp" -#include "pal/dbgmsg.h" - -using namespace CorUnix; - - -SET_DEFAULT_DEBUG_CHANNEL(CRT); - -/*++ -Function: - PAL_wcstok - -Finds the next token in a wide character string. - -Return value: - -A pointer to the next token found in strToken. Returns NULL when no more -tokens are found. Each call modifies strToken by substituting a NULL -character for each delimiter that is encountered. - -Parameters: -strToken String containing token(s) -strDelimit Set of delimiter characters - ---*/ -WCHAR * -__cdecl -PAL_wcstok(WCHAR *strToken, const WCHAR *strDelimit) -{ - CPalThread *pThread = NULL; - WCHAR *retval = NULL; - WCHAR *delim_ptr; - WCHAR *next_context; /* string to save in TLS for future calls */ - - PERF_ENTRY(wcstok); - ENTRY("PAL_wcstok (strToken=%p (%S), strDelimit=%p (%S))\n", - strToken?strToken:W16_NULLSTRING, - strToken?strToken:W16_NULLSTRING, - strDelimit?strDelimit:W16_NULLSTRING, - strDelimit?strDelimit:W16_NULLSTRING); - - /* Get the per-thread buffer from the thread structure. */ - pThread = InternalGetCurrentThread(); - - if(NULL == strDelimit) - { - ERROR("delimiter string is NULL\n"); - goto done; - } - - /* get token string from TLS if none is provided */ - if(NULL == strToken) - { - TRACE("wcstok() called with NULL string, using previous string\n"); - strToken = pThread->crtInfo.wcstokContext; - if(NULL == strToken) - { - ERROR("wcstok called with NULL string without a previous call\n"); - goto done; - } - } - - /* first, skip all leading delimiters */ - while ((*strToken != '\0') && (PAL_wcschr(strDelimit,*strToken))) - { - strToken++; - } - - /* if there were only delimiters, there's no string */ - if('\0' == strToken[0]) - { - TRACE("end of string already reached, returning NULL\n"); - goto done; - } - - /* we're now at the beginning of the token; look for the first delimiter */ - delim_ptr = PAL_wcspbrk(strToken,strDelimit); - if(NULL == delim_ptr) - { - TRACE("no delimiters found, this is the last token\n"); - /* place the next context at the end of the string, so that subsequent - calls will return NULL */ - next_context = strToken+PAL_wcslen(strToken); - retval = strToken; - } - else - { - /* null-terminate current token */ - *delim_ptr=0; - - /* place the next context right after the delimiter */ - next_context = delim_ptr+1; - retval = strToken; - - TRACE("found delimiter; next token will be %p\n",next_context); - } - - pThread->crtInfo.wcstokContext = next_context; - -done: - LOGEXIT("PAL_wcstok() returns %p (%S)\n", retval?retval:W16_NULLSTRING, retval?retval:W16_NULLSTRING); - PERF_EXIT(wcstok); - return(retval); -} - diff --git a/src/coreclr/pal/src/exception/remote-unwind.cpp b/src/coreclr/pal/src/exception/remote-unwind.cpp index af0293ba5bc60..b27fc9680bbed 100644 --- a/src/coreclr/pal/src/exception/remote-unwind.cpp +++ b/src/coreclr/pal/src/exception/remote-unwind.cpp @@ -57,6 +57,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include #include #include "compact_unwind_encoding.h" +#define MACOS_ARM64_POINTER_AUTH_MASK 0x7fffffffffffull #endif // Sub-headers included from the libunwind.h contain an empty struct @@ -1422,25 +1423,56 @@ StepWithCompactNoEncoding(const libunwindInfo* info) #if defined(TARGET_ARM64) -inline static bool +#define ARM64_SYSCALL_OPCODE 0xD4001001 +#define ARM64_BL_OPCODE_MASK 0xFC000000 +#define ARM64_BL_OPCODE 0x94000000 +#define ARM64_BLR_OPCODE_MASK 0xFFFFFC00 +#define ARM64_BLR_OPCODE 0xD63F0000 +#define ARM64_BLRA_OPCODE_MASK 0xFEFFF800 +#define ARM64_BLRA_OPCODE 0xD63F0800 + +static bool +StepWithCompactNoEncoding(const libunwindInfo* info) +{ + // Check that the function is a syscall "wrapper" and assume there is no frame and pop the return address. + uint32_t opcode; + unw_word_t addr = info->Context->Pc - sizeof(opcode); + if (!ReadValue32(info, &addr, &opcode)) { + ERROR("StepWithCompactNoEncoding: can read opcode %p\n", (void*)addr); + return false; + } + // Is the IP pointing just after a "syscall" opcode? + if (opcode != ARM64_SYSCALL_OPCODE) { + ERROR("StepWithCompactNoEncoding: not in syscall wrapper function\n"); + return false; + } + // Pop the return address from the stack + info->Context->Pc = info->Context->Lr; + TRACE("StepWithCompactNoEncoding: SUCCESS new pc %p sp %p\n", (void*)info->Context->Pc, (void*)info->Context->Sp); + return true; +} + +static bool ReadCompactEncodingRegister(const libunwindInfo* info, unw_word_t* addr, DWORD64* reg) { - *addr -= sizeof(uint64_t); - if (!ReadValue64(info, addr, (uint64_t*)reg)) { + uint64_t value; + if (!info->ReadMemory((PVOID)*addr, &value, sizeof(value))) { return false; } + *reg = VAL64(value); + *addr -= sizeof(uint64_t); return true; } -inline static bool -ReadCompactEncodingRegisterPair(const libunwindInfo* info, unw_word_t* addr, DWORD64*second, DWORD64* first) +static bool +ReadCompactEncodingRegisterPair(const libunwindInfo* info, unw_word_t* addr, DWORD64* first, DWORD64* second) { // Registers are effectively pushed in pairs // + // *first = **addr // *addr -= 8 - // **addr = *first + // *second= **addr // *addr -= 8 - // **addr = *second if (!ReadCompactEncodingRegister(info, addr, first)) { return false; } @@ -1450,8 +1482,8 @@ ReadCompactEncodingRegisterPair(const libunwindInfo* info, unw_word_t* addr, DWO return true; } -inline static bool -ReadCompactEncodingRegisterPair(const libunwindInfo* info, unw_word_t* addr, NEON128*second, NEON128* first) +static bool +ReadCompactEncodingRegisterPair(const libunwindInfo* info, unw_word_t* addr, NEON128* first, NEON128* second) { if (!ReadCompactEncodingRegisterPair(info, addr, &first->Low, &second->Low)) { return false; @@ -1484,30 +1516,28 @@ static bool StepWithCompactEncodingArm64(const libunwindInfo* info, compact_unwind_encoding_t compactEncoding, bool hasFrame) { CONTEXT* context = info->Context; + unw_word_t addr; - unw_word_t callerSp; - - if (hasFrame) { - // caller Sp is callee Fp plus saved FP and LR - callerSp = context->Fp + 2 * sizeof(uint64_t); - } else { + if (hasFrame) + { + context->Sp = context->Fp + 16; + addr = context->Fp + 8; + if (!ReadCompactEncodingRegisterPair(info, &addr, &context->Lr, &context->Fp)) { + return false; + } + // Strip pointer authentication bits + context->Lr &= MACOS_ARM64_POINTER_AUTH_MASK; + } + else + { // Get the leat significant bit in UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK uint64_t stackSizeScale = UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK & ~(UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK - 1); - uint64_t stackSize = (compactEncoding & UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK) / stackSizeScale * 16; + uint64_t stackSize = ((compactEncoding & UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK) / stackSizeScale) * 16; - callerSp = context->Sp + stackSize; + addr = context->Sp + stackSize; } - context->Sp = callerSp; - - unw_word_t addr = callerSp; - - if (hasFrame && - !ReadCompactEncodingRegisterPair(info, &addr, &context->Lr, &context->Fp)) { - return false; - } - - // unwound return address is stored in Lr + // Unwound return address is stored in Lr context->Pc = context->Lr; if (compactEncoding & UNWIND_ARM64_FRAME_X19_X20_PAIR && @@ -1546,7 +1576,10 @@ StepWithCompactEncodingArm64(const libunwindInfo* info, compact_unwind_encoding_ !ReadCompactEncodingRegisterPair(info, &addr, &context->V[14], &context->V[15])) { return false; } - + if (!hasFrame) + { + context->Sp = addr; + } TRACE("SUCCESS: compact step encoding %08x pc %p sp %p fp %p lr %p\n", compactEncoding, (void*)context->Pc, (void*)context->Sp, (void*)context->Fp, (void*)context->Lr); return true; @@ -1557,11 +1590,11 @@ StepWithCompactEncodingArm64(const libunwindInfo* info, compact_unwind_encoding_ static bool StepWithCompactEncoding(const libunwindInfo* info, compact_unwind_encoding_t compactEncoding, unw_word_t functionStart) { -#if defined(TARGET_AMD64) if (compactEncoding == 0) { return StepWithCompactNoEncoding(info); } +#if defined(TARGET_AMD64) switch (compactEncoding & UNWIND_X86_64_MODE_MASK) { case UNWIND_X86_64_MODE_RBP_FRAME: @@ -1575,11 +1608,6 @@ StepWithCompactEncoding(const libunwindInfo* info, compact_unwind_encoding_t com return false; } #elif defined(TARGET_ARM64) - if (compactEncoding == 0) - { - TRACE("Compact unwind missing for %p\n", (void*)info->Context->Pc); - return false; - } switch (compactEncoding & UNWIND_ARM64_MODE_MASK) { case UNWIND_ARM64_MODE_FRAME: @@ -1717,6 +1745,12 @@ static void UnwindContextToContext(unw_cursor_t *cursor, CONTEXT *winContext) unw_get_reg(cursor, UNW_AARCH64_X28, (unw_word_t *) &winContext->X28); unw_get_reg(cursor, UNW_AARCH64_X29, (unw_word_t *) &winContext->Fp); unw_get_reg(cursor, UNW_AARCH64_X30, (unw_word_t *) &winContext->Lr); +#ifdef __APPLE__ + // Strip pointer authentication bits which seem to be leaking out of libunwind + // Seems like ptrauth_strip() / __builtin_ptrauth_strip() should work, but currently + // errors with "this target does not support pointer authentication" + winContext->Pc = winContext->Pc & MACOS_ARM64_POINTER_AUTH_MASK; +#endif // __APPLE__ TRACE("sp %p pc %p lr %p fp %p\n", winContext->Sp, winContext->Pc, winContext->Lr, winContext->Fp); #elif defined(TARGET_S390X) unw_get_reg(cursor, UNW_REG_IP, (unw_word_t *) &winContext->PSWAddr); @@ -2126,6 +2160,33 @@ PAL_VirtualUnwindOutOfProc(CONTEXT *context, KNONVOLATILE_CONTEXT_POINTERS *cont #elif defined(TARGET_ARM64) TRACE("Unwind: pc %p sp %p fp %p\n", (void*)context->Pc, (void*)context->Sp, (void*)context->Fp); result = GetProcInfo(context->Pc, &procInfo, &info, &step, false); + if (result && step) + { + // If the PC is at the start of the function, the previous instruction is BL and the unwind encoding is frameless + // with nothing on stack (0x02000000), back up PC by 1 to the previous function and get the unwind info for that + // function. + if ((context->Pc == procInfo.start_ip) && + (procInfo.format & (UNWIND_ARM64_MODE_MASK | UNWIND_ARM64_FRAMELESS_STACK_SIZE_MASK)) == UNWIND_ARM64_MODE_FRAMELESS) + { + uint32_t opcode; + unw_word_t addr = context->Pc - sizeof(opcode); + if (ReadValue32(&info, &addr, &opcode)) + { + // Is the previous instruction a BL opcode? + if ((opcode & ARM64_BL_OPCODE_MASK) == ARM64_BL_OPCODE || + (opcode & ARM64_BLR_OPCODE_MASK) == ARM64_BLR_OPCODE || + (opcode & ARM64_BLRA_OPCODE_MASK) == ARM64_BLRA_OPCODE) + { + TRACE("Unwind: getting unwind info for PC - 1 opcode %08x\n", opcode); + result = GetProcInfo(context->Pc - 1, &procInfo, &info, &step, false); + } + else + { + TRACE("Unwind: not BL* opcode %08x\n", opcode); + } + } + } + } #else #error Unexpected architecture #endif diff --git a/src/coreclr/pal/src/exception/seh-unwind.cpp b/src/coreclr/pal/src/exception/seh-unwind.cpp index 4b149f941b5dc..750f19109fbaa 100644 --- a/src/coreclr/pal/src/exception/seh-unwind.cpp +++ b/src/coreclr/pal/src/exception/seh-unwind.cpp @@ -699,7 +699,7 @@ PAL_FreeExceptionRecords(IN EXCEPTION_RECORD *exceptionRecord, IN CONTEXT *conte Note: The name of this function and the name of the ExceptionRecord parameter is used in the sos lldb plugin code to read the exception - record. See coreclr\ToolBox\SOS\lldbplugin\services.cpp. + record. See coreclr\tools\SOS\lldbplugin\services.cpp. This function must not be inlined or optimized so the below PAL_VirtualUnwind calls end up with RaiseException caller's context and so the above debugger diff --git a/src/coreclr/pal/src/exception/signal.cpp b/src/coreclr/pal/src/exception/signal.cpp index 521150530fa33..58fc78ef357e8 100644 --- a/src/coreclr/pal/src/exception/signal.cpp +++ b/src/coreclr/pal/src/exception/signal.cpp @@ -240,8 +240,11 @@ BOOL SEHInitializeSignals(CorUnix::CPalThread *pthrCurrent, DWORD flags) } #ifdef INJECT_ACTIVATION_SIGNAL - handle_signal(INJECT_ACTIVATION_SIGNAL, inject_activation_handler, &g_previous_activation); - g_registered_activation_handler = true; + if (flags & PAL_INITIALIZE_REGISTER_ACTIVATION_SIGNAL) + { + handle_signal(INJECT_ACTIVATION_SIGNAL, inject_activation_handler, &g_previous_activation); + g_registered_activation_handler = true; + } #endif return TRUE; diff --git a/src/coreclr/pal/src/include/pal/modulename.h b/src/coreclr/pal/src/include/pal/modulename.h deleted file mode 100644 index 87d54b77a5b95..0000000000000 --- a/src/coreclr/pal/src/include/pal/modulename.h +++ /dev/null @@ -1,35 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - include/pal/modulename.h - -Abstract: - Header file for functions to get the name of a module - -Revision History: - - - ---*/ - -#ifndef _PAL_MODULENAME_H_ -#define _PAL_MODULENAME_H_ - -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus - -const char *PAL_dladdr(LPVOID ProcAddress); - -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif /*_PAL_MODULENAME_H_*/ diff --git a/src/coreclr/pal/src/include/pal/palinternal.h b/src/coreclr/pal/src/include/pal/palinternal.h index 3a12d78910364..ff3703c6ae4f7 100644 --- a/src/coreclr/pal/src/include/pal/palinternal.h +++ b/src/coreclr/pal/src/include/pal/palinternal.h @@ -526,8 +526,6 @@ function_name() to call the system's implementation #undef wcsstr #undef wcscmp #undef wcsncpy -#undef wcstok -#undef wcscspn #undef iswupper #undef iswspace #undef towlower diff --git a/src/coreclr/pal/src/loader/module.cpp b/src/coreclr/pal/src/loader/module.cpp index e792f75a2b22e..2a559b56e2bef 100644 --- a/src/coreclr/pal/src/loader/module.cpp +++ b/src/coreclr/pal/src/loader/module.cpp @@ -30,7 +30,6 @@ SET_DEFAULT_DEBUG_CHANNEL(LOADER); // some headers have code with asserts, so do #include "pal/file.h" #include "pal/utils.h" #include "pal/init.h" -#include "pal/modulename.h" #include "pal/environ.h" #include "pal/virtual.h" #include "pal/map.hpp" @@ -342,9 +341,10 @@ GetProcAddress( /* if we don't know the module's full name yet, this is our chance to obtain it */ if (!module->lib_name && module->dl_handle) { - const char* libName = PAL_dladdr((LPVOID)ProcAddress); - if (libName) + Dl_info dl_info; + if (dladdr((LPVOID)ProcAddress, &dl_info) != 0) { + const char* libName = dl_info.dli_fname; module->lib_name = UTIL_MBToWC_Alloc(libName, -1); if (nullptr == module->lib_name) { @@ -356,6 +356,10 @@ GetProcAddress( module, libName); } } + else + { + TRACE("GetProcAddress: dladdr() call failed!\n"); + } } } else @@ -925,7 +929,7 @@ struct CopyModuleDataParam int result; }; -void handle_image_range(uint8_t* source_start, size_t size, struct CopyModuleDataParam* param) +void handle_image_range(uint8_t* source_start, size_t size, struct CopyModuleDataParam* param) { uint8_t* source_end = source_start + size; if (param->destination_buffer_start != NULL) diff --git a/src/coreclr/pal/src/loader/modulename.cpp b/src/coreclr/pal/src/loader/modulename.cpp deleted file mode 100644 index 40c1c6de5c3d6..0000000000000 --- a/src/coreclr/pal/src/loader/modulename.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - modulename.cpp - -Abstract: - - Implementation of internal functions to get module names - - - ---*/ - -#include "pal/thread.hpp" -#include "pal/malloc.hpp" -#include "pal/palinternal.h" -#include "pal/dbgmsg.h" -#include "pal/modulename.h" - -#include - -using namespace CorUnix; - -SET_DEFAULT_DEBUG_CHANNEL(LOADER); - -/*++ - PAL_dladdr - - Internal wrapper for dladder used only to get module name - -Parameters: - LPVOID ProcAddress: a pointer to a function in a shared library - -Return value: - Pointer to string with the fullpath to the shared library containing - ProcAddress. - - NULL if error occurred. - -Notes: - The string returned by this function is owned by the OS. - If you need to keep it, strdup() it, because it is unknown how long - this ptr will point at the string you want (over the lifetime of - the system running) It is only safe to use it immediately after calling - this function. ---*/ -const char *PAL_dladdr(LPVOID ProcAddress) -{ - Dl_info dl_info; - if (!dladdr(ProcAddress, &dl_info)) - { - WARN("dladdr() call failed!\n"); - /* If we get an error, return NULL */ - return (NULL); - } - else - { - /* Return the module name */ - return dl_info.dli_fname; - } -} - diff --git a/src/coreclr/pal/src/memory/local.cpp b/src/coreclr/pal/src/memory/local.cpp deleted file mode 100644 index fc62ef428b1e2..0000000000000 --- a/src/coreclr/pal/src/memory/local.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - local.c - -Abstract: - - Implementation of local memory management functions. - -Revision History: - - - ---*/ - -#include "pal/palinternal.h" -#include "pal/dbgmsg.h" - - -SET_DEFAULT_DEBUG_CHANNEL(MEM); - - -/*++ -Function: - LocalAlloc - -See MSDN doc. ---*/ -HLOCAL -PALAPI -LocalAlloc( - IN UINT uFlags, - IN SIZE_T uBytes) -{ - LPVOID lpRetVal = NULL; - PERF_ENTRY(LocalAlloc); - ENTRY("LocalAlloc (uFlags=%#x, uBytes=%u)\n", uFlags, uBytes); - - if ((uFlags & ~LMEM_ZEROINIT) != 0) - { - ASSERT("Invalid parameter AllocFlags=0x%x\n", uFlags); - SetLastError(ERROR_INVALID_PARAMETER); - goto done; - } - - lpRetVal = PAL_malloc(uBytes); - - if (lpRetVal == NULL) - { - ERROR("Not enough memory\n"); - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - - if ((uFlags & LMEM_ZEROINIT) != 0) - { - memset(lpRetVal, 0, uBytes); - } - -done: - LOGEXIT( "LocalAlloc returning %p.\n", lpRetVal ); - PERF_EXIT(LocalAlloc); - return (HLOCAL) lpRetVal; -} - -/*++ -Function: - LocalFree - -See MSDN doc. ---*/ -HLOCAL -PALAPI -LocalFree( - IN HLOCAL hMem) -{ - BOOL bRetVal = FALSE; - PERF_ENTRY(LocalFree); - ENTRY("LocalFree (hmem=%p)\n", hMem); - - free(hMem); - bRetVal = TRUE; - - LOGEXIT( "LocalFree returning %p.\n", bRetVal == TRUE ? (HLOCAL)NULL : hMem ); - PERF_EXIT(LocalFree); - return bRetVal == TRUE ? (HLOCAL)NULL : hMem; -} diff --git a/src/coreclr/pal/src/misc/fmtmessage.cpp b/src/coreclr/pal/src/misc/fmtmessage.cpp index 81502bfc7722e..e9d87d19c4a08 100644 --- a/src/coreclr/pal/src/misc/fmtmessage.cpp +++ b/src/coreclr/pal/src/misc/fmtmessage.cpp @@ -63,7 +63,7 @@ static LPWSTR FMTMSG_GetMessageString( DWORD dwErrCode ) allocChars = MAX_ERROR_STRING_LENGTH + 1; } - LPWSTR lpRetVal = (LPWSTR)LocalAlloc(LMEM_FIXED, allocChars * sizeof(WCHAR)); + LPWSTR lpRetVal = (LPWSTR)PAL_malloc(allocChars * sizeof(WCHAR)); if (lpRetVal) { @@ -135,7 +135,7 @@ static INT FMTMSG__watoi( LPWSTR str ) UINT NumOfBytes = 0; \ nSize *= 2; \ NumOfBytes = nSize * sizeof( WCHAR ); \ - lpTemp = static_cast( LocalAlloc( LMEM_FIXED, NumOfBytes ) ); \ + lpTemp = static_cast( PAL_malloc( NumOfBytes ) ); \ TRACE( "Growing the buffer.\n" );\ \ if ( !lpTemp ) \ @@ -149,7 +149,7 @@ static INT FMTMSG__watoi( LPWSTR str ) \ *lpWorkingString = '\0';\ PAL_wcscpy( lpTemp, lpReturnString );\ - LocalFree( lpReturnString ); \ + free( lpReturnString ); \ lpWorkingString = lpReturnString = lpTemp; \ lpWorkingString += nCount; \ } \ @@ -341,7 +341,7 @@ FormatMessageW( /* Parameter processing. */ if ( dwFlags & FORMAT_MESSAGE_ALLOCATE_BUFFER ) { - TRACE( "Allocated %d TCHARs. Don't forget to call LocalFree to " + TRACE( "Allocated %d TCHARs. Don't forget to call free to " "free the memory when done.\n", nSize ); bIsLocalAlloced = TRUE; } @@ -418,7 +418,7 @@ FormatMessageW( } lpWorkingString = static_cast( - LocalAlloc( LMEM_FIXED, nSize * sizeof( WCHAR ) ) ); + PAL_malloc( nSize * sizeof( WCHAR ) ) ); if ( !lpWorkingString ) { ERROR( "Unable to allocate memory for the working string.\n" ); @@ -675,14 +675,14 @@ FormatMessageW( { TRACE( "Copying the string into the buffer.\n" ); PAL_wcsncpy( lpBuffer, lpReturnString, nCount + 1 ); - LocalFree( lpReturnString ); + free( lpReturnString ); } } else /* Error, something occurred. */ { if ( lpReturnString ) { - LocalFree( lpReturnString ); + free( lpReturnString ); } } LOGEXIT( "FormatMessageW returns %d.\n", nCount ); diff --git a/src/coreclr/pal/src/thread/process.cpp b/src/coreclr/pal/src/thread/process.cpp index 76135d655f934..cd62cb917635d 100644 --- a/src/coreclr/pal/src/thread/process.cpp +++ b/src/coreclr/pal/src/thread/process.cpp @@ -73,7 +73,7 @@ SET_DEFAULT_DEBUG_CHANNEL(PROCESS); // some headers have code with asserts, so d # define __NR_membarrier 389 # elif defined(__aarch64__) # define __NR_membarrier 283 -# elif +# else # error Unknown architecture # endif # endif diff --git a/src/coreclr/pal/tests/palsuite/CMakeLists.txt b/src/coreclr/pal/tests/palsuite/CMakeLists.txt index f58757a1f6d5f..f14b2442afa78 100644 --- a/src/coreclr/pal/tests/palsuite/CMakeLists.txt +++ b/src/coreclr/pal/tests/palsuite/CMakeLists.txt @@ -415,7 +415,6 @@ add_executable_clr(paltests c_runtime/wcsstr/test1/test1.cpp c_runtime/wcstod/test1/test1.cpp c_runtime/wcstod/test2/test2.cpp - c_runtime/wcstok/test1/test1.cpp c_runtime/wcstoul/test1/test1.cpp c_runtime/wcstoul/test2/test2.cpp c_runtime/wcstoul/test3/test3.cpp @@ -581,9 +580,6 @@ add_executable_clr(paltests # filemapping_memmgt/GetProcAddress/test1/testlib.cpp filemapping_memmgt/GetProcAddress/test2/test2.cpp # filemapping_memmgt/GetProcAddress/test2/testlib.cpp - filemapping_memmgt/LocalAlloc/test1/LocalAlloc.cpp - filemapping_memmgt/LocalFree/test1/LocalFree.cpp - filemapping_memmgt/LocalFree/test2/LocalFree.cpp filemapping_memmgt/MapViewOfFile/test1/MapViewOfFile.cpp filemapping_memmgt/MapViewOfFile/test2/MapViewOfFile.cpp filemapping_memmgt/MapViewOfFile/test3/MapViewOfFile.cpp diff --git a/src/coreclr/pal/tests/palsuite/c_runtime/wcstok/test1/test1.cpp b/src/coreclr/pal/tests/palsuite/c_runtime/wcstok/test1/test1.cpp deleted file mode 100644 index 564466c2a4e7f..0000000000000 --- a/src/coreclr/pal/tests/palsuite/c_runtime/wcstok/test1/test1.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================================ -** -** Source: test1.c -** -** Purpose: -** Search for a number of tokens within strings. Check that the return values -** are what is expected, and also that the strings match up with our expected -** results. -** -** -**==========================================================================*/ - -#include - -PALTEST(c_runtime_wcstok_test1_paltest_wcstok_test1, "c_runtime/wcstok/test1/paltest_wcstok_test1") -{ - /* foo bar baz */ - WCHAR str[] = {'f','o','o',' ','b','a','r',' ','b','a','z','\0'}; - - /* foo \0ar baz */ - WCHAR result1[] = {'f','o','o',' ','\0','a','r',' ','b','a','z','\0'}; - - /* foo \0a\0 baz */ - WCHAR result2[] = {'f','o','o',' ','\0','a','\0',' ','b','a','z','\0'}; - - WCHAR* tempString; - int len = 0; - WCHAR *ptr; - - if (PAL_Initialize(argc, argv)) - { - return FAIL; - } - - len = (wcslen(str)*sizeof(WCHAR)) + 2; - - /* Tokenize 'str'. It will hit the 'b' delimiter first. Check to see - that the ptr is pointing to the start of the string and do a compare - to ensure the tokenized string is what we expected. - */ - - tempString = convert("bz"); - ptr = wcstok(str, tempString); - free(tempString); - - if (ptr != str) - { - Fail("ERROR: Expected wcstok() to return %p, got %p!\n", str, ptr); - } - - if (memcmp(str, result1, len) != 0) - { - Fail("ERROR: wcstok altered the string in an unexpected fashion."); - } - - /* If NULL is passed as the first parameter, wcstok will continue - tokenizing the same string. Test that this works properly. - */ - tempString = convert("r "); - ptr = wcstok(NULL, tempString); - free(tempString); - - if (ptr != str + 5) - { - Fail("ERROR: Expected wcstok() to return %p, got %p!\n", str+5, ptr); - } - - if (memcmp(str, result2, len) != 0) - { - Fail("ERROR: wcstok altered the string in an unexpected fashion."); - } - - /* Continue onward, and search for 'X' now, which won't be found. The - pointer should point just after the last NULL in the string. And - the string itself shouldn't have changed. - */ - tempString = convert("X"); - ptr = wcstok(NULL, tempString); - free(tempString); - - if (ptr != str + 7) - { - Fail("ERROR: Expected wcstok() to return %p, got %p!\n", str + 7, ptr); - } - - if (memcmp(str, result2, len) != 0) - { - Fail("ERROR: wcstok altered the string in an unexpeced fashion.\n"); - } - - /* Call wcstok again. Now the ptr should point to the end of the - string at NULL. And the string itself shouldn't have changed. - */ - tempString = convert("X"); - ptr = wcstok(NULL, tempString); - free(tempString); - - if (ptr != NULL) - { - Fail("ERROR: Expected wcstok() to return %p, got %p!\n", NULL, ptr); - } - - if (memcmp(str, result2, len) != 0) - { - Fail("ERROR: wcstok altered the string in an unexpeced fashion.\n"); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/compilableTests.txt b/src/coreclr/pal/tests/palsuite/compilableTests.txt index c674de294db45..a7e27f9228976 100644 --- a/src/coreclr/pal/tests/palsuite/compilableTests.txt +++ b/src/coreclr/pal/tests/palsuite/compilableTests.txt @@ -348,7 +348,6 @@ c_runtime/wcsrchr/test1/paltest_wcsrchr_test1 c_runtime/wcsstr/test1/paltest_wcsstr_test1 c_runtime/wcstod/test1/paltest_wcstod_test1 c_runtime/wcstod/test2/paltest_wcstod_test2 -c_runtime/wcstok/test1/paltest_wcstok_test1 c_runtime/wcstoul/test1/paltest_wcstoul_test1 c_runtime/wcstoul/test2/paltest_wcstoul_test2 c_runtime/wcstoul/test3/paltest_wcstoul_test3 @@ -487,9 +486,6 @@ filemapping_memmgt/GetModuleFileNameW/test1/paltest_getmodulefilenamew_test1 filemapping_memmgt/GetModuleFileNameW/test2/paltest_getmodulefilenamew_test2 filemapping_memmgt/GetProcAddress/test1/paltest_getprocaddress_test1 filemapping_memmgt/GetProcAddress/test2/paltest_getprocaddress_test2 -filemapping_memmgt/LocalAlloc/test1/paltest_localalloc_test1 -filemapping_memmgt/LocalFree/test1/paltest_localfree_test1 -filemapping_memmgt/LocalFree/test2/paltest_localfree_test2 filemapping_memmgt/MapViewOfFile/test1/paltest_mapviewoffile_test1 filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2 filemapping_memmgt/MapViewOfFile/test3/paltest_mapviewoffile_test3 diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalAlloc/test1/LocalAlloc.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalAlloc/test1/LocalAlloc.cpp deleted file mode 100644 index 5879ed598071a..0000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalAlloc/test1/LocalAlloc.cpp +++ /dev/null @@ -1,48 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: LocalAlloc.c -** -** Purpose: Positive test the LocalAlloc API. -** Call LocalAlloc with zero as the allocation attribute -** -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_LocalAlloc_test1_paltest_localalloc_test1, "filemapping_memmgt/LocalAlloc/test1/paltest_localalloc_test1") -{ - HLOCAL LocalHeap; - HLOCAL FreeHeap; - int err; - const SIZE_T heapSize = 64; - - /*Initialize the PAL environment*/ - err = PAL_Initialize(argc, argv); - if(0 != err) - { - return FAIL; - } - - /*Allocate the specified number of bytes from the heap*/ - /*with allocation attribute: zero which is required by PAL Doc*/ - LocalHeap = LocalAlloc(0, heapSize); - if(!LocalHeap) - { - Fail("\nFailed to call LocalAlloc API, " - "error code=%u\n", GetLastError()); - } - - /*Free the allocated local heap memory*/ - FreeHeap = LocalFree(LocalHeap); - if(FreeHeap) - { - Fail("Failed to call LocalFree API, " - "error code=%u\n", GetLastError()); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalFree/test1/LocalFree.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalFree/test1/LocalFree.cpp deleted file mode 100644 index 0fcb32d6fc96f..0000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalFree/test1/LocalFree.cpp +++ /dev/null @@ -1,48 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: LocalFree.c -** -** Purpose: Positive test the LocalFree API. -** Call LocalFree to free a specified local memory object -** -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_LocalFree_test1_paltest_localfree_test1, "filemapping_memmgt/LocalFree/test1/paltest_localfree_test1") -{ - HLOCAL LocalHeap; - HLOCAL FreeHeap; - int err; - const SIZE_T heapSize = 64; - - /*Initialize the PAL environment*/ - err = PAL_Initialize(argc, argv); - if(0 != err) - { - return FAIL; - } - - /*Allocate the specified number of bytes from the heap*/ - /*with zero ad the allocation attribute*/ - LocalHeap = LocalAlloc(0, heapSize); - if(!LocalHeap) - { - Fail("\nFailed to call LocalAlloc API, " - "error code=%u\n", GetLastError()); - } - - /*Free the allocated local heap memory*/ - FreeHeap = LocalFree(LocalHeap); - if(FreeHeap) - { - Fail("Failed to call LocalFree API, " - "error code=%u\n", GetLastError()); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalFree/test2/LocalFree.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalFree/test2/LocalFree.cpp deleted file mode 100644 index 5d66077a2cfd7..0000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/LocalFree/test2/LocalFree.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: LocalFree.c -** -** Purpose: Positive test the LocalFree API. -** call LocalFree by passing NULL as local memory -** object handle -** -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_LocalFree_test2_paltest_localfree_test2, "filemapping_memmgt/LocalFree/test2/paltest_localfree_test2") -{ - HLOCAL FreeHeap; - int err; - - /*Initialize the PAL environment*/ - err = PAL_Initialize(argc, argv); - if(0 != err) - { - return FAIL; - } - - /*call LocalFree by passing NULL as local memory object handle*/ - FreeHeap = LocalFree(NULL); - if(FreeHeap) - { - Fail("Failed to call LocalFree API, " - "error code=%u\n", GetLastError()); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test6/loadlibrarya.cpp b/src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test6/loadlibrarya.cpp index d71e0ea85c333..93363488bc61d 100644 --- a/src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test6/loadlibrarya.cpp +++ b/src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test6/loadlibrarya.cpp @@ -7,9 +7,9 @@ ** ** Purpose: Positive test the LoadLibrary API. Test will verify ** that it is unable to load the library twice. Once by -** using the full path name and secondly by using the +** using the full path name and secondly by using the ** short name. -** +** ** **============================================================*/ @@ -25,14 +25,13 @@ typedef int (*dllfunct)(); #define GETATTACHCOUNTNAME "_GetAttachCount@0" #endif - /* Helper function to test the loaded library. */ BOOL PALAPI TestDll(HMODULE hLib) { int RetVal; char FunctName[] = GETATTACHCOUNTNAME; - FARPROC DllFunc; + FARPROC DllFunc; /* Access a function from the loaded library. */ @@ -45,7 +44,7 @@ BOOL PALAPI TestDll(HMODULE hLib) return (FALSE); } - /* Verify that the DLL_PROCESS_ATTACH is only + /* Verify that the DLL_PROCESS_ATTACH is only * accessed once.*/ RetVal = DllFunc(); if (RetVal != 1) @@ -70,7 +69,7 @@ PALTEST(loader_LoadLibraryA_test6_paltest_loadlibrarya_test6, "loader/LoadLibrar char fname[_MAX_FNAME]; char ext[_MAX_EXT]; - + /* Initialize the PAL. */ if ((PAL_Initialize(argc, argv)) != 0) @@ -84,15 +83,15 @@ PALTEST(loader_LoadLibraryA_test6_paltest_loadlibrarya_test6, "loader/LoadLibrar /* Get the full path to the library (DLL). */ - - if (NULL != _fullpath(fullPath,argv[0],_MAX_DIR)) { - + + if (NULL != realpath(argv[0],fullpath)) { + _splitpath(fullPath,drive,dir,fname,ext); _makepath(fullPath,drive,dir,LibraryName,""); - - + + } else { - Fail("ERROR: conversion from relative path \" %s \" to absolute path failed. _fullpath returned NULL\n",argv[0]); + Fail("ERROR: conversion from relative path \" %s \" to absolute path failed. realpath returned NULL\n",argv[0]); } /* Call Load library with the short name of @@ -101,11 +100,11 @@ PALTEST(loader_LoadLibraryA_test6_paltest_loadlibrarya_test6, "loader/LoadLibrar hShortLib = LoadLibrary(LibraryName); if(hShortLib == NULL) { - Fail("ERROR:%u:Unable to load library %s\n", - GetLastError(), + Fail("ERROR:%u:Unable to load library %s\n", + GetLastError(), LibraryName); } - + /* Test the loaded library. */ if (!TestDll(hShortLib)) @@ -120,8 +119,8 @@ PALTEST(loader_LoadLibraryA_test6_paltest_loadlibrarya_test6, "loader/LoadLibrar hFullLib = LoadLibrary(fullPath); if(hFullLib == NULL) { - Trace("ERROR:%u:Unable to load library %s\n", - GetLastError(), + Trace("ERROR:%u:Unable to load library %s\n", + GetLastError(), fullPath); iRetVal = FAIL; goto cleanUpTwo; @@ -141,11 +140,11 @@ PALTEST(loader_LoadLibraryA_test6_paltest_loadlibrarya_test6, "loader/LoadLibrar cleanUpTwo: - /* Call the FreeLibrary API. - */ + /* Call the FreeLibrary API. + */ if (!FreeLibrary(hFullLib)) { - Trace("ERROR:%u: Unable to free library \"%s\"\n", + Trace("ERROR:%u: Unable to free library \"%s\"\n", GetLastError(), fullPath); iRetVal = FAIL; @@ -153,11 +152,11 @@ PALTEST(loader_LoadLibraryA_test6_paltest_loadlibrarya_test6, "loader/LoadLibrar cleanUpOne: - /* Call the FreeLibrary API. - */ + /* Call the FreeLibrary API. + */ if (!FreeLibrary(hShortLib)) { - Trace("ERROR:%u: Unable to free library \"%s\"\n", + Trace("ERROR:%u: Unable to free library \"%s\"\n", GetLastError(), LibraryName); iRetVal = FAIL; @@ -167,5 +166,4 @@ PALTEST(loader_LoadLibraryA_test6_paltest_loadlibrarya_test6, "loader/LoadLibrar */ PAL_TerminateEx(iRetVal); return iRetVal; - } diff --git a/src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test8/loadlibrarya.cpp b/src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test8/loadlibrarya.cpp index b489ef27f965e..1bbf9a6d08ad1 100644 --- a/src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test8/loadlibrarya.cpp +++ b/src/coreclr/pal/tests/palsuite/loader/LoadLibraryA/test8/loadlibrarya.cpp @@ -7,9 +7,9 @@ ** ** Purpose: Positive test the LoadLibrary API. Test will verify ** that it is unable to load the library twice. Once by -** using the full path name and secondly by using the +** using the full path name and secondly by using the ** short name. -** +** ** **============================================================*/ @@ -25,14 +25,13 @@ typedef int (*dllfunct)(); #define GETATTACHCOUNTNAME "_GetAttachCount@0" #endif - /* Helper function to test the loaded library. */ BOOL PALAPI TestDll(HMODULE hLib) { int RetVal; char FunctName[] = GETATTACHCOUNTNAME; - FARPROC DllFunc; + FARPROC DllFunc; /* Access a function from the loaded library. */ @@ -45,7 +44,7 @@ BOOL PALAPI TestDll(HMODULE hLib) return (FALSE); } - /* Verify that the DLL_PROCESS_ATTACH is only + /* Verify that the DLL_PROCESS_ATTACH is only * accessed once.*/ RetVal = DllFunc(); if (RetVal != 1) @@ -72,7 +71,7 @@ PALTEST(loader_LoadLibraryA_test8_paltest_loadlibrarya_test8, "loader/LoadLibrar char relTestDir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; - + BOOL bRc = FALSE; char relLibPath[_MAX_DIR]; @@ -89,15 +88,15 @@ PALTEST(loader_LoadLibraryA_test8_paltest_loadlibrarya_test8, "loader/LoadLibrar /* Get the full path to the library (DLL). */ - - if (NULL != _fullpath(fullPath,argv[0],_MAX_DIR)) { - + + if (NULL != realpath(argv[0],fullpath)) { + _splitpath(fullPath,drive,dir,fname,ext); _makepath(fullPath,drive,dir,LibraryName,""); - - + + } else { - Fail("ERROR: conversion from relative path \" %s \" to absolute path failed. _fullpath returned NULL\n",argv[0]); + Fail("ERROR: conversion from relative path \" %s \" to absolute path failed. realpath returned NULL\n",argv[0]); } /* Get relative path to the library @@ -112,11 +111,11 @@ PALTEST(loader_LoadLibraryA_test8_paltest_loadlibrarya_test8, "loader/LoadLibrar hShortLib = LoadLibrary(LibraryName); if(hShortLib == NULL) { - Fail("ERROR:%u:Short:Unable to load library %s\n", - GetLastError(), + Fail("ERROR:%u:Short:Unable to load library %s\n", + GetLastError(), LibraryName); } - + /* Test the loaded library. */ if (!TestDll(hShortLib)) @@ -131,8 +130,8 @@ PALTEST(loader_LoadLibraryA_test8_paltest_loadlibrarya_test8, "loader/LoadLibrar hFullLib = LoadLibrary(fullPath); if(hFullLib == NULL) { - Trace("ERROR:%u:Full:Unable to load library %s\n", - GetLastError(), + Trace("ERROR:%u:Full:Unable to load library %s\n", + GetLastError(), fullPath); iRetVal = FAIL; goto cleanUpTwo; @@ -148,14 +147,14 @@ PALTEST(loader_LoadLibraryA_test8_paltest_loadlibrarya_test8, "loader/LoadLibrar /* ** Call the load library with the relative path - ** wrt to the directory ./testloadlibrary/.. + ** wrt to the directory ./testloadlibrary/.. ** since we don't want to make any assumptions ** regarding the type of build */ hRelLib = LoadLibrary(relLibPath); if(hRelLib == NULL) { - Trace("ERROR:%u:Rel:Unable to load library at %s\n", + Trace("ERROR:%u:Rel:Unable to load library at %s\n", GetLastError(), relLibPath); iRetVal = FAIL; goto cleanUpTwo; @@ -190,12 +189,12 @@ PALTEST(loader_LoadLibraryA_test8_paltest_loadlibrarya_test8, "loader/LoadLibrar cleanUpThree: - /* Call the FreeLibrary API. - */ + /* Call the FreeLibrary API. + */ if (!FreeLibrary(hRelLib)) { - Trace("ERROR:%u: Unable to free library \"%s\"\n", + Trace("ERROR:%u: Unable to free library \"%s\"\n", GetLastError(), relLibPath); iRetVal = FAIL; @@ -203,11 +202,11 @@ PALTEST(loader_LoadLibraryA_test8_paltest_loadlibrarya_test8, "loader/LoadLibrar cleanUpTwo: - /* Call the FreeLibrary API. - */ + /* Call the FreeLibrary API. + */ if (!FreeLibrary(hFullLib)) { - Trace("ERROR:%u: Unable to free library \"%s\"\n", + Trace("ERROR:%u: Unable to free library \"%s\"\n", GetLastError(), fullPath); iRetVal = FAIL; @@ -215,20 +214,18 @@ PALTEST(loader_LoadLibraryA_test8_paltest_loadlibrarya_test8, "loader/LoadLibrar cleanUpOne: - /* Call the FreeLibrary API. - */ + /* Call the FreeLibrary API. + */ if (!FreeLibrary(hShortLib)) { - Trace("ERROR:%u: Unable to free library \"%s\"\n", + Trace("ERROR:%u: Unable to free library \"%s\"\n", GetLastError(), LibraryName); iRetVal = FAIL; } - /* Terminate the PAL. */ PAL_TerminateEx(iRetVal); return iRetVal; - } diff --git a/src/coreclr/pal/tests/palsuite/miscellaneous/FormatMessageW/test6/test.cpp b/src/coreclr/pal/tests/palsuite/miscellaneous/FormatMessageW/test6/test.cpp index b16b0ea27754e..15d94411bb030 100644 --- a/src/coreclr/pal/tests/palsuite/miscellaneous/FormatMessageW/test6/test.cpp +++ b/src/coreclr/pal/tests/palsuite/miscellaneous/FormatMessageW/test6/test.cpp @@ -36,9 +36,9 @@ PALTEST(miscellaneous_FormatMessageW_test6_paltest_formatmessagew_test6, "miscel the error message it extracts is correct, only that it does place some information into the buffer when it is called. */ - + /* - + ERROR_SUCCESS (0L) is normally returned by GetLastError, But, the ERROR_SUCCESS is removed from messages for Unix based Systems To ensure that we have some information into the buffer we are using the message @@ -54,25 +54,25 @@ PALTEST(miscellaneous_FormatMessageW_test6_paltest_formatmessagew_test6, "miscel 0, /* maximum size of message buffer */ NULL /* array of message inserts */ ); - - if(ReturnResult == 0) + + if(ReturnResult == 0) { Fail("ERROR: The return value was 0, which indicates failure. The " "function failed when trying to Format a FROM_SYSTEM message."); } - - if(wcslen(OutBuffer) <= 0) + + if(wcslen(OutBuffer) <= 0) { Fail("ERROR: There are no characters in the buffer, and when the " "FORMAT_MESSAGE_FROM_SYSTEM flag is used with ERROR_FILE_NOT_FOUND error, " "something should be put into the buffer."); } - - LocalFree(OutBuffer); - + + free(OutBuffer); + PAL_Terminate(); return PASS; - + } diff --git a/src/coreclr/pal/tests/palsuite/paltestlist.txt b/src/coreclr/pal/tests/palsuite/paltestlist.txt index 2b9ac7ccd4eb1..2afdf101d5b68 100644 --- a/src/coreclr/pal/tests/palsuite/paltestlist.txt +++ b/src/coreclr/pal/tests/palsuite/paltestlist.txt @@ -333,7 +333,6 @@ c_runtime/wcsrchr/test1/paltest_wcsrchr_test1 c_runtime/wcsstr/test1/paltest_wcsstr_test1 c_runtime/wcstod/test1/paltest_wcstod_test1 c_runtime/wcstod/test2/paltest_wcstod_test2 -c_runtime/wcstok/test1/paltest_wcstok_test1 c_runtime/wcstoul/test1/paltest_wcstoul_test1 c_runtime/wcstoul/test2/paltest_wcstoul_test2 c_runtime/wcstoul/test3/paltest_wcstoul_test3 @@ -449,9 +448,6 @@ filemapping_memmgt/CreateFileMappingW/test9/paltest_createfilemappingw_test9 filemapping_memmgt/FreeLibrary/test2/paltest_freelibrary_test2 filemapping_memmgt/GetModuleFileNameA/test2/paltest_getmodulefilenamea_test2 filemapping_memmgt/GetModuleFileNameW/test2/paltest_getmodulefilenamew_test2 -filemapping_memmgt/LocalAlloc/test1/paltest_localalloc_test1 -filemapping_memmgt/LocalFree/test1/paltest_localfree_test1 -filemapping_memmgt/LocalFree/test2/paltest_localfree_test2 filemapping_memmgt/MapViewOfFile/test1/paltest_mapviewoffile_test1 filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2 filemapping_memmgt/MapViewOfFile/test3/paltest_mapviewoffile_test3 diff --git a/src/coreclr/pal/tests/palsuite/runpaltests.sh b/src/coreclr/pal/tests/palsuite/runpaltests.sh index e38f2aaa18840..c10930e2acc39 100755 --- a/src/coreclr/pal/tests/palsuite/runpaltests.sh +++ b/src/coreclr/pal/tests/palsuite/runpaltests.sh @@ -19,26 +19,18 @@ echo "***** Testing PAL *****" echo # Store the location of the root of build directory -BUILD_ROOT_DIR=$1 -if [ -d "$(pwd)/$BUILD_ROOT_DIR" ]; then - BUILD_ROOT_DIR="$(pwd)/$BUILD_ROOT_DIR" +if [ ! -e "$1" ]; then + echo "Core_Root not found at $1" + exit 1 fi +BUILD_ROOT_DIR="$(cd "$1"; pwd -P)" # Create path to the compiled PAL tets in the build directory PAL_TEST_BUILD=$BUILD_ROOT_DIR echo Running PAL tests from $PAL_TEST_BUILD -pushd $BUILD_ROOT_DIR - export LD_LIBRARY_PATH=$BUILD_ROOT_DIR:$LD_LIBRARY_PATH -# Create absolute path to the file that contains a list of PAL tests to execute. -# This file is located next to this script in the source tree -RELATIVE_PATH_TO_PAL_TESTS=$0 -# Remove the name of this script from the path -RELATIVE_PATH_TO_PAL_TESTS=${RELATIVE_PATH_TO_PAL_TESTS%/*.*} -# Change current directory to the location of this script -cd $RELATIVE_PATH_TO_PAL_TESTS # Environment variable PWD contains absolute path to the current folder # so use it to create absolute path to the file with a list of tests. PAL_TEST_LIST=$BUILD_ROOT_DIR/paltestlist.txt @@ -79,8 +71,6 @@ then fi fi -cd $PAL_TEST_OUTPUT_DIR - echo PAL tests will store their temporary files and output in $PAL_TEST_OUTPUT_DIR. if [ "$COPY_TO_TEST_OUTPUT_DIR" != "$PAL_TEST_OUTPUT_DIR" ]; then echo Output files will be copied to $COPY_TO_TEST_OUTPUT_DIR at the end. @@ -115,7 +105,6 @@ else COPY_TO_TEST_OUTPUT_DIR=$PAL_TEST_OUTPUT_DIR fi fi -cd $PAL_TEST_OUTPUT_DIR echo echo "Running tests..." @@ -133,7 +122,7 @@ do # Create a folder with the test name, and use that as the working directory for the test. Many PAL tests don't clean up after # themselves and may leave files/directories around, but even to handle test failures that result in a dirty state, run each # test in its own folder. - TEST_WORKING_DIR=$(basename $TEST_NAME) + TEST_WORKING_DIR=$PAL_TEST_OUTPUT_DIR/$(basename $TEST_NAME) if [ -e $TEST_WORKING_DIR ]; then rm -f -r $TEST_WORKING_DIR fi @@ -233,8 +222,6 @@ if [ "$COPY_TO_TEST_OUTPUT_DIR" != "$PAL_TEST_OUTPUT_DIR" ]; then echo Copied PAL test output files to $COPY_TO_TEST_OUTPUT_DIR. fi -popd - # Set exit code to be equal to the number PAL tests that have failed. # Exit code 0 indicates success. exit $NUMBER_OF_FAILED_TESTS diff --git a/src/coreclr/runtime-prereqs.proj b/src/coreclr/runtime-prereqs.proj index 1127c3df8bdf3..36ed2ce497be1 100644 --- a/src/coreclr/runtime-prereqs.proj +++ b/src/coreclr/runtime-prereqs.proj @@ -7,7 +7,7 @@ - + diff --git a/src/coreclr/scripts/jitutil.py b/src/coreclr/scripts/jitutil.py index c7906124b45d4..9552869dffa97 100644 --- a/src/coreclr/scripts/jitutil.py +++ b/src/coreclr/scripts/jitutil.py @@ -119,15 +119,15 @@ def run_command(command_to_run, _cwd=None, _exit_on_fail=False, _output_file=Non if proc.poll() is not None: break if output: - output_str = output.strip().decode("utf-8") + output_str = output.strip().decode("utf-8", errors='replace') print(output_str) of.write(output_str + "\n") else: command_stdout, command_stderr = proc.communicate() if len(command_stdout) > 0: - print(command_stdout.decode("utf-8")) + print(command_stdout.decode("utf-8", errors='replace')) if len(command_stderr) > 0: - print(command_stderr.decode("utf-8")) + print(command_stderr.decode("utf-8", errors='replace')) return_code = proc.returncode if _exit_on_fail and return_code != 0: diff --git a/src/coreclr/scripts/superpmi.md b/src/coreclr/scripts/superpmi.md index d9404dc32d740..36e24711637ae 100644 --- a/src/coreclr/scripts/superpmi.md +++ b/src/coreclr/scripts/superpmi.md @@ -1,7 +1,7 @@ # Documentation for the superpmi.py tool SuperPMI is a tool for developing and testing the JIT compiler. -General information on SuperPMI can be found [here](../ToolBox/superpmi/readme.md). +General information on SuperPMI can be found [here](../tools/superpmi/readme.md). ## Overview diff --git a/src/coreclr/scripts/superpmi_benchmarks.py b/src/coreclr/scripts/superpmi_benchmarks.py index 1c15b9ae803bf..a72747e77ee6a 100644 --- a/src/coreclr/scripts/superpmi_benchmarks.py +++ b/src/coreclr/scripts/superpmi_benchmarks.py @@ -17,7 +17,7 @@ import stat from os import path -from os.path import isfile +from os.path import isfile, realpath from shutil import copyfile from coreclr_arguments import * from jitutil import run_command, ChangeDir, TempDir @@ -136,6 +136,9 @@ def build_and_run(coreclr_args, output_mch_name): project_file = path.join(performance_directory, "src", "benchmarks", "micro", "MicroBenchmarks.csproj") benchmarks_dll = path.join(artifacts_directory, "MicroBenchmarks.dll") + # Workaround https://github.com/dotnet/sdk/issues/23430 + project_file = realpath(project_file) + if is_windows: shim_name = "%JitName%" corerun_exe = "CoreRun.exe" diff --git a/src/coreclr/scripts/superpmi_collect_setup.py b/src/coreclr/scripts/superpmi_collect_setup.py index ce102ea091026..9eedadb57e3cf 100644 --- a/src/coreclr/scripts/superpmi_collect_setup.py +++ b/src/coreclr/scripts/superpmi_collect_setup.py @@ -22,12 +22,12 @@ # 4. Lastly, it sets the pipeline variables. # # Below are the helix queues it sets depending on the OS/architecture: -# | Arch | windows | Linux | -# |-------|-------------------------|--------------------------------------------------------------------------------------------------------------------------------------| -# | x86 | Windows.10.Amd64.X86.Rt | | -# | x64 | Windows.10.Amd64.X86.Rt | Ubuntu.1804.Amd64 | -# | arm | - | (Ubuntu.1804.Arm32)Ubuntu.1804.Armarch@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-18.04-helix-arm32v7-bfcd90a-20200121150440 | -# | arm64 | Windows.10.Arm64 | (Ubuntu.1804.Arm64)Ubuntu.1804.ArmArch@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-18.04-helix-arm64v8-20210531091519-97d8652 | +# | Arch | windows | Linux | macOS | +# |-------|-------------------------|--------------------------------------------------------------------------------------------------------------------------------------|----------------| +# | x86 | Windows.10.Amd64.X86.Rt | | - | +# | x64 | Windows.10.Amd64.X86.Rt | Ubuntu.1804.Amd64 | OSX.1014.Amd64 | +# | arm | - | (Ubuntu.1804.Arm32)Ubuntu.1804.Armarch@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-18.04-helix-arm32v7-bfcd90a-20200121150440 | - | +# | arm64 | Windows.10.Arm64 | (Ubuntu.1804.Arm64)Ubuntu.1804.ArmArch@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-18.04-helix-arm64v8-20210531091519-97d8652 | OSX.1100.ARM64 | # ################################################################################ ################################################################################ @@ -47,6 +47,7 @@ parser.add_argument("-source_directory", help="path to source directory") parser.add_argument("-core_root_directory", help="path to core_root directory") parser.add_argument("-arch", help="Architecture") +parser.add_argument("-platform", help="OS platform") parser.add_argument("-mch_file_tag", help="Tag to be used to mch files") parser.add_argument("-collection_name", help="Name of the SPMI collection to be done (e.g., libraries, tests)") parser.add_argument("-collection_type", help="Type of the SPMI collection to be done (crossgen, crossgen2, pmi)") @@ -196,6 +197,11 @@ def setup_args(args): lambda unused: True, "Unable to set arch") + coreclr_args.verify(args, + "platform", + lambda unused: True, + "Unable to set platform") + coreclr_args.verify(args, "mch_file_tag", lambda unused: True, @@ -383,28 +389,33 @@ def main(main_args): superpmi_src_directory = os.path.join(source_directory, 'src', 'coreclr', 'scripts') superpmi_dst_directory = os.path.join(correlation_payload_directory, "superpmi") arch = coreclr_args.arch + platform_name = coreclr_args.platform.lower() helix_source_prefix = "official" creator = "" ci = True - if is_windows: + if platform_name == "windows": helix_queue = "Windows.10.Arm64" if arch == "arm64" else "Windows.10.Amd64.X86.Rt" - else: + elif platform_name == "linux": if arch == "arm": helix_queue = "(Ubuntu.1804.Arm32)Ubuntu.1804.Armarch@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-18.04-helix-arm32v7-bfcd90a-20200121150440" elif arch == "arm64": helix_queue = "(Ubuntu.1804.Arm64)Ubuntu.1804.ArmArch@mcr.microsoft.com/dotnet-buildtools/prereqs:ubuntu-18.04-helix-arm64v8-20210531091519-97d8652" else: helix_queue = "Ubuntu.1804.Amd64" + elif platform_name == "osx": + helix_queue = "OSX.1100.ARM64" if arch == "arm64" else "OSX.1014.Amd64" # create superpmi directory print('Copying {} -> {}'.format(superpmi_src_directory, superpmi_dst_directory)) copy_directory(superpmi_src_directory, superpmi_dst_directory, verbose_output=True, match_func=lambda path: any(path.endswith(extension) for extension in [".py"])) - if is_windows: + if platform_name == "windows": acceptable_copy = lambda path: any(path.endswith(extension) for extension in [".py", ".dll", ".exe", ".json"]) else: + acceptable_extensions = [".py", ".dll", ".json"] + acceptable_extensions.append(".so" if platform_name == "linux" else ".dylib") # Need to accept files without any extension, which is how executable file's names look. - acceptable_copy = lambda path: (os.path.basename(path).find(".") == -1) or any(path.endswith(extension) for extension in [".py", ".dll", ".so", ".json"]) + acceptable_copy = lambda path: (os.path.basename(path).find(".") == -1) or any(path.endswith(extension) for extension in acceptable_extensions) print('Copying {} -> {}'.format(coreclr_args.core_root_directory, superpmi_dst_directory)) copy_directory(coreclr_args.core_root_directory, superpmi_dst_directory, verbose_output=True, match_func=acceptable_copy) diff --git a/src/coreclr/tools/CMakeLists.txt b/src/coreclr/tools/CMakeLists.txt index a50b1e6a1afbd..db59797e26f78 100644 --- a/src/coreclr/tools/CMakeLists.txt +++ b/src/coreclr/tools/CMakeLists.txt @@ -1,3 +1,6 @@ +add_subdirectory(SOS) +add_subdirectory(superpmi) + if (CLR_CMAKE_TARGET_WIN32 AND NOT CLR_CMAKE_CROSS_ARCH) add_subdirectory(GenClrDebugResource) add_subdirectory(InjectResource) diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/ReaderGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/ReaderGen.cs index d068f7d047704..55b09b37b3431 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/ReaderGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/Generator/ReaderGen.cs @@ -20,6 +20,7 @@ public void EmitSource() WriteLine("#pragma warning disable 649"); WriteLine("#pragma warning disable 169"); WriteLine("#pragma warning disable 282 // There is no defined ordering between fields in multiple declarations of partial class or struct"); + WriteLine("#pragma warning disable IDE0059"); WriteLine(); WriteLine("using System;"); diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs index 523fc0d172d52..1d92be5677148 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs @@ -6,6 +6,7 @@ #pragma warning disable 649 #pragma warning disable 169 #pragma warning disable 282 // There is no defined ordering between fields in multiple declarations of partial class or struct +#pragma warning disable IDE0059 using System; using System.Reflection; diff --git a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs index 6063683a7d62e..845dc7c95a478 100644 --- a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs +++ b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs @@ -543,7 +543,7 @@ public NativeParser GetNext() { while (_parser.Offset < _endOffset) { - byte lowHashcode = _parser.GetUInt8(); + _parser.GetUInt8(); return _parser.GetParserFromRelativeOffset(); } diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoBase.cs b/src/coreclr/tools/Common/JitInterface/CorInfoBase.cs index f660b55ebe192..006409bdbb533 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoBase.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoBase.cs @@ -2200,20 +2200,6 @@ static uint _getFieldThreadLocalStoreID(IntPtr thisHandle, IntPtr* ppException, } } - [UnmanagedCallersOnly] - static void _setOverride(IntPtr thisHandle, IntPtr* ppException, IntPtr pOverride, CORINFO_METHOD_STRUCT_* currentMethod) - { - var _this = GetThis(thisHandle); - try - { - _this.setOverride(pOverride, currentMethod); - } - catch (Exception ex) - { - *ppException = _this.AllocException(ex); - } - } - [UnmanagedCallersOnly] static void _addActiveDependency(IntPtr thisHandle, IntPtr* ppException, CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MODULE_STRUCT_* moduleTo) { @@ -2566,7 +2552,7 @@ static byte _doesFieldBelongToClass(IntPtr thisHandle, IntPtr* ppException, CORI static IntPtr GetUnmanagedCallbacks() { - void** callbacks = (void**)Marshal.AllocCoTaskMem(sizeof(IntPtr) * 173); + void** callbacks = (void**)Marshal.AllocCoTaskMem(sizeof(IntPtr) * 172); callbacks[0] = (delegate* unmanaged)&_isIntrinsic; callbacks[1] = (delegate* unmanaged)&_getMethodAttribs; @@ -2716,31 +2702,30 @@ static IntPtr GetUnmanagedCallbacks() callbacks[145] = (delegate* unmanaged)&_constructStringLiteral; callbacks[146] = (delegate* unmanaged)&_emptyStringLiteral; callbacks[147] = (delegate* unmanaged)&_getFieldThreadLocalStoreID; - callbacks[148] = (delegate* unmanaged)&_setOverride; - callbacks[149] = (delegate* unmanaged)&_addActiveDependency; - callbacks[150] = (delegate* unmanaged)&_GetDelegateCtor; - callbacks[151] = (delegate* unmanaged)&_MethodCompileComplete; - callbacks[152] = (delegate* unmanaged)&_getTailCallHelpers; - callbacks[153] = (delegate* unmanaged)&_convertPInvokeCalliToCall; - callbacks[154] = (delegate* unmanaged)&_notifyInstructionSetUsage; - callbacks[155] = (delegate* unmanaged)&_updateEntryPointForTailCall; - callbacks[156] = (delegate* unmanaged)&_allocMem; - callbacks[157] = (delegate* unmanaged)&_reserveUnwindInfo; - callbacks[158] = (delegate* unmanaged)&_allocUnwindInfo; - callbacks[159] = (delegate* unmanaged)&_allocGCInfo; - callbacks[160] = (delegate* unmanaged)&_setEHcount; - callbacks[161] = (delegate* unmanaged)&_setEHinfo; - callbacks[162] = (delegate* unmanaged)&_logMsg; - callbacks[163] = (delegate* unmanaged)&_doAssert; - callbacks[164] = (delegate* unmanaged)&_reportFatalError; - callbacks[165] = (delegate* unmanaged)&_getPgoInstrumentationResults; - callbacks[166] = (delegate* unmanaged)&_allocPgoInstrumentationBySchema; - callbacks[167] = (delegate* unmanaged)&_recordCallSite; - callbacks[168] = (delegate* unmanaged)&_recordRelocation; - callbacks[169] = (delegate* unmanaged)&_getRelocTypeHint; - callbacks[170] = (delegate* unmanaged)&_getExpectedTargetArchitecture; - callbacks[171] = (delegate* unmanaged)&_getJitFlags; - callbacks[172] = (delegate* unmanaged)&_doesFieldBelongToClass; + callbacks[148] = (delegate* unmanaged)&_addActiveDependency; + callbacks[149] = (delegate* unmanaged)&_GetDelegateCtor; + callbacks[150] = (delegate* unmanaged)&_MethodCompileComplete; + callbacks[151] = (delegate* unmanaged)&_getTailCallHelpers; + callbacks[152] = (delegate* unmanaged)&_convertPInvokeCalliToCall; + callbacks[153] = (delegate* unmanaged)&_notifyInstructionSetUsage; + callbacks[154] = (delegate* unmanaged)&_updateEntryPointForTailCall; + callbacks[155] = (delegate* unmanaged)&_allocMem; + callbacks[156] = (delegate* unmanaged)&_reserveUnwindInfo; + callbacks[157] = (delegate* unmanaged)&_allocUnwindInfo; + callbacks[158] = (delegate* unmanaged)&_allocGCInfo; + callbacks[159] = (delegate* unmanaged)&_setEHcount; + callbacks[160] = (delegate* unmanaged)&_setEHinfo; + callbacks[161] = (delegate* unmanaged)&_logMsg; + callbacks[162] = (delegate* unmanaged)&_doAssert; + callbacks[163] = (delegate* unmanaged)&_reportFatalError; + callbacks[164] = (delegate* unmanaged)&_getPgoInstrumentationResults; + callbacks[165] = (delegate* unmanaged)&_allocPgoInstrumentationBySchema; + callbacks[166] = (delegate* unmanaged)&_recordCallSite; + callbacks[167] = (delegate* unmanaged)&_recordRelocation; + callbacks[168] = (delegate* unmanaged)&_getRelocTypeHint; + callbacks[169] = (delegate* unmanaged)&_getExpectedTargetArchitecture; + callbacks[170] = (delegate* unmanaged)&_getJitFlags; + callbacks[171] = (delegate* unmanaged)&_doesFieldBelongToClass; return (IntPtr)callbacks; } diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index f800dadf43159..30189ccc4cb52 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -3283,8 +3283,6 @@ private InfoAccessType emptyStringLiteral(ref void* ppValue) private uint getFieldThreadLocalStoreID(CORINFO_FIELD_STRUCT_* field, ref void* ppIndirection) { throw new NotImplementedException("getFieldThreadLocalStoreID"); } - private void setOverride(IntPtr pOverride, CORINFO_METHOD_STRUCT_* currentMethod) - { throw new NotImplementedException("setOverride"); } private void addActiveDependency(CORINFO_MODULE_STRUCT_* moduleFrom, CORINFO_MODULE_STRUCT_* moduleTo) { throw new NotImplementedException("addActiveDependency"); } private CORINFO_METHOD_STRUCT_* GetDelegateCtor(CORINFO_METHOD_STRUCT_* methHnd, CORINFO_CLASS_STRUCT_* clsHnd, CORINFO_METHOD_STRUCT_* targetMethodHnd, ref DelegateCtorArgs pCtorData) diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoInstructionSet.cs b/src/coreclr/tools/Common/JitInterface/CorInfoInstructionSet.cs index f1ffa0a0cd4eb..a7b188e037408 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoInstructionSet.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoInstructionSet.cs @@ -8,6 +8,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using System.Runtime.InteropServices; using Internal.TypeSystem; @@ -17,105 +18,220 @@ public enum InstructionSet { ILLEGAL = 0, NONE = 63, - ARM64_ArmBase=1, - ARM64_AdvSimd=2, - ARM64_Aes=3, - ARM64_Crc32=4, - ARM64_Dp=5, - ARM64_Rdm=6, - ARM64_Sha1=7, - ARM64_Sha256=8, - ARM64_Atomics=9, - ARM64_Vector64=10, - ARM64_Vector128=11, - ARM64_Dczva=12, - ARM64_ArmBase_Arm64=13, - ARM64_AdvSimd_Arm64=14, - ARM64_Aes_Arm64=15, - ARM64_Crc32_Arm64=16, - ARM64_Dp_Arm64=17, - ARM64_Rdm_Arm64=18, - ARM64_Sha1_Arm64=19, - ARM64_Sha256_Arm64=20, - X64_X86Base=1, - X64_SSE=2, - X64_SSE2=3, - X64_SSE3=4, - X64_SSSE3=5, - X64_SSE41=6, - X64_SSE42=7, - X64_AVX=8, - X64_AVX2=9, - X64_AES=10, - X64_BMI1=11, - X64_BMI2=12, - X64_FMA=13, - X64_LZCNT=14, - X64_PCLMULQDQ=15, - X64_POPCNT=16, - X64_Vector128=17, - X64_Vector256=18, - X64_AVXVNNI=19, - X64_X86Base_X64=20, - X64_SSE_X64=21, - X64_SSE2_X64=22, - X64_SSE3_X64=23, - X64_SSSE3_X64=24, - X64_SSE41_X64=25, - X64_SSE42_X64=26, - X64_AVX_X64=27, - X64_AVX2_X64=28, - X64_AES_X64=29, - X64_BMI1_X64=30, - X64_BMI2_X64=31, - X64_FMA_X64=32, - X64_LZCNT_X64=33, - X64_PCLMULQDQ_X64=34, - X64_POPCNT_X64=35, - X64_AVXVNNI_X64=36, - X86_X86Base=1, - X86_SSE=2, - X86_SSE2=3, - X86_SSE3=4, - X86_SSSE3=5, - X86_SSE41=6, - X86_SSE42=7, - X86_AVX=8, - X86_AVX2=9, - X86_AES=10, - X86_BMI1=11, - X86_BMI2=12, - X86_FMA=13, - X86_LZCNT=14, - X86_PCLMULQDQ=15, - X86_POPCNT=16, - X86_Vector128=17, - X86_Vector256=18, - X86_AVXVNNI=19, - X86_X86Base_X64=20, - X86_SSE_X64=21, - X86_SSE2_X64=22, - X86_SSE3_X64=23, - X86_SSSE3_X64=24, - X86_SSE41_X64=25, - X86_SSE42_X64=26, - X86_AVX_X64=27, - X86_AVX2_X64=28, - X86_AES_X64=29, - X86_BMI1_X64=30, - X86_BMI2_X64=31, - X86_FMA_X64=32, - X86_LZCNT_X64=33, - X86_PCLMULQDQ_X64=34, - X86_POPCNT_X64=35, - X86_AVXVNNI_X64=36, + ARM64_ArmBase = InstructionSet_ARM64.ArmBase, + ARM64_AdvSimd = InstructionSet_ARM64.AdvSimd, + ARM64_Aes = InstructionSet_ARM64.Aes, + ARM64_Crc32 = InstructionSet_ARM64.Crc32, + ARM64_Dp = InstructionSet_ARM64.Dp, + ARM64_Rdm = InstructionSet_ARM64.Rdm, + ARM64_Sha1 = InstructionSet_ARM64.Sha1, + ARM64_Sha256 = InstructionSet_ARM64.Sha256, + ARM64_Atomics = InstructionSet_ARM64.Atomics, + ARM64_Vector64 = InstructionSet_ARM64.Vector64, + ARM64_Vector128 = InstructionSet_ARM64.Vector128, + ARM64_Dczva = InstructionSet_ARM64.Dczva, + ARM64_ArmBase_Arm64 = InstructionSet_ARM64.ArmBase_Arm64, + ARM64_AdvSimd_Arm64 = InstructionSet_ARM64.AdvSimd_Arm64, + ARM64_Aes_Arm64 = InstructionSet_ARM64.Aes_Arm64, + ARM64_Crc32_Arm64 = InstructionSet_ARM64.Crc32_Arm64, + ARM64_Dp_Arm64 = InstructionSet_ARM64.Dp_Arm64, + ARM64_Rdm_Arm64 = InstructionSet_ARM64.Rdm_Arm64, + ARM64_Sha1_Arm64 = InstructionSet_ARM64.Sha1_Arm64, + ARM64_Sha256_Arm64 = InstructionSet_ARM64.Sha256_Arm64, + X64_X86Base = InstructionSet_X64.X86Base, + X64_SSE = InstructionSet_X64.SSE, + X64_SSE2 = InstructionSet_X64.SSE2, + X64_SSE3 = InstructionSet_X64.SSE3, + X64_SSSE3 = InstructionSet_X64.SSSE3, + X64_SSE41 = InstructionSet_X64.SSE41, + X64_SSE42 = InstructionSet_X64.SSE42, + X64_AVX = InstructionSet_X64.AVX, + X64_AVX2 = InstructionSet_X64.AVX2, + X64_AES = InstructionSet_X64.AES, + X64_BMI1 = InstructionSet_X64.BMI1, + X64_BMI2 = InstructionSet_X64.BMI2, + X64_FMA = InstructionSet_X64.FMA, + X64_LZCNT = InstructionSet_X64.LZCNT, + X64_PCLMULQDQ = InstructionSet_X64.PCLMULQDQ, + X64_POPCNT = InstructionSet_X64.POPCNT, + X64_Vector128 = InstructionSet_X64.Vector128, + X64_Vector256 = InstructionSet_X64.Vector256, + X64_AVXVNNI = InstructionSet_X64.AVXVNNI, + X64_X86Base_X64 = InstructionSet_X64.X86Base_X64, + X64_SSE_X64 = InstructionSet_X64.SSE_X64, + X64_SSE2_X64 = InstructionSet_X64.SSE2_X64, + X64_SSE3_X64 = InstructionSet_X64.SSE3_X64, + X64_SSSE3_X64 = InstructionSet_X64.SSSE3_X64, + X64_SSE41_X64 = InstructionSet_X64.SSE41_X64, + X64_SSE42_X64 = InstructionSet_X64.SSE42_X64, + X64_AVX_X64 = InstructionSet_X64.AVX_X64, + X64_AVX2_X64 = InstructionSet_X64.AVX2_X64, + X64_AES_X64 = InstructionSet_X64.AES_X64, + X64_BMI1_X64 = InstructionSet_X64.BMI1_X64, + X64_BMI2_X64 = InstructionSet_X64.BMI2_X64, + X64_FMA_X64 = InstructionSet_X64.FMA_X64, + X64_LZCNT_X64 = InstructionSet_X64.LZCNT_X64, + X64_PCLMULQDQ_X64 = InstructionSet_X64.PCLMULQDQ_X64, + X64_POPCNT_X64 = InstructionSet_X64.POPCNT_X64, + X64_AVXVNNI_X64 = InstructionSet_X64.AVXVNNI_X64, + X86_X86Base = InstructionSet_X86.X86Base, + X86_SSE = InstructionSet_X86.SSE, + X86_SSE2 = InstructionSet_X86.SSE2, + X86_SSE3 = InstructionSet_X86.SSE3, + X86_SSSE3 = InstructionSet_X86.SSSE3, + X86_SSE41 = InstructionSet_X86.SSE41, + X86_SSE42 = InstructionSet_X86.SSE42, + X86_AVX = InstructionSet_X86.AVX, + X86_AVX2 = InstructionSet_X86.AVX2, + X86_AES = InstructionSet_X86.AES, + X86_BMI1 = InstructionSet_X86.BMI1, + X86_BMI2 = InstructionSet_X86.BMI2, + X86_FMA = InstructionSet_X86.FMA, + X86_LZCNT = InstructionSet_X86.LZCNT, + X86_PCLMULQDQ = InstructionSet_X86.PCLMULQDQ, + X86_POPCNT = InstructionSet_X86.POPCNT, + X86_Vector128 = InstructionSet_X86.Vector128, + X86_Vector256 = InstructionSet_X86.Vector256, + X86_AVXVNNI = InstructionSet_X86.AVXVNNI, + X86_X86Base_X64 = InstructionSet_X86.X86Base_X64, + X86_SSE_X64 = InstructionSet_X86.SSE_X64, + X86_SSE2_X64 = InstructionSet_X86.SSE2_X64, + X86_SSE3_X64 = InstructionSet_X86.SSE3_X64, + X86_SSSE3_X64 = InstructionSet_X86.SSSE3_X64, + X86_SSE41_X64 = InstructionSet_X86.SSE41_X64, + X86_SSE42_X64 = InstructionSet_X86.SSE42_X64, + X86_AVX_X64 = InstructionSet_X86.AVX_X64, + X86_AVX2_X64 = InstructionSet_X86.AVX2_X64, + X86_AES_X64 = InstructionSet_X86.AES_X64, + X86_BMI1_X64 = InstructionSet_X86.BMI1_X64, + X86_BMI2_X64 = InstructionSet_X86.BMI2_X64, + X86_FMA_X64 = InstructionSet_X86.FMA_X64, + X86_LZCNT_X64 = InstructionSet_X86.LZCNT_X64, + X86_PCLMULQDQ_X64 = InstructionSet_X86.PCLMULQDQ_X64, + X86_POPCNT_X64 = InstructionSet_X86.POPCNT_X64, + X86_AVXVNNI_X64 = InstructionSet_X86.AVXVNNI_X64, + } + + public enum InstructionSet_ARM64 + { + ILLEGAL = InstructionSet.ILLEGAL, + NONE = InstructionSet.NONE, + ArmBase = 1, + AdvSimd = 2, + Aes = 3, + Crc32 = 4, + Dp = 5, + Rdm = 6, + Sha1 = 7, + Sha256 = 8, + Atomics = 9, + Vector64 = 10, + Vector128 = 11, + Dczva = 12, + ArmBase_Arm64 = 13, + AdvSimd_Arm64 = 14, + Aes_Arm64 = 15, + Crc32_Arm64 = 16, + Dp_Arm64 = 17, + Rdm_Arm64 = 18, + Sha1_Arm64 = 19, + Sha256_Arm64 = 20, + } + + public enum InstructionSet_X64 + { + ILLEGAL = InstructionSet.ILLEGAL, + NONE = InstructionSet.NONE, + X86Base = 1, + SSE = 2, + SSE2 = 3, + SSE3 = 4, + SSSE3 = 5, + SSE41 = 6, + SSE42 = 7, + AVX = 8, + AVX2 = 9, + AES = 10, + BMI1 = 11, + BMI2 = 12, + FMA = 13, + LZCNT = 14, + PCLMULQDQ = 15, + POPCNT = 16, + Vector128 = 17, + Vector256 = 18, + AVXVNNI = 19, + X86Base_X64 = 20, + SSE_X64 = 21, + SSE2_X64 = 22, + SSE3_X64 = 23, + SSSE3_X64 = 24, + SSE41_X64 = 25, + SSE42_X64 = 26, + AVX_X64 = 27, + AVX2_X64 = 28, + AES_X64 = 29, + BMI1_X64 = 30, + BMI2_X64 = 31, + FMA_X64 = 32, + LZCNT_X64 = 33, + PCLMULQDQ_X64 = 34, + POPCNT_X64 = 35, + AVXVNNI_X64 = 36, + } + public enum InstructionSet_X86 + { + ILLEGAL = InstructionSet.ILLEGAL, + NONE = InstructionSet.NONE, + X86Base = 1, + SSE = 2, + SSE2 = 3, + SSE3 = 4, + SSSE3 = 5, + SSE41 = 6, + SSE42 = 7, + AVX = 8, + AVX2 = 9, + AES = 10, + BMI1 = 11, + BMI2 = 12, + FMA = 13, + LZCNT = 14, + PCLMULQDQ = 15, + POPCNT = 16, + Vector128 = 17, + Vector256 = 18, + AVXVNNI = 19, + X86Base_X64 = 20, + SSE_X64 = 21, + SSE2_X64 = 22, + SSE3_X64 = 23, + SSSE3_X64 = 24, + SSE41_X64 = 25, + SSE42_X64 = 26, + AVX_X64 = 27, + AVX2_X64 = 28, + AES_X64 = 29, + BMI1_X64 = 30, + BMI2_X64 = 31, + FMA_X64 = 32, + LZCNT_X64 = 33, + PCLMULQDQ_X64 = 34, + POPCNT_X64 = 35, + AVXVNNI_X64 = 36, } public struct InstructionSetFlags : IEnumerable { - ulong _flags; - + private ulong _flags; + + public IEnumerable ARM64Flags => this.Select((x) => (InstructionSet_ARM64)x); + + public IEnumerable X64Flags => this.Select((x) => (InstructionSet_X64)x); + + public IEnumerable X86Flags => this.Select((x) => (InstructionSet_X86)x); + public void AddInstructionSet(InstructionSet instructionSet) { _flags = _flags | (((ulong)1) << (int)instructionSet); @@ -235,6 +351,10 @@ public static InstructionSetFlags ExpandInstructionSetByImplicationHelper(Target resultflags.AddInstructionSet(InstructionSet.ARM64_ArmBase); if (resultflags.HasInstructionSet(InstructionSet.ARM64_Sha256)) resultflags.AddInstructionSet(InstructionSet.ARM64_ArmBase); + if (resultflags.HasInstructionSet(InstructionSet.ARM64_Vector64)) + resultflags.AddInstructionSet(InstructionSet.ARM64_AdvSimd); + if (resultflags.HasInstructionSet(InstructionSet.ARM64_Vector128)) + resultflags.AddInstructionSet(InstructionSet.ARM64_AdvSimd); break; case TargetArchitecture.X64: @@ -330,12 +450,18 @@ public static InstructionSetFlags ExpandInstructionSetByImplicationHelper(Target resultflags.AddInstructionSet(InstructionSet.X64_AVX); if (resultflags.HasInstructionSet(InstructionSet.X64_FMA)) resultflags.AddInstructionSet(InstructionSet.X64_AVX); + if (resultflags.HasInstructionSet(InstructionSet.X64_LZCNT)) + resultflags.AddInstructionSet(InstructionSet.X64_X86Base); if (resultflags.HasInstructionSet(InstructionSet.X64_PCLMULQDQ)) resultflags.AddInstructionSet(InstructionSet.X64_SSE2); if (resultflags.HasInstructionSet(InstructionSet.X64_POPCNT)) resultflags.AddInstructionSet(InstructionSet.X64_SSE42); + if (resultflags.HasInstructionSet(InstructionSet.X64_Vector128)) + resultflags.AddInstructionSet(InstructionSet.X64_SSE); if (resultflags.HasInstructionSet(InstructionSet.X64_Vector256)) resultflags.AddInstructionSet(InstructionSet.X64_AVX); + if (resultflags.HasInstructionSet(InstructionSet.X64_AVXVNNI)) + resultflags.AddInstructionSet(InstructionSet.X64_AVX2); break; case TargetArchitecture.X86: @@ -363,16 +489,22 @@ public static InstructionSetFlags ExpandInstructionSetByImplicationHelper(Target resultflags.AddInstructionSet(InstructionSet.X86_AVX); if (resultflags.HasInstructionSet(InstructionSet.X86_FMA)) resultflags.AddInstructionSet(InstructionSet.X86_AVX); + if (resultflags.HasInstructionSet(InstructionSet.X86_LZCNT)) + resultflags.AddInstructionSet(InstructionSet.X86_X86Base); if (resultflags.HasInstructionSet(InstructionSet.X86_PCLMULQDQ)) resultflags.AddInstructionSet(InstructionSet.X86_SSE2); if (resultflags.HasInstructionSet(InstructionSet.X86_POPCNT)) resultflags.AddInstructionSet(InstructionSet.X86_SSE42); + if (resultflags.HasInstructionSet(InstructionSet.X86_Vector128)) + resultflags.AddInstructionSet(InstructionSet.X86_SSE); if (resultflags.HasInstructionSet(InstructionSet.X86_Vector256)) resultflags.AddInstructionSet(InstructionSet.X86_AVX); + if (resultflags.HasInstructionSet(InstructionSet.X86_AVXVNNI)) + resultflags.AddInstructionSet(InstructionSet.X86_AVX2); break; - } } while (!oldflags.Equals(resultflags)); + return resultflags; } @@ -422,6 +554,10 @@ private static InstructionSetFlags ExpandInstructionSetByReverseImplicationHelpe resultflags.AddInstructionSet(InstructionSet.ARM64_Sha1); if (resultflags.HasInstructionSet(InstructionSet.ARM64_ArmBase)) resultflags.AddInstructionSet(InstructionSet.ARM64_Sha256); + if (resultflags.HasInstructionSet(InstructionSet.ARM64_AdvSimd)) + resultflags.AddInstructionSet(InstructionSet.ARM64_Vector64); + if (resultflags.HasInstructionSet(InstructionSet.ARM64_AdvSimd)) + resultflags.AddInstructionSet(InstructionSet.ARM64_Vector128); break; case TargetArchitecture.X64: @@ -483,12 +619,18 @@ private static InstructionSetFlags ExpandInstructionSetByReverseImplicationHelpe resultflags.AddInstructionSet(InstructionSet.X64_BMI2); if (resultflags.HasInstructionSet(InstructionSet.X64_AVX)) resultflags.AddInstructionSet(InstructionSet.X64_FMA); + if (resultflags.HasInstructionSet(InstructionSet.X64_X86Base)) + resultflags.AddInstructionSet(InstructionSet.X64_LZCNT); if (resultflags.HasInstructionSet(InstructionSet.X64_SSE2)) resultflags.AddInstructionSet(InstructionSet.X64_PCLMULQDQ); if (resultflags.HasInstructionSet(InstructionSet.X64_SSE42)) resultflags.AddInstructionSet(InstructionSet.X64_POPCNT); + if (resultflags.HasInstructionSet(InstructionSet.X64_SSE)) + resultflags.AddInstructionSet(InstructionSet.X64_Vector128); if (resultflags.HasInstructionSet(InstructionSet.X64_AVX)) resultflags.AddInstructionSet(InstructionSet.X64_Vector256); + if (resultflags.HasInstructionSet(InstructionSet.X64_AVX2)) + resultflags.AddInstructionSet(InstructionSet.X64_AVXVNNI); break; case TargetArchitecture.X86: @@ -516,16 +658,22 @@ private static InstructionSetFlags ExpandInstructionSetByReverseImplicationHelpe resultflags.AddInstructionSet(InstructionSet.X86_BMI2); if (resultflags.HasInstructionSet(InstructionSet.X86_AVX)) resultflags.AddInstructionSet(InstructionSet.X86_FMA); + if (resultflags.HasInstructionSet(InstructionSet.X86_X86Base)) + resultflags.AddInstructionSet(InstructionSet.X86_LZCNT); if (resultflags.HasInstructionSet(InstructionSet.X86_SSE2)) resultflags.AddInstructionSet(InstructionSet.X86_PCLMULQDQ); if (resultflags.HasInstructionSet(InstructionSet.X86_SSE42)) resultflags.AddInstructionSet(InstructionSet.X86_POPCNT); + if (resultflags.HasInstructionSet(InstructionSet.X86_SSE)) + resultflags.AddInstructionSet(InstructionSet.X86_Vector128); if (resultflags.HasInstructionSet(InstructionSet.X86_AVX)) resultflags.AddInstructionSet(InstructionSet.X86_Vector256); + if (resultflags.HasInstructionSet(InstructionSet.X86_AVX2)) + resultflags.AddInstructionSet(InstructionSet.X86_AVXVNNI); break; - } } while (!oldflags.Equals(resultflags)); + return resultflags; } @@ -608,7 +756,6 @@ public static IEnumerable ArchitectureToValidInstructionSets yield return new InstructionSetInfo("Vector256", "", InstructionSet.X86_Vector256, false); yield return new InstructionSetInfo("avxvnni", "AvxVnni", InstructionSet.X86_AVXVNNI, true); break; - } } @@ -675,7 +822,6 @@ public void Set64BitInstructionSetVariants(TargetArchitecture architecture) case TargetArchitecture.X86: break; - } } @@ -734,7 +880,6 @@ public void Set64BitInstructionSetVariantsUnconditionally(TargetArchitecture arc AddInstructionSet(InstructionSet.X86_POPCNT_X64); AddInstructionSet(InstructionSet.X86_AVXVNNI_X64); break; - } } } diff --git a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetDesc.txt b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetDesc.txt index 8bfdc9a9d86a7..02586289c003a 100644 --- a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetDesc.txt +++ b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetDesc.txt @@ -1,5 +1,5 @@ ; Define the set of instruction sets available on a platform -; Format is +; Format is ; ; Add new instruction set ; instructionset,,,,, , @@ -72,9 +72,12 @@ implication ,X86 ,AES ,SSE2 implication ,X86 ,BMI1 ,AVX implication ,X86 ,BMI2 ,AVX implication ,X86 ,FMA ,AVX +implication ,X86 ,LZCNT ,X86Base implication ,X86 ,PCLMULQDQ ,SSE2 implication ,X86 ,POPCNT ,SSE42 +implication ,X86 ,Vector128 ,SSE implication ,X86 ,Vector256 ,AVX +implication ,X86 ,AVXVNNI ,AVX2 ; Definition of X64 instruction sets definearch ,X64 ,64Bit ,X64 @@ -113,3 +116,5 @@ implication ,ARM64 ,Dp ,AdvSimd implication ,ARM64 ,Rdm ,AdvSimd implication ,ARM64 ,Sha1 ,ArmBase implication ,ARM64 ,Sha256 ,ArmBase +implication ,ARM64 ,Vector64 ,AdvSimd +implication ,ARM64 ,Vector128 ,AdvSimd diff --git a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetGenerator.cs b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetGenerator.cs index aeece5255661f..a9e7ee1086e39 100644 --- a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetGenerator.cs +++ b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetGenerator.cs @@ -355,6 +355,7 @@ public void WriteManagedJitInstructionSet(TextWriter tr) using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using System.Runtime.InteropServices; using Internal.TypeSystem; @@ -365,23 +366,51 @@ public enum InstructionSet ILLEGAL = 0, NONE = 63, "); + foreach (string architecture in _architectures) { - int counter = 1; foreach (var jitName in _architectureJitNames[architecture]) { - tr.WriteLine($" {architecture}_{jitName}={counter++},"); + tr.WriteLine($" {architecture}_{jitName} = InstructionSet_{architecture}.{jitName},"); } } - tr.Write(@" - } + tr.Write(@" } + +"); + + foreach (string architecture in _architectures) + { + tr.WriteLine($" public enum InstructionSet_{architecture}"); + tr.Write(@" { + ILLEGAL = InstructionSet.ILLEGAL, + NONE = InstructionSet.NONE, +"); - public struct InstructionSetFlags : IEnumerable + int counter = 1; + foreach (var jitName in _architectureJitNames[architecture]) + { + tr.WriteLine($" {jitName} = {counter++},"); + } + + tr.Write(@" } + +"); + } + + tr.Write(@" public struct InstructionSetFlags : IEnumerable { - ulong _flags; - - public void AddInstructionSet(InstructionSet instructionSet) + private ulong _flags; + +"); + + foreach (string architecture in _architectures) + { + tr.WriteLine($" public IEnumerable {architecture}Flags => this.Select((x) => (InstructionSet_{architecture})x);"); + tr.WriteLine(); + } + + tr.Write(@" public void AddInstructionSet(InstructionSet instructionSet) { _flags = _flags | (((ulong)1) << (int)instructionSet); } @@ -475,9 +504,9 @@ public static InstructionSetFlags ExpandInstructionSetByImplicationHelper(Target tr.WriteLine(" break;"); } - tr.Write(@" - } + tr.Write(@" } } while (!oldflags.Equals(resultflags)); + return resultflags; } @@ -515,9 +544,9 @@ private static InstructionSetFlags ExpandInstructionSetByReverseImplicationHelpe tr.WriteLine(" break;"); } - tr.Write(@" - } + tr.Write(@" } } while (!oldflags.Equals(resultflags)); + return resultflags; } @@ -559,8 +588,8 @@ public static IEnumerable ArchitectureToValidInstructionSets } tr.WriteLine(" break;"); } - tr.Write(@" - } + + tr.Write(@" } } public void Set64BitInstructionSetVariants(TargetArchitecture architecture) @@ -586,8 +615,7 @@ public void Set64BitInstructionSetVariants(TargetArchitecture architecture) tr.WriteLine(" break;"); } - tr.Write(@" - } + tr.Write(@" } } public void Set64BitInstructionSetVariantsUnconditionally(TargetArchitecture architecture) @@ -610,13 +638,13 @@ public void Set64BitInstructionSetVariantsUnconditionally(TargetArchitecture arc tr.WriteLine(" break;"); } - tr.Write(@" - } + tr.Write(@" } } } } "); return; + void AddReverseImplication(string architecture, string jitName, string impliedJitName) { AddImplication(architecture, impliedJitName, jitName); diff --git a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/ThunkInput.txt b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/ThunkInput.txt index dbe775e1e0246..92bc30aaf2570 100644 --- a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/ThunkInput.txt +++ b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/ThunkInput.txt @@ -301,7 +301,6 @@ FUNCTIONS InfoAccessType constructStringLiteral(CORINFO_MODULE_HANDLE module, mdToken metaTok, void **ppValue); InfoAccessType emptyStringLiteral(void **ppValue); uint32_t getFieldThreadLocalStoreID (CORINFO_FIELD_HANDLE field, void **ppIndirection); - void setOverride(ICorDynamicInfo *pOverride, CORINFO_METHOD_HANDLE currentMethod); void addActiveDependency(CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo); CORINFO_METHOD_HANDLE GetDelegateCtor(CORINFO_METHOD_HANDLE methHnd, CORINFO_CLASS_HANDLE clsHnd, CORINFO_METHOD_HANDLE targetMethodHnd, DelegateCtorArgs * pCtorData); void MethodCompileComplete(CORINFO_METHOD_HANDLE methHnd); diff --git a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.bat b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.bat index c775755558de9..69e3367c4e094 100644 --- a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.bat +++ b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.bat @@ -1,4 +1,4 @@ pushd %~dp0 -call ..\..\..\..\..\..\dotnet.cmd run -- ThunkInput.txt ..\CorInfoBase.cs ..\..\..\aot\jitinterface\jitinterface.h ..\..\..\..\jit\ICorJitInfo_API_names.h ..\..\..\..\jit\ICorJitInfo_API_wrapper.hpp ..\..\..\..\inc\icorjitinfoimpl_generated.h ..\..\..\..\ToolBox\superpmi\superpmi-shim-counter\icorjitinfo.cpp ..\..\..\..\ToolBox\superpmi\superpmi-shim-simple\icorjitinfo.cpp +call ..\..\..\..\..\..\dotnet.cmd run -- ThunkInput.txt ..\CorInfoBase.cs ..\..\..\aot\jitinterface\jitinterface.h ..\..\..\..\jit\ICorJitInfo_API_names.h ..\..\..\..\jit\ICorJitInfo_API_wrapper.hpp ..\..\..\..\inc\icorjitinfoimpl_generated.h ..\..\..\..\tools\superpmi\superpmi-shim-counter\icorjitinfo.cpp ..\..\..\..\tools\superpmi\superpmi-shim-simple\icorjitinfo.cpp call ..\..\..\..\..\..\dotnet.cmd run -- InstructionSetGenerator InstructionSetDesc.txt ..\..\Internal\Runtime\ReadyToRunInstructionSet.cs ..\..\Internal\Runtime\ReadyToRunInstructionSetHelper.cs ..\CorInfoInstructionSet.cs ..\..\..\..\inc\corinfoinstructionset.h ..\..\..\..\inc\readytoruninstructionset.h popd diff --git a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.sh b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.sh index 7dc71bd378d85..ca9cdcb52ef11 100755 --- a/src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.sh +++ b/src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.sh @@ -1,4 +1,4 @@ #!/usr/bin/env bash cd "$(dirname ${BASH_SOURCE[0]})" -../../../../../../dotnet.sh run -- ThunkInput.txt ../CorInfoBase.cs ../../../aot/jitinterface/jitinterface.h ../../../../jit/ICorJitInfo_API_names.h ../../../../jit/ICorJitInfo_API_wrapper.hpp ../../../../inc/icorjitinfoimpl_generated.h ../../../../ToolBox/superpmi/superpmi-shim-counter/icorjitinfo.cpp ../../../../ToolBox/superpmi/superpmi-shim-simple/icorjitinfo.cpp +../../../../../../dotnet.sh run -- ThunkInput.txt ../CorInfoBase.cs ../../../aot/jitinterface/jitinterface.h ../../../../jit/ICorJitInfo_API_names.h ../../../../jit/ICorJitInfo_API_wrapper.hpp ../../../../inc/icorjitinfoimpl_generated.h ../../../../tools/superpmi/superpmi-shim-counter/icorjitinfo.cpp ../../../../tools/superpmi/superpmi-shim-simple/icorjitinfo.cpp ../../../../../../dotnet.sh run -- InstructionSetGenerator InstructionSetDesc.txt ../../Internal/Runtime/ReadyToRunInstructionSet.cs ../../Internal/Runtime/ReadyToRunInstructionSetHelper.cs ../CorInfoInstructionSet.cs ../../../../inc/corinfoinstructionset.h ../../../../inc/readytoruninstructionset.h diff --git a/src/coreclr/tools/Common/TypeSystem/Canon/TypeSystemContext.Canon.cs b/src/coreclr/tools/Common/TypeSystem/Canon/TypeSystemContext.Canon.cs index 091f26bfda510..0a35ceeb64d25 100644 --- a/src/coreclr/tools/Common/TypeSystem/Canon/TypeSystemContext.Canon.cs +++ b/src/coreclr/tools/Common/TypeSystem/Canon/TypeSystemContext.Canon.cs @@ -69,8 +69,7 @@ public bool IsCanonicalDefinitionType(TypeDesc type, CanonicalFormKind kind) /// public Instantiation ConvertInstantiationToCanonForm(Instantiation instantiation, CanonicalFormKind kind) { - bool changed; - return ConvertInstantiationToCanonForm(instantiation, kind, out changed); + return ConvertInstantiationToCanonForm(instantiation, kind, out _); } /// diff --git a/src/coreclr/tools/Common/TypeSystem/Common/ConstructedTypeRewritingHelpers.cs b/src/coreclr/tools/Common/TypeSystem/Common/ConstructedTypeRewritingHelpers.cs index 73c4dfd43f7b4..42011765c379d 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/ConstructedTypeRewritingHelpers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/ConstructedTypeRewritingHelpers.cs @@ -155,7 +155,7 @@ public static TypeDesc ReplaceTypesInConstructionOfType(this TypeDesc type, Type public static MethodDesc ReplaceTypesInConstructionOfMethod(this MethodDesc method, TypeDesc[] typesToReplace, TypeDesc[] replacementTypes) { TypeDesc newOwningType = method.OwningType.ReplaceTypesInConstructionOfType(typesToReplace, replacementTypes); - MethodDesc methodOnOwningType = null; + MethodDesc methodOnOwningType; bool owningTypeChanged = false; if (newOwningType == method.OwningType) { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemHelpers.cs b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemHelpers.cs index f062c0daede44..f36f45f00f5cc 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemHelpers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/TypeSystemHelpers.cs @@ -287,7 +287,7 @@ public static MethodDesc ResolveInterfaceMethodTarget(this TypeDesc thisType, Me { Debug.Assert(interfaceMethodToResolve.OwningType.IsInterface); - MethodDesc result = null; + MethodDesc result; TypeDesc currentType = thisType; do { @@ -307,7 +307,7 @@ public static MethodDesc ResolveInterfaceMethodTargetWithVariance(this TypeDesc { Debug.Assert(interfaceMethodToResolve.OwningType.IsInterface); - MethodDesc result = null; + MethodDesc result; TypeDesc currentType = thisType; do { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs index eee17ccf0cc48..e915f9518ad04 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs @@ -363,8 +363,7 @@ public bool TryAdd(TValue value) /// Newly added value, or a value which was already present in the hashtable which is equal to it. public TValue AddOrGetExisting(TValue value) { - bool unused; - return AddOrGetExistingInner(value, out unused); + return AddOrGetExistingInner(value, out _); } private TValue AddOrGetExistingInner(TValue value, out bool addedValue) @@ -584,8 +583,7 @@ public TValue GetOrCreateValue(TKey key) /// public bool Contains(TKey key) { - TValue dummyExistingValue; - return TryGetValue(key, out dummyExistingValue); + return TryGetValue(key, out _); } /// diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtableOfPointers.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtableOfPointers.cs index 42b62fc6bb073..7c03a26c71bc6 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtableOfPointers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtableOfPointers.cs @@ -326,8 +326,7 @@ public bool TryAdd(TValue value) /// Newly added value, or a value which was already present in the hashtable which is equal to it. public TValue AddOrGetExisting(TValue value) { - bool unused; - return AddOrGetExistingInner(value, out unused); + return AddOrGetExistingInner(value, out _); } private TValue AddOrGetExistingInner(TValue value, out bool addedValue) @@ -525,8 +524,7 @@ public TValue GetOrCreateValue(TKey key) /// public bool Contains(TKey key) { - TValue dummyExistingValue; - return TryGetValue(key, out dummyExistingValue); + return TryGetValue(key, out _); } /// diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs index 276f7dc4a42fc..5b09863069020 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.cs @@ -27,6 +27,14 @@ public partial class DelegateMarshallingMethodThunk : ILStubMethod private readonly MethodDesc _invokeMethod; private MethodSignature _signature; // signature of the native callable marshalling stub + public MethodDesc InvokeMethod + { + get + { + return _invokeMethod; + } + } + public DelegateMarshallingMethodThunkKind Kind { get; diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.cs index a736d065dd833..f23a4479634a9 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/MarshalHelpers.cs @@ -521,7 +521,7 @@ internal static MarshallerKind GetMarshallerKind( else return MarshallerKind.Invalid; } - else if (type.IsDelegate) + else if (type.IsDelegate || InteropTypes.IsSystemDelegate(context, type) || InteropTypes.IsSystemMulticastDelegate(context, type)) { if (type.HasInstantiation) { diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/InteropTypes.cs b/src/coreclr/tools/Common/TypeSystem/Interop/InteropTypes.cs index 4007dc756494e..96ffe8868422d 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/InteropTypes.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/InteropTypes.cs @@ -97,6 +97,16 @@ public static bool IsSystemDecimal(TypeSystemContext context, TypeDesc type) return IsCoreNamedType(context, type, "System", "Decimal"); } + public static bool IsSystemDelegate(TypeSystemContext context, TypeDesc type) + { + return IsCoreNamedType(context, type, "System", "Delegate"); + } + + public static bool IsSystemMulticastDelegate(TypeSystemContext context, TypeDesc type) + { + return IsCoreNamedType(context, type, "System", "MulticastDelegate"); + } + public static bool IsSystemGuid(TypeSystemContext context, TypeDesc type) { return IsCoreNamedType(context, type, "System", "Guid"); diff --git a/src/coreclr/tools/ILVerification/ILVerification.csproj b/src/coreclr/tools/ILVerification/ILVerification.csproj index f9663c92b3069..a7d00d9f30473 100644 --- a/src/coreclr/tools/ILVerification/ILVerification.csproj +++ b/src/coreclr/tools/ILVerification/ILVerification.csproj @@ -9,6 +9,7 @@ netstandard2.0 AnyCPU true + Open diff --git a/src/coreclr/ToolBox/SOS/CMakeLists.txt b/src/coreclr/tools/SOS/CMakeLists.txt similarity index 100% rename from src/coreclr/ToolBox/SOS/CMakeLists.txt rename to src/coreclr/tools/SOS/CMakeLists.txt diff --git a/src/coreclr/ToolBox/SOS/DIALib/DIALib.il b/src/coreclr/tools/SOS/DIALib/DIALib.il similarity index 100% rename from src/coreclr/ToolBox/SOS/DIALib/DIALib.il rename to src/coreclr/tools/SOS/DIALib/DIALib.il diff --git a/src/coreclr/ToolBox/SOS/DIALib/DIALib.ilproj b/src/coreclr/tools/SOS/DIALib/DIALib.ilproj similarity index 100% rename from src/coreclr/ToolBox/SOS/DIALib/DIALib.ilproj rename to src/coreclr/tools/SOS/DIALib/DIALib.ilproj diff --git a/src/coreclr/ToolBox/SOS/DacTableGen/DacTableGen.csproj b/src/coreclr/tools/SOS/DacTableGen/DacTableGen.csproj similarity index 100% rename from src/coreclr/ToolBox/SOS/DacTableGen/DacTableGen.csproj rename to src/coreclr/tools/SOS/DacTableGen/DacTableGen.csproj diff --git a/src/coreclr/ToolBox/SOS/DacTableGen/MapSymbolProvider.cs b/src/coreclr/tools/SOS/DacTableGen/MapSymbolProvider.cs similarity index 100% rename from src/coreclr/ToolBox/SOS/DacTableGen/MapSymbolProvider.cs rename to src/coreclr/tools/SOS/DacTableGen/MapSymbolProvider.cs diff --git a/src/coreclr/ToolBox/SOS/DacTableGen/cvconst.cs b/src/coreclr/tools/SOS/DacTableGen/cvconst.cs similarity index 100% rename from src/coreclr/ToolBox/SOS/DacTableGen/cvconst.cs rename to src/coreclr/tools/SOS/DacTableGen/cvconst.cs diff --git a/src/coreclr/ToolBox/SOS/DacTableGen/diautil.cs b/src/coreclr/tools/SOS/DacTableGen/diautil.cs similarity index 100% rename from src/coreclr/ToolBox/SOS/DacTableGen/diautil.cs rename to src/coreclr/tools/SOS/DacTableGen/diautil.cs diff --git a/src/coreclr/ToolBox/SOS/DacTableGen/main.cs b/src/coreclr/tools/SOS/DacTableGen/main.cs similarity index 100% rename from src/coreclr/ToolBox/SOS/DacTableGen/main.cs rename to src/coreclr/tools/SOS/DacTableGen/main.cs diff --git a/src/coreclr/ToolBox/SOS/Directory.Build.props b/src/coreclr/tools/SOS/Directory.Build.props similarity index 100% rename from src/coreclr/ToolBox/SOS/Directory.Build.props rename to src/coreclr/tools/SOS/Directory.Build.props diff --git a/src/coreclr/ToolBox/SOS/SOS_README.md b/src/coreclr/tools/SOS/SOS_README.md similarity index 100% rename from src/coreclr/ToolBox/SOS/SOS_README.md rename to src/coreclr/tools/SOS/SOS_README.md diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs index 981983750de05..06d371cd17aea 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs @@ -2199,7 +2199,9 @@ public override bool HandleCall(MethodIL callingMethodBody, MethodDesc calledMet if (comDangerousMethod) { reflectionContext.AnalyzingPattern(); - reflectionContext.RecordUnrecognizedPattern(2050, $"P/invoke method '{calledMethod.GetDisplayName()}' declares a parameter with COM marshalling. Correctness of COM interop cannot be guaranteed after trimming. Interfaces and interface members might be removed."); + reflectionContext.RecordUnrecognizedPattern( + (int)DiagnosticId.CorrectnessOfCOMCannotBeGuaranteed, + new DiagnosticString(DiagnosticId.CorrectnessOfCOMCannotBeGuaranteed).GetMessage(DiagnosticUtilities.GetMethodSignatureDisplayName(calledMethod))); } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericCompositionNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericCompositionNode.cs index a4388b4eeb4a9..9857c633784db 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericCompositionNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericCompositionNode.cs @@ -36,6 +36,7 @@ public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) if (_details.Variance != null) { + sb.Append("__Variance__"); for (int i = 0; i < _details.Variance.Length; i++) { sb.Append('_'); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSettings.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSettings.cs new file mode 100644 index 0000000000000..773c061081e45 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSettings.cs @@ -0,0 +1,52 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Xml.XPath; +using ILLink.Shared; +using Internal.TypeSystem; + +namespace ILCompiler +{ + public static class FeatureSettings + { + public static bool ShouldProcessElement(XPathNavigator nav, IReadOnlyDictionary featureSwitchValues) + { + var feature = GetAttribute(nav, "feature"); + if (string.IsNullOrEmpty(feature)) + return true; + + var value = GetAttribute(nav, "featurevalue"); + if (string.IsNullOrEmpty(value)) + { + //context.LogError(null, DiagnosticId.XmlFeatureDoesNotSpecifyFeatureValue, documentLocation, feature); + return false; + } + + if (!bool.TryParse(value, out bool bValue)) + { + //context.LogError(null, DiagnosticId.XmlUnsupportedNonBooleanValueForFeature, documentLocation, feature); + return false; + } + + var isDefault = GetAttribute(nav, "featuredefault"); + bool bIsDefault = false; + if (!string.IsNullOrEmpty(isDefault) && (!bool.TryParse(isDefault, out bIsDefault) || !bIsDefault)) + { + //context.LogError(null, DiagnosticId.XmlDocumentLocationHasInvalidFeatureDefault, documentLocation); + return false; + } + + if (!featureSwitchValues.TryGetValue(feature, out bool featureSetting)) + return bIsDefault; + + return bValue == featureSetting; + } + + public static string GetAttribute(XPathNavigator nav, string attribute) + { + return nav.GetAttribute(attribute, String.Empty); + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs index 5f06913b97d37..20050db2c8cda 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/FeatureSwitchManager.cs @@ -792,7 +792,7 @@ public MethodIL EmitIL(MethodDesc method) } } - private class SubstitutionsReader : ProcessLinkerXmlBase + private class SubstitutionsReader : ProcessXmlBase { private readonly Dictionary _methodSubstitutions; private readonly Dictionary _fieldSubstitutions; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManifestResourceBlockingPolicy.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManifestResourceBlockingPolicy.cs index f9df59bfa816f..3b2b3a2e25384 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManifestResourceBlockingPolicy.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ManifestResourceBlockingPolicy.cs @@ -100,7 +100,7 @@ public AssemblyFeatureInfo(EcmaModule module, IReadOnlyDictionary } } - private class SubstitutionsReader : ProcessLinkerXmlBase + private class SubstitutionsReader : ProcessXmlBase { private readonly HashSet _substitutions = new HashSet(); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessLinkerXmlBase.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessLinkerXmlBase.cs index c5101bde818fa..e157381162aa5 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessLinkerXmlBase.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessLinkerXmlBase.cs @@ -1,316 +1,511 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; using System.Reflection; +using System.Reflection.Metadata; using System.Text; +using System.Text.RegularExpressions; using System.Xml; - +using System.Xml.Linq; +using System.Xml.XPath; +using ILLink.Shared; using Internal.TypeSystem; +#nullable enable + namespace ILCompiler { - /// - /// Base class for readers of IL Linker XML file format. - /// - internal abstract class ProcessLinkerXmlBase + [Flags] + public enum AllowedAssemblies { - private readonly XmlReader _reader; - private readonly ModuleDesc _owningModule; + ContainingAssembly = 0x1, + AnyAssembly = 0x2 | ContainingAssembly, + AllAssemblies = 0x4 | AnyAssembly + } + + public abstract class ProcessLinkerXmlBase + { + const string FullNameAttributeName = "fullname"; + const string LinkerElementName = "linker"; + const string TypeElementName = "type"; + const string SignatureAttributeName = "signature"; + const string NameAttributeName = "name"; + const string FieldElementName = "field"; + const string MethodElementName = "method"; + const string EventElementName = "event"; + const string PropertyElementName = "property"; + const string AllAssembliesFullName = "*"; + protected const string XmlNamespace = ""; + + protected readonly string _xmlDocumentLocation; + readonly XPathNavigator _document; + protected readonly ModuleDesc? _owningModule; private readonly IReadOnlyDictionary _featureSwitchValues; protected readonly TypeSystemContext _context; - public ProcessLinkerXmlBase(TypeSystemContext context, XmlReader reader, ModuleDesc owningModule, IReadOnlyDictionary featureSwitchValues) + protected ProcessLinkerXmlBase(TypeSystemContext context, UnmanagedMemoryStream documentStream, string xmlDocumentLocation, IReadOnlyDictionary featureSwitchValues) { - _reader = reader; - _owningModule = owningModule; - _featureSwitchValues = featureSwitchValues; _context = context; + using (documentStream) + { + _document = XDocument.Load(documentStream, LoadOptions.SetLineInfo).CreateNavigator(); + } + _xmlDocumentLocation = xmlDocumentLocation; + _featureSwitchValues = featureSwitchValues; } - public void ProcessXml() + protected ProcessLinkerXmlBase(TypeSystemContext context, UnmanagedMemoryStream documentStream, ManifestResource resource, ModuleDesc resourceAssembly, string xmlDocumentLocation, IReadOnlyDictionary featureSwitchValues) + : this(context, documentStream, xmlDocumentLocation, featureSwitchValues) { - if (_reader.IsStartElement() && _reader.Name == "linker") + _owningModule = resourceAssembly ?? throw new ArgumentNullException(nameof(resourceAssembly)); + } + + protected virtual bool ShouldProcessElement(XPathNavigator nav) => FeatureSettings.ShouldProcessElement(nav, _featureSwitchValues); + + protected virtual void ProcessXml(bool ignoreResource) + { + if (!AllowedAssemblySelector.HasFlag(AllowedAssemblies.AnyAssembly) && _owningModule == null) + throw new InvalidOperationException("The containing assembly must be specified for XML which is restricted to modifying that assembly only."); + + try { - if (!ShouldProcessElement()) + XPathNavigator nav = _document.CreateNavigator(); + + // Initial structure check - ignore XML document which don't look like linker XML format + if (!nav.MoveToChild(LinkerElementName, XmlNamespace)) + return; + + if (_owningModule != null) + { + if (ignoreResource) + return; + } + + if (!ShouldProcessElement(nav)) return; - _reader.Read(); + ProcessAssemblies(nav); - ProcessAssemblies(); + // For embedded XML, allow not specifying the assembly explicitly in XML. + if (_owningModule != null) + ProcessAssembly(_owningModule, nav, warnOnUnresolvedTypes: true); + + } + catch (Exception ex) + { + // throw new LinkerFatalErrorException(MessageContainer.CreateErrorMessage(null, DiagnosticId.ErrorProcessingXmlLocation, _xmlDocumentLocation), ex); + throw ex; } } - protected string GetAttribute(string attribute) - { - return _reader.GetAttribute(attribute); - } + protected virtual AllowedAssemblies AllowedAssemblySelector { get => _owningModule != null ? AllowedAssemblies.ContainingAssembly : AllowedAssemblies.AnyAssembly; } - protected bool IsEmpty() + bool ShouldProcessAllAssemblies(XPathNavigator nav, [NotNullWhen(false)] out AssemblyName? assemblyName) { - return _reader.IsEmptyElement; + assemblyName = null; + if (GetFullName(nav) == AllAssembliesFullName) + return true; + + assemblyName = GetAssemblyName(nav); + return false; } - private void ProcessAssemblies() + protected virtual void ProcessAssemblies(XPathNavigator nav) { - while (_reader.IsStartElement()) + foreach (XPathNavigator assemblyNav in nav.SelectChildren("assembly", "")) { - if (_reader.Name == "assembly") + // Errors for invalid assembly names should show up even if this element will be + // skipped due to feature conditions. + bool processAllAssemblies = ShouldProcessAllAssemblies(assemblyNav, out AssemblyName? name); + if (processAllAssemblies && AllowedAssemblySelector != AllowedAssemblies.AllAssemblies) { - string assemblyName = _reader.GetAttribute("fullname"); + //LogWarning(assemblyNav, DiagnosticId.XmlUnsuportedWildcard); + continue; + } - if (assemblyName == "*") + ModuleDesc? assemblyToProcess = null; + if (!AllowedAssemblySelector.HasFlag(AllowedAssemblies.AnyAssembly)) + { + Debug.Assert(!processAllAssemblies); + Debug.Assert(_owningModule != null); + if (_owningModule.Assembly.GetName().Name != name!.Name) { - // https://github.com/dotnet/runtimelab/issues/1381 - _reader.Skip(); + //LogWarning(assemblyNav, DiagnosticId.AssemblyWithEmbeddedXmlApplyToAnotherAssembly, _resource.Value.Assembly.Name.Name, name.ToString()); continue; } + assemblyToProcess = _owningModule; + } - // Errors for invalid assembly names should show up even if this element will be - // skipped due to feature conditions. - var name = new AssemblyName(assemblyName); + if (!ShouldProcessElement(assemblyNav)) + continue; - if (!ShouldProcessElement()) - { - _reader.Skip(); - continue; - } - - ModuleDesc assembly = GetAssembly(name); + if (processAllAssemblies) + { + throw new NotImplementedException(); + // We could avoid loading all references in this case: https://github.com/dotnet/linker/issues/1708 + //foreach (ModuleDesc assembly in GetReferencedAssemblies()) + // ProcessAssembly(assembly, assemblyNav, warnOnUnresolvedTypes: false); + } + else + { + Debug.Assert(!processAllAssemblies); + ModuleDesc? assembly = assemblyToProcess ?? _context.ResolveAssembly(name!); if (assembly == null) { - //Context.LogWarning($"Could not resolve assembly '{name.Name}'", 2007, _xmlDocumentLocation); - _reader.Skip(); + //LogWarning(assemblyNav, DiagnosticId.XmlCouldNotResolveAssembly, name!.Name); continue; } - _reader.Read(); - - ProcessAssembly(assembly); - } - else if (_reader.Name == "type") - { - ProcessType(_owningModule); - } - else if (_reader.Name == "resource") - { - ProcessResource(_owningModule); - } - else - { - _reader.Skip(); + ProcessAssembly(assembly, assemblyNav, warnOnUnresolvedTypes: true); } } } - protected ModuleDesc GetAssembly(AssemblyName name) - { - return _context.ResolveAssembly(name); - } - private void ProcessAssembly(ModuleDesc assembly) + protected abstract void ProcessAssembly(ModuleDesc assembly, XPathNavigator nav, bool warnOnUnresolvedTypes); + + protected virtual void ProcessTypes(ModuleDesc assembly, XPathNavigator nav, bool warnOnUnresolvedTypes) { - while (_reader.IsStartElement()) + foreach (XPathNavigator typeNav in nav.SelectChildren(TypeElementName, XmlNamespace)) { - if (_reader.Name == "type") + + if (!ShouldProcessElement(typeNav)) + continue; + + string fullname = GetFullName(typeNav); + + if (fullname.IndexOf("*") != -1) { - ProcessType(assembly); + if (ProcessTypePattern(fullname, assembly, typeNav)) + continue; } - else if (_reader.Name == "resource") + + // TODO: Process exported types + + // TODO: Semantics differ and xml format is cecil specific, therefore they are discrepancies on things like nested types + TypeDesc type = CustomAttributeTypeNameParser.GetTypeByCustomAttributeTypeName(assembly, fullname, throwIfNotFound: false); + + if (type == null) { - ProcessResource(assembly); + //if (warnOnUnresolvedTypes) + // LogWarning(typeNav, DiagnosticId.XmlCouldNotResolveType, fullname); + continue; } - _reader.Skip(); + ProcessType(type, typeNav); } + } + + void MatchType(TypeDesc type, Regex regex, XPathNavigator nav) + { + StringBuilder sb = new StringBuilder(); + CecilTypeNameFormatter.Instance.AppendName(sb, type); + if (regex.Match(sb.ToString()).Success) + ProcessType(type, nav); + } - _reader.ReadEndElement(); + protected virtual bool ProcessTypePattern(string fullname, ModuleDesc assembly, XPathNavigator nav) + { + Regex regex = new Regex(fullname.Replace(".", @"\.").Replace("*", "(.*)")); + + foreach (TypeDesc type in assembly.GetAllTypes()) + MatchType(type, regex, nav); + + return true; } - private void ProcessType(ModuleDesc assembly) + protected abstract void ProcessType(TypeDesc type, XPathNavigator nav); + + protected void ProcessTypeChildren(TypeDesc type, XPathNavigator nav, object? customData = null) { - if (ShouldProcessElement()) + if (nav.HasChildren) { - string typeName = _reader.GetAttribute("fullname"); + ProcessSelectedFields(nav, type); + ProcessSelectedMethods(nav, type, customData); + // TODO: In order to be compatible with the format we need to be able to recognize properties, events and maybe attributes + } + } - if (typeName.Contains('*')) - throw new NotSupportedException(); + void ProcessSelectedFields(XPathNavigator nav, TypeDesc type) + { + foreach (XPathNavigator fieldNav in nav.SelectChildren(FieldElementName, XmlNamespace)) + { + if (!ShouldProcessElement(fieldNav)) + continue; + ProcessField(type, fieldNav); + } + } - TypeDesc type = CustomAttributeTypeNameParser.GetTypeByCustomAttributeTypeName(assembly, typeName, throwIfNotFound: false); - if (type == null) + protected virtual void ProcessField(TypeDesc type, XPathNavigator nav) + { + string signature = GetSignature(nav); + if (!String.IsNullOrEmpty(signature)) + { + FieldDesc? field = GetField(type, signature); + if (field == null) { - //Context.LogWarning ($"Could not resolve type '{fullname}'", 2008, _xmlDocumentLocation); - _reader.Skip(); + //LogWarning(nav, DiagnosticId.XmlCouldNotFindFieldOnType, signature, type.GetDisplayName()); return; } - _reader.Read(); + ProcessField(type, field, nav); + } - while (_reader.IsStartElement()) + string name = GetName(nav); + if (!String.IsNullOrEmpty(name)) + { + bool foundMatch = false; + foreach (FieldDesc field in type.GetFields()) { - if (_reader.Name == "method") - { - ProcessMethod(type); - } - else if (_reader.Name == "field") + if (field.Name == name) { - ProcessField(type); - } - else if (_reader.Name == "attribute") - { - ProcessAttribute(type); + foundMatch = true; + ProcessField(type, field, nav); } + } + - _reader.Skip(); + if (!foundMatch) + { + // LogWarning(nav, DiagnosticId.XmlCouldNotFindFieldOnType, name, type.GetDisplayName()); } } + } + + protected static FieldDesc? GetField(TypeDesc type, string signature) + { + StringBuilder sb = new StringBuilder(); + foreach (FieldDesc field in type.GetFields()) + { + sb.Clear(); + CecilTypeNameFormatter.Instance.AppendName(sb, field.FieldType); + if (signature == sb.ToString() + " " + field.Name) + return field; + } + + return null; + } + + protected virtual void ProcessField(TypeDesc type, FieldDesc field, XPathNavigator nav) { } - _reader.Skip(); + void ProcessSelectedMethods(XPathNavigator nav, TypeDesc type, object? customData) + { + foreach (XPathNavigator methodNav in nav.SelectChildren(MethodElementName, XmlNamespace)) + { + if (!ShouldProcessElement(methodNav)) + continue; + ProcessMethod(type, methodNav, customData); + } } - private void ProcessMethod(TypeDesc type) + protected virtual void ProcessMethod(TypeDesc type, XPathNavigator nav, object? customData) { - if (ShouldProcessElement()) + string signature = GetSignature(nav); + if (!String.IsNullOrEmpty(signature)) { - string signature = _reader.GetAttribute("signature"); - if (!String.IsNullOrEmpty(signature)) + MethodDesc? method = GetMethod(type, signature); + if (method == null) { - MethodDesc method = GetMethod(type, signature); - if (method == null) - { - //Context.LogWarning($"Could not find method '{signature}' on type '{type.GetDisplayName()}'", 2009, _xmlDocumentLocation); - return; - } - - ProcessMethod(method); + //LogWarning(nav, DiagnosticId.XmlCouldNotFindMethodOnType, signature, type.GetDisplayName()); + return; } - string methodName = _reader.GetAttribute("name"); - if (!String.IsNullOrEmpty(methodName)) - { - bool foundMatch = false; - foreach (MethodDesc method in type.GetMethods()) - { - if (method.Name == methodName) - { - foundMatch = true; - ProcessMethod(method); - } - } + ProcessMethod(type, method, nav, customData); + } - if (!foundMatch) + string name = GetAttribute(nav, NameAttributeName); + if (!String.IsNullOrEmpty(name)) + { + bool foundMatch = false; + foreach (MethodDesc method in type.GetAllMethods()) + { + if (name == method.Name) { - //Context.LogWarning($"Could not find method '{name}' on type '{type.GetDisplayName()}'", 2009, _xmlDocumentLocation); + foundMatch = true; + ProcessMethod(type, method, nav, customData); } } + if (!foundMatch) + { + // LogWarning(nav, DiagnosticId.XmlCouldNotFindMethodOnType, name, type.GetDisplayName()); + } } } - protected virtual void ProcessMethod(MethodDesc method) + protected virtual MethodDesc? GetMethod(TypeDesc type, string signature) => null; + + protected virtual void ProcessMethod(TypeDesc type, MethodDesc method, XPathNavigator nav, object? customData) { } + +#if false + void ProcessSelectedEvents(XPathNavigator nav, TypeDefinition type, object? customData) { + foreach (XPathNavigator eventNav in nav.SelectChildren(EventElementName, XmlNamespace)) + { + if (!ShouldProcessElement(eventNav)) + continue; + ProcessEvent(type, eventNav, customData); + } } - private void ProcessField(TypeDesc type) + protected virtual void ProcessEvent(TypeDefinition type, XPathNavigator nav, object? customData) { - if (ShouldProcessElement()) + string signature = GetSignature(nav); + if (!String.IsNullOrEmpty(signature)) { - string fieldName = _reader.GetAttribute("name"); - if (!String.IsNullOrEmpty(fieldName)) + EventDefinition? @event = GetEvent(type, signature); + if (@event == null) { - FieldDesc field = type.GetField(fieldName); + LogWarning(nav, DiagnosticId.XmlCouldNotFindEventOnType, signature, type.GetDisplayName()); + return; + } - if (field == null) - { - //Context.LogWarning($"Could not find field '{name}' on type '{type.GetDisplayName()}'", 2012, _xmlDocumentLocation); - } - else + ProcessEvent(type, @event, nav, customData); + } + + string name = GetAttribute(nav, NameAttributeName); + if (!String.IsNullOrEmpty(name)) + { + bool foundMatch = false; + foreach (EventDefinition @event in type.Events) + { + if (@event.Name == name) { - ProcessField(field); + foundMatch = true; + ProcessEvent(type, @event, nav, customData); } } + + if (!foundMatch) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindEventOnType, name, type.GetDisplayName()); + } } } - protected virtual void ProcessField(FieldDesc field) + protected static EventDefinition? GetEvent(TypeDefinition type, string signature) { - } + if (!type.HasEvents) + return null; - protected virtual void ProcessAttribute(TypeDesc type) - { - } + foreach (EventDefinition @event in type.Events) + if (signature == @event.EventType.FullName + " " + @event.Name) + return @event; - protected virtual void ProcessResource(ModuleDesc module) - { + return null; } - protected MethodDesc GetMethod(TypeDesc type, string signature) - { - foreach (MethodDesc meth in type.GetMethods()) - if (signature == GetMethodSignature(meth, false)) - return meth; + protected virtual void ProcessEvent(TypeDefinition type, EventDefinition @event, XPathNavigator nav, object? customData) { } - return null; + void ProcessSelectedProperties(XPathNavigator nav, TypeDefinition type, object? customData) + { + foreach (XPathNavigator propertyNav in nav.SelectChildren(PropertyElementName, XmlNamespace)) + { + if (!ShouldProcessElement(propertyNav)) + continue; + ProcessProperty(type, propertyNav, customData); + } } - public static string GetMethodSignature(MethodDesc meth, bool includeGenericParameters) + protected virtual void ProcessProperty(TypeDefinition type, XPathNavigator nav, object? customData) { - StringBuilder sb = new StringBuilder(); - CecilTypeNameFormatter.Instance.AppendName(sb, meth.Signature.ReturnType); - sb.Append(' '); - sb.Append(meth.Name); - if (includeGenericParameters && meth.HasInstantiation) + string signature = GetSignature(nav); + if (!String.IsNullOrEmpty(signature)) { - sb.Append('`'); - sb.Append(meth.Instantiation.Length); + PropertyDefinition? property = GetProperty(type, signature); + if (property == null) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindPropertyOnType, signature, type.GetDisplayName()); + return; + } + + ProcessProperty(type, property, nav, customData, true); } - sb.Append('('); - for (int i = 0; i < meth.Signature.Length; i++) + string name = GetAttribute(nav, NameAttributeName); + if (!String.IsNullOrEmpty(name)) { - if (i > 0) - sb.Append(','); + bool foundMatch = false; + foreach (PropertyDefinition property in type.Properties) + { + if (property.Name == name) + { + foundMatch = true; + ProcessProperty(type, property, nav, customData, false); + } + } - CecilTypeNameFormatter.Instance.AppendName(sb, meth.Signature[i]); + if (!foundMatch) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindPropertyOnType, name, type.GetDisplayName()); + } } + } + + protected static PropertyDefinition? GetProperty(TypeDefinition type, string signature) + { + if (!type.HasProperties) + return null; + + foreach (PropertyDefinition property in type.Properties) + if (signature == property.PropertyType.FullName + " " + property.Name) + return property; - sb.Append(')'); - return sb.ToString(); + return null; } - private bool ShouldProcessElement() + protected virtual void ProcessProperty(TypeDefinition type, PropertyDefinition property, XPathNavigator nav, object? customData, bool fromSignature) { } +#endif + + protected virtual AssemblyName GetAssemblyName(XPathNavigator nav) { - string feature = _reader.GetAttribute("feature"); - if (string.IsNullOrEmpty(feature)) - return true; + return new AssemblyName(GetFullName(nav)); + } - string value = _reader.GetAttribute("featurevalue"); - if (string.IsNullOrEmpty(value)) - { - //context.LogError($"Failed to process '{documentLocation}'. Feature '{feature}' does not specify a 'featurevalue' attribute", 1001); - return false; - } + protected static string GetFullName(XPathNavigator nav) + { + return GetAttribute(nav, FullNameAttributeName); + } - if (!bool.TryParse(value, out bool bValue)) - { - //context.LogError($"Failed to process '{documentLocation}'. Unsupported non-boolean feature definition '{feature}'", 1002); - return false; - } + protected static string GetName(XPathNavigator nav) + { + return GetAttribute(nav, NameAttributeName); + } - var isDefault = _reader.GetAttribute("featuredefault"); - bool bIsDefault = false; - if (!string.IsNullOrEmpty(isDefault) && (!bool.TryParse(isDefault, out bIsDefault) || !bIsDefault)) - { - //context.LogError($"Failed to process '{documentLocation}'. Unsupported value for featuredefault attribute", 1014); - return false; - } + protected static string GetSignature(XPathNavigator nav) + { + return GetAttribute(nav, SignatureAttributeName); + } - if (!_featureSwitchValues.TryGetValue(feature, out bool featureSetting)) - return bIsDefault; + protected static string GetAttribute(XPathNavigator nav, string attribute) + { + return nav.GetAttribute(attribute, XmlNamespace); + } - return bValue == featureSetting; +#if false + protected MessageOrigin GetMessageOriginForPosition(XPathNavigator position) + { + return (position is IXmlLineInfo lineInfo) + ? new MessageOrigin(_xmlDocumentLocation, lineInfo.LineNumber, lineInfo.LinePosition, _resource?.Assembly) + : new MessageOrigin(_xmlDocumentLocation, 0, 0, _resource?.Assembly); + } + protected void LogWarning(string message, int warningCode, XPathNavigator position) + { + _context.LogWarning(message, warningCode, GetMessageOriginForPosition(position)); + } + + protected void LogWarning(XPathNavigator position, DiagnosticId id, params string[] args) + { + _context.LogWarning(GetMessageOriginForPosition(position), id, args); } +#endif class CecilTypeNameFormatter : TypeNameFormatter { @@ -399,6 +594,106 @@ protected override void AppendNameForNestedType(StringBuilder sb, DefType nested sb.Append('/'); sb.Append(nestedType.Name); } + +#if false + public bool TryConvertValue(string value, TypeDesc type, out object? result) + { + switch (type.UnderlyingType.Category) + { + case TypeFlags.Boolean: + if ((bool.TryParse(value, out bool bvalue))) + { + result = bvalue ? 1 : 0; + return true; + } + else + goto case TypeFlags.Int32; + + case TypeFlags.Byte: + if (!byte.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out byte byteresult)) + break; + + result = (int)byteresult; + return true; + + case TypeFlags.SByte: + if (!sbyte.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out sbyte sbyteresult)) + break; + + result = (int)sbyteresult; + return true; + + case TypeFlags.Int16: + if (!short.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out short shortresult)) + break; + + result = (int)shortresult; + return true; + + case TypeFlags.UInt16: + if (!ushort.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out ushort ushortresult)) + break; + + result = (int)ushortresult; + return true; + + case TypeFlags.Int32: + if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int iresult)) + break; + + result = iresult; + return true; + + case TypeFlags.UInt32: + if (!uint.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out uint uresult)) + break; + + result = (int)uresult; + return true; + + case TypeFlags.Double: + if (!double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double dresult)) + break; + + result = dresult; + return true; + + case TypeFlags.Single: + if (!float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float fresult)) + break; + + result = fresult; + return true; + + case TypeFlags.Int64: + if (!long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long lresult)) + break; + + result = lresult; + return true; + + case TypeFlags.UInt64: + if (!ulong.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out ulong ulresult)) + break; + + result = (long)ulresult; + return true; + + case TypeFlags.Char: + if (!char.TryParse(value, out char chresult)) + break; + + result = (int)chresult; + return true; + + default: + throw new NotSupportedException(type.ToString()); + } + + result = null; + return false; + } +#endif } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessXmlBase.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessXmlBase.cs new file mode 100644 index 0000000000000..b00f56a0c2ce4 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ProcessXmlBase.cs @@ -0,0 +1,404 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using System.Xml; + +using Internal.TypeSystem; + +namespace ILCompiler +{ + /// + /// Base class for readers of IL Linker XML file format. + /// + internal abstract class ProcessXmlBase + { + private readonly XmlReader _reader; + private readonly ModuleDesc _owningModule; + private readonly IReadOnlyDictionary _featureSwitchValues; + protected readonly TypeSystemContext _context; + + public ProcessXmlBase(TypeSystemContext context, XmlReader reader, ModuleDesc owningModule, IReadOnlyDictionary featureSwitchValues) + { + _reader = reader; + _owningModule = owningModule; + _featureSwitchValues = featureSwitchValues; + _context = context; + } + + public void ProcessXml() + { + if (_reader.IsStartElement() && _reader.Name == "linker") + { + if (!ShouldProcessElement()) + return; + + _reader.Read(); + + ProcessAssemblies(); + } + } + + protected string GetAttribute(string attribute) + { + return _reader.GetAttribute(attribute); + } + + protected bool IsEmpty() + { + return _reader.IsEmptyElement; + } + + private void ProcessAssemblies() + { + while (_reader.IsStartElement()) + { + if (_reader.Name == "assembly") + { + string assemblyName = _reader.GetAttribute("fullname"); + + if (assemblyName == "*") + { + // https://github.com/dotnet/runtimelab/issues/1381 + _reader.Skip(); + continue; + } + + // Errors for invalid assembly names should show up even if this element will be + // skipped due to feature conditions. + var name = new AssemblyName(assemblyName); + + if (!ShouldProcessElement()) + { + _reader.Skip(); + continue; + } + + ModuleDesc assembly = GetAssembly(name); + + if (assembly == null) + { + //Context.LogWarning($"Could not resolve assembly '{name.Name}'", 2007, _xmlDocumentLocation); + _reader.Skip(); + continue; + } + + _reader.Read(); + + ProcessAssembly(assembly); + } + else if (_reader.Name == "type") + { + ProcessType(_owningModule); + } + else if (_reader.Name == "resource") + { + ProcessResource(_owningModule); + } + else + { + _reader.Skip(); + } + } + } + + protected ModuleDesc GetAssembly(AssemblyName name) + { + return _context.ResolveAssembly(name); + } + + private void ProcessAssembly(ModuleDesc assembly) + { + while (_reader.IsStartElement()) + { + if (_reader.Name == "type") + { + ProcessType(assembly); + } + else if (_reader.Name == "resource") + { + ProcessResource(assembly); + } + + _reader.Skip(); + } + + _reader.ReadEndElement(); + } + + private void ProcessType(ModuleDesc assembly) + { + if (ShouldProcessElement()) + { + string typeName = _reader.GetAttribute("fullname"); + + if (typeName.Contains('*')) + throw new NotSupportedException(); + + TypeDesc type = CustomAttributeTypeNameParser.GetTypeByCustomAttributeTypeName(assembly, typeName, throwIfNotFound: false); + if (type == null) + { + //Context.LogWarning ($"Could not resolve type '{fullname}'", 2008, _xmlDocumentLocation); + _reader.Skip(); + return; + } + + _reader.Read(); + + while (_reader.IsStartElement()) + { + if (_reader.Name == "method") + { + ProcessMethod(type); + } + else if (_reader.Name == "field") + { + ProcessField(type); + } + else if (_reader.Name == "attribute") + { + ProcessAttribute(type); + } + + _reader.Skip(); + } + } + + _reader.Skip(); + } + + private void ProcessMethod(TypeDesc type) + { + if (ShouldProcessElement()) + { + string signature = _reader.GetAttribute("signature"); + if (!String.IsNullOrEmpty(signature)) + { + MethodDesc method = GetMethod(type, signature); + if (method == null) + { + //Context.LogWarning($"Could not find method '{signature}' on type '{type.GetDisplayName()}'", 2009, _xmlDocumentLocation); + return; + } + + ProcessMethod(method); + } + + string methodName = _reader.GetAttribute("name"); + if (!String.IsNullOrEmpty(methodName)) + { + bool foundMatch = false; + foreach (MethodDesc method in type.GetMethods()) + { + if (method.Name == methodName) + { + foundMatch = true; + ProcessMethod(method); + } + } + + if (!foundMatch) + { + //Context.LogWarning($"Could not find method '{name}' on type '{type.GetDisplayName()}'", 2009, _xmlDocumentLocation); + } + } + } + } + + protected virtual void ProcessMethod(MethodDesc method) + { + } + + private void ProcessField(TypeDesc type) + { + if (ShouldProcessElement()) + { + string fieldName = _reader.GetAttribute("name"); + if (!String.IsNullOrEmpty(fieldName)) + { + FieldDesc field = type.GetField(fieldName); + + if (field == null) + { + //Context.LogWarning($"Could not find field '{name}' on type '{type.GetDisplayName()}'", 2012, _xmlDocumentLocation); + } + else + { + ProcessField(field); + } + } + } + } + + protected virtual void ProcessField(FieldDesc field) + { + } + + protected virtual void ProcessAttribute(TypeDesc type) + { + } + + protected virtual void ProcessResource(ModuleDesc module) + { + } + + protected MethodDesc GetMethod(TypeDesc type, string signature) + { + foreach (MethodDesc meth in type.GetMethods()) + if (signature == GetMethodSignature(meth, false)) + return meth; + + return null; + } + + public static string GetMethodSignature(MethodDesc meth, bool includeGenericParameters) + { + StringBuilder sb = new StringBuilder(); + CecilTypeNameFormatter.Instance.AppendName(sb, meth.Signature.ReturnType); + sb.Append(' '); + sb.Append(meth.Name); + if (includeGenericParameters && meth.HasInstantiation) + { + sb.Append('`'); + sb.Append(meth.Instantiation.Length); + } + + sb.Append('('); + for (int i = 0; i < meth.Signature.Length; i++) + { + if (i > 0) + sb.Append(','); + + CecilTypeNameFormatter.Instance.AppendName(sb, meth.Signature[i]); + } + + sb.Append(')'); + return sb.ToString(); + } + + private bool ShouldProcessElement() + { + string feature = _reader.GetAttribute("feature"); + if (string.IsNullOrEmpty(feature)) + return true; + + string value = _reader.GetAttribute("featurevalue"); + if (string.IsNullOrEmpty(value)) + { + //context.LogError($"Failed to process '{documentLocation}'. Feature '{feature}' does not specify a 'featurevalue' attribute", 1001); + return false; + } + + if (!bool.TryParse(value, out bool bValue)) + { + //context.LogError($"Failed to process '{documentLocation}'. Unsupported non-boolean feature definition '{feature}'", 1002); + return false; + } + + var isDefault = _reader.GetAttribute("featuredefault"); + bool bIsDefault = false; + if (!string.IsNullOrEmpty(isDefault) && (!bool.TryParse(isDefault, out bIsDefault) || !bIsDefault)) + { + //context.LogError($"Failed to process '{documentLocation}'. Unsupported value for featuredefault attribute", 1014); + return false; + } + + if (!_featureSwitchValues.TryGetValue(feature, out bool featureSetting)) + return bIsDefault; + + return bValue == featureSetting; + } + + class CecilTypeNameFormatter : TypeNameFormatter + { + public static readonly CecilTypeNameFormatter Instance = new CecilTypeNameFormatter(); + + public override void AppendName(StringBuilder sb, ArrayType type) + { + AppendName(sb, type.ElementType); + sb.Append('['); + if (type.Rank > 1) + sb.Append(new string(',', type.Rank - 1)); + sb.Append(']'); + } + public override void AppendName(StringBuilder sb, ByRefType type) + { + AppendName(sb, type.ParameterType); + sb.Append('&'); + } + + public override void AppendName(StringBuilder sb, PointerType type) + { + AppendName(sb, type.ParameterType); + sb.Append('*'); + } + + public override void AppendName(StringBuilder sb, FunctionPointerType type) + { + sb.Append(" "); + AppendName(sb, type.Signature.ReturnType); + sb.Append(" *"); + + sb.Append("("); + + for (int i = 0; i < type.Signature.Length; i++) + { + var parameter = type.Signature[i]; + if (i > 0) + sb.Append(","); + + AppendName(sb, parameter); + } + + sb.Append(")"); + } + + public override void AppendName(StringBuilder sb, GenericParameterDesc type) + { + sb.Append(type.Name); + } + public override void AppendName(StringBuilder sb, SignatureMethodVariable type) + { + } + public override void AppendName(StringBuilder sb, SignatureTypeVariable type) + { + } + protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType type) + { + AppendName(sb, type.GetTypeDefinition()); + + sb.Append('<'); + + for (int i = 0; i < type.Instantiation.Length; i++) + { + if (i != 0) + sb.Append(','); + + AppendName(sb, type.Instantiation[i]); + } + + sb.Append('>'); + } + protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type) + { + if (!String.IsNullOrEmpty(type.Namespace)) + { + sb.Append(type.Namespace); + sb.Append('.'); + } + + sb.Append(type.Name); + } + + protected override void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType) + { + AppendName(sb, containingType); + sb.Append('/'); + sb.Append(nestedType.Name); + } + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/BodySubstitutionParser.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/BodySubstitutionParser.cs new file mode 100644 index 0000000000000..403eb9207342e --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/BodySubstitutionParser.cs @@ -0,0 +1,174 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Xml.XPath; +using ILLink.Shared; +using Mono.Cecil; + +namespace Mono.Linker.Steps +{ + public class BodySubstitutionParser : ProcessLinkerXmlBase + { + SubstitutionInfo? _substitutionInfo; + + public BodySubstitutionParser(LinkContext context, Stream documentStream, string xmlDocumentLocation) + : base(context, documentStream, xmlDocumentLocation) + { + } + + public BodySubstitutionParser(LinkContext context, Stream documentStream, EmbeddedResource resource, AssemblyDefinition resourceAssembly, string xmlDocumentLocation = "") + : base(context, documentStream, resource, resourceAssembly, xmlDocumentLocation) + { + } + + public void Parse(SubstitutionInfo xmlInfo) + { + _substitutionInfo = xmlInfo; + bool stripSubstitutions = _context.IsOptimizationEnabled(CodeOptimizations.RemoveSubstitutions, _resource?.Assembly); + ProcessXml(stripSubstitutions, _context.IgnoreSubstitutions); + } + + protected override void ProcessAssembly(AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes) + { + ProcessTypes(assembly, nav, warnOnUnresolvedTypes); + ProcessResources(assembly, nav); + } + + protected override TypeDefinition? ProcessExportedType(ExportedType exported, AssemblyDefinition assembly, XPathNavigator nav) => null; + + protected override bool ProcessTypePattern(string fullname, AssemblyDefinition assembly, XPathNavigator nav) => false; + + protected override void ProcessType(TypeDefinition type, XPathNavigator nav) + { + Debug.Assert(ShouldProcessElement(nav)); + ProcessTypeChildren(type, nav); + } + + protected override void ProcessMethod(TypeDefinition type, XPathNavigator methodNav, object? _customData) + { + Debug.Assert(_substitutionInfo != null); + string signature = GetSignature(methodNav); + if (string.IsNullOrEmpty(signature)) + return; + + MethodDefinition? method = FindMethod(type, signature); + if (method == null) + { + LogWarning(methodNav, DiagnosticId.XmlCouldNotFindMethodOnType, signature, type.GetDisplayName()); + return; + } + + string action = GetAttribute(methodNav, "body"); + switch (action) + { + case "remove": + _substitutionInfo.SetMethodAction(method, MethodAction.ConvertToThrow); + return; + case "stub": + string value = GetAttribute(methodNav, "value"); + if (!string.IsNullOrEmpty(value)) + { + if (!TryConvertValue(value, method.ReturnType, out object? res)) + { + LogWarning(methodNav, DiagnosticId.XmlInvalidValueForStub, method.GetDisplayName()); + return; + } + + _substitutionInfo.SetMethodStubValue(method, res); + } + + _substitutionInfo.SetMethodAction(method, MethodAction.ConvertToStub); + return; + default: + LogWarning(methodNav, DiagnosticId.XmlUnkownBodyModification, action, method.GetDisplayName()); + return; + } + } + + protected override void ProcessField(TypeDefinition type, XPathNavigator fieldNav) + { + Debug.Assert(_substitutionInfo != null); + string name = GetAttribute(fieldNav, "name"); + if (string.IsNullOrEmpty(name)) + return; + + var field = type.Fields.FirstOrDefault(f => f.Name == name); + if (field == null) + { + LogWarning(fieldNav, DiagnosticId.XmlCouldNotFindFieldOnType, name, type.GetDisplayName()); + return; + } + + if (!field.IsStatic || field.IsLiteral) + { + LogWarning(fieldNav, DiagnosticId.XmlSubstitutedFieldNeedsToBeStatic, field.GetDisplayName()); + return; + } + + string value = GetAttribute(fieldNav, "value"); + if (string.IsNullOrEmpty(value)) + { + LogWarning(fieldNav, DiagnosticId.XmlMissingSubstitutionValueForField, field.GetDisplayName()); + return; + } + if (!TryConvertValue(value, field.FieldType, out object? res)) + { + LogWarning(fieldNav, DiagnosticId.XmlInvalidSubstitutionValueForField, value, field.GetDisplayName()); + return; + } + + _substitutionInfo.SetFieldValue(field, res); + + string init = GetAttribute(fieldNav, "initialize"); + if (init?.ToLowerInvariant() == "true") + { + _substitutionInfo.SetFieldInit(field); + } + } + + void ProcessResources(AssemblyDefinition assembly, XPathNavigator nav) + { + foreach (XPathNavigator resourceNav in nav.SelectChildren("resource", "")) + { + if (!ShouldProcessElement(resourceNav)) + continue; + + string name = GetAttribute(resourceNav, "name"); + if (String.IsNullOrEmpty(name)) + { + LogWarning(resourceNav, DiagnosticId.XmlMissingNameAttributeInResource); + continue; + } + + string action = GetAttribute(resourceNav, "action"); + if (action != "remove") + { + LogWarning(resourceNav, DiagnosticId.XmlInvalidValueForAttributeActionForResource, action, name); + continue; + } + + EmbeddedResource? resource = assembly.FindEmbeddedResource(name); + if (resource == null) + { + LogWarning(resourceNav, DiagnosticId.XmlCouldNotFindResourceToRemoveInAssembly, name, assembly.Name.Name); + continue; + } + + _context.Annotations.AddResourceToRemove(assembly, resource); + } + } + + static MethodDefinition? FindMethod(TypeDefinition type, string signature) + { + if (!type.HasMethods) + return null; + + foreach (MethodDefinition meth in type.Methods) + if (signature == DescriptorMarker.GetMethodSignature(meth, includeGenericParameters: true)) + return meth; + + return null; + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/DescriptorMarker.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/DescriptorMarker.cs new file mode 100644 index 0000000000000..49404575e41f9 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/DescriptorMarker.cs @@ -0,0 +1,292 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Xml.XPath; +using ILLink.Shared; + +using Mono.Cecil; + +namespace Mono.Linker.Steps +{ + public class DescriptorMarker : ProcessLinkerXmlBase + { + const string NamespaceElementName = "namespace"; + + const string _required = "required"; + const string _preserve = "preserve"; + const string _accessors = "accessors"; + + static readonly string[] _accessorsAll = new string[] { "all" }; + static readonly char[] _accessorsSep = new char[] { ';' }; + + public DescriptorMarker(LinkContext context, Stream documentStream, string xmlDocumentLocation) + : base(context, documentStream, xmlDocumentLocation) + { + } + + public DescriptorMarker(LinkContext context, Stream documentStream, EmbeddedResource resource, AssemblyDefinition resourceAssembly, string xmlDocumentLocation = "") + : base(context, documentStream, resource, resourceAssembly, xmlDocumentLocation) + { + } + + public void Mark() + { + bool stripDescriptors = _context.IsOptimizationEnabled(CodeOptimizations.RemoveDescriptors, _resource?.Assembly); + ProcessXml(stripDescriptors, _context.IgnoreDescriptors); + } + + protected override AllowedAssemblies AllowedAssemblySelector { get => AllowedAssemblies.AnyAssembly; } + + protected override void ProcessAssembly(AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes) + { + if (GetTypePreserve(nav) == TypePreserve.All) + { + foreach (var type in assembly.MainModule.Types) + MarkAndPreserveAll(type, nav); + + foreach (var exportedType in assembly.MainModule.ExportedTypes) + _context.MarkingHelpers.MarkExportedType(exportedType, assembly.MainModule, new DependencyInfo(DependencyKind.XmlDescriptor, assembly.MainModule), GetMessageOriginForPosition(nav)); + } + else + { + ProcessTypes(assembly, nav, warnOnUnresolvedTypes); + ProcessNamespaces(assembly, nav); + } + } + + void ProcessNamespaces(AssemblyDefinition assembly, XPathNavigator nav) + { + foreach (XPathNavigator namespaceNav in nav.SelectChildren(NamespaceElementName, XmlNamespace)) + { + if (!ShouldProcessElement(namespaceNav)) + continue; + + string fullname = GetFullName(namespaceNav); + bool foundMatch = false; + foreach (TypeDefinition type in assembly.MainModule.Types) + { + if (type.Namespace != fullname) + continue; + + foundMatch = true; + MarkAndPreserveAll(type, nav); + } + + if (!foundMatch) + { + LogWarning(namespaceNav, DiagnosticId.XmlCouldNotFindAnyTypeInNamespace, fullname); + } + } + } + + void MarkAndPreserveAll(TypeDefinition type, XPathNavigator nav) + { + _context.Annotations.Mark(type, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav)); + _context.Annotations.SetPreserve(type, TypePreserve.All); + + if (!type.HasNestedTypes) + return; + + foreach (TypeDefinition nested in type.NestedTypes) + MarkAndPreserveAll(nested, nav); + } + + protected override TypeDefinition? ProcessExportedType(ExportedType exported, AssemblyDefinition assembly, XPathNavigator nav) + { + _context.MarkingHelpers.MarkExportedType(exported, assembly.MainModule, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav)); + return base.ProcessExportedType(exported, assembly, nav); + } + + protected override void ProcessType(TypeDefinition type, XPathNavigator nav) + { + Debug.Assert(ShouldProcessElement(nav)); + + TypePreserve preserve = GetTypePreserve(nav); + switch (preserve) + { + case TypePreserve.Fields when !type.HasFields: + LogWarning(nav, DiagnosticId.TypeHasNoFieldsToPreserve, type.GetDisplayName()); + break; + + case TypePreserve.Methods when !type.HasMethods: + LogWarning(nav, DiagnosticId.TypeHasNoMethodsToPreserve, type.GetDisplayName()); + break; + + case TypePreserve.Fields: + case TypePreserve.Methods: + case TypePreserve.All: + _context.Annotations.SetPreserve(type, preserve); + break; + } + + bool required = IsRequired(nav); + ProcessTypeChildren(type, nav, required); + + if (!required) + return; + + _context.Annotations.Mark(type, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav)); + + if (type.IsNested) + { + var currentType = type; + while (currentType.IsNested) + { + var parent = currentType.DeclaringType; + _context.Annotations.Mark(parent, new DependencyInfo(DependencyKind.DeclaringType, currentType), GetMessageOriginForPosition(nav)); + currentType = parent; + } + } + } + + static TypePreserve GetTypePreserve(XPathNavigator nav) + { + string attribute = GetAttribute(nav, _preserve); + if (string.IsNullOrEmpty(attribute)) + return nav.HasChildren ? TypePreserve.Nothing : TypePreserve.All; + + if (Enum.TryParse(attribute, true, out TypePreserve result)) + return result; + return TypePreserve.Nothing; + } + + protected override void ProcessField(TypeDefinition type, FieldDefinition field, XPathNavigator nav) + { + if (_context.Annotations.IsMarked(field)) + LogWarning(nav, DiagnosticId.XmlDuplicatePreserveMember, field.FullName); + + _context.Annotations.Mark(field, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav)); + } + + protected override void ProcessMethod(TypeDefinition type, MethodDefinition method, XPathNavigator nav, object? customData) + { + if (_context.Annotations.IsMarked(method)) + LogWarning(nav, DiagnosticId.XmlDuplicatePreserveMember, method.GetDisplayName()); + + _context.Annotations.MarkIndirectlyCalledMethod(method); + _context.Annotations.SetAction(method, MethodAction.Parse); + + if (customData is bool required && !required) + { + _context.Annotations.AddPreservedMethod(type, method); + } + else + { + _context.Annotations.Mark(method, new DependencyInfo(DependencyKind.XmlDescriptor, _xmlDocumentLocation), GetMessageOriginForPosition(nav)); + } + } + + void ProcessMethodIfNotNull(TypeDefinition type, MethodDefinition method, XPathNavigator nav, object? customData) + { + if (method == null) + return; + + ProcessMethod(type, method, nav, customData); + } + + protected override MethodDefinition? GetMethod(TypeDefinition type, string signature) + { + if (type.HasMethods) + foreach (MethodDefinition meth in type.Methods) + if (signature == GetMethodSignature(meth, false)) + return meth; + + return null; + } + + public static string GetMethodSignature(MethodDefinition meth, bool includeGenericParameters) + { + StringBuilder sb = new StringBuilder(); + sb.Append(meth.ReturnType.FullName); + sb.Append(" "); + sb.Append(meth.Name); + if (includeGenericParameters && meth.HasGenericParameters) + { + sb.Append("`"); + sb.Append(meth.GenericParameters.Count); + } + + sb.Append("("); + if (meth.HasParameters) + { + for (int i = 0; i < meth.Parameters.Count; i++) + { + if (i > 0) + sb.Append(","); + + sb.Append(meth.Parameters[i].ParameterType.FullName); + } + } + sb.Append(")"); + return sb.ToString(); + } + + protected override void ProcessEvent(TypeDefinition type, EventDefinition @event, XPathNavigator nav, object? customData) + { + if (_context.Annotations.IsMarked(@event)) + LogWarning(nav, DiagnosticId.XmlDuplicatePreserveMember, @event.FullName); + + ProcessMethod(type, @event.AddMethod, nav, customData); + ProcessMethod(type, @event.RemoveMethod, nav, customData); + ProcessMethodIfNotNull(type, @event.InvokeMethod, nav, customData); + } + + protected override void ProcessProperty(TypeDefinition type, PropertyDefinition property, XPathNavigator nav, object? customData, bool fromSignature) + { + string[] accessors = fromSignature ? GetAccessors(nav) : _accessorsAll; + + if (_context.Annotations.IsMarked(property)) + LogWarning(nav, DiagnosticId.XmlDuplicatePreserveMember, property.FullName); + + if (Array.IndexOf(accessors, "all") >= 0) + { + ProcessMethodIfNotNull(type, property.GetMethod, nav, customData); + ProcessMethodIfNotNull(type, property.SetMethod, nav, customData); + return; + } + + if (property.GetMethod != null && Array.IndexOf(accessors, "get") >= 0) + ProcessMethod(type, property.GetMethod, nav, customData); + else if (property.GetMethod == null) + LogWarning(nav, DiagnosticId.XmlCouldNotFindGetAccesorOfPropertyOnType, property.Name, type.FullName); + + if (property.SetMethod != null && Array.IndexOf(accessors, "set") >= 0) + ProcessMethod(type, property.SetMethod, nav, customData); + else if (property.SetMethod == null) + LogWarning(nav, DiagnosticId.XmlCouldNotFindSetAccesorOfPropertyOnType, property.Name, type.FullName); + } + + static bool IsRequired(XPathNavigator nav) + { + string attribute = GetAttribute(nav, _required); + if (attribute == null || attribute.Length == 0) + return true; + + return bool.TryParse(attribute, out bool result) && result; + } + + protected static string[] GetAccessors(XPathNavigator nav) + { + string accessorsValue = GetAttribute(nav, _accessors); + + if (accessorsValue != null) + { + string[] accessors = accessorsValue.Split( + _accessorsSep, StringSplitOptions.RemoveEmptyEntries); + + if (accessors.Length > 0) + { + for (int i = 0; i < accessors.Length; ++i) + accessors[i] = accessors[i].ToLower(); + + return accessors; + } + } + return _accessorsAll; + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/FeatureSettings.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/FeatureSettings.cs new file mode 100644 index 0000000000000..5e89376022684 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/FeatureSettings.cs @@ -0,0 +1,50 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Xml.XPath; +using ILLink.Shared; + +namespace Mono.Linker +{ + public static class FeatureSettings + { + public static bool ShouldProcessElement(XPathNavigator nav, LinkContext context, string documentLocation) + { + var feature = GetAttribute(nav, "feature"); + if (string.IsNullOrEmpty(feature)) + return true; + + var value = GetAttribute(nav, "featurevalue"); + if (string.IsNullOrEmpty(value)) + { + context.LogError(null, DiagnosticId.XmlFeatureDoesNotSpecifyFeatureValue, documentLocation, feature); + return false; + } + + if (!bool.TryParse(value, out bool bValue)) + { + context.LogError(null, DiagnosticId.XmlUnsupportedNonBooleanValueForFeature, documentLocation, feature); + return false; + } + + var isDefault = GetAttribute(nav, "featuredefault"); + bool bIsDefault = false; + if (!string.IsNullOrEmpty(isDefault) && (!bool.TryParse(isDefault, out bIsDefault) || !bIsDefault)) + { + context.LogError(null, DiagnosticId.XmlDocumentLocationHasInvalidFeatureDefault, documentLocation); + return false; + } + + if (!context.FeatureSettings.TryGetValue(feature, out bool featureSetting)) + return bIsDefault; + + return bValue == featureSetting; + } + + public static string GetAttribute(XPathNavigator nav, string attribute) + { + return nav.GetAttribute(attribute, String.Empty); + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/LinkAttributesParser.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/LinkAttributesParser.cs new file mode 100644 index 0000000000000..0acfdda2dccbe --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/LinkAttributesParser.cs @@ -0,0 +1,578 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Text; +using System.Xml.XPath; +using ILLink.Shared; +using Mono.Cecil; + +namespace Mono.Linker.Steps +{ + public class LinkAttributesParser : ProcessLinkerXmlBase + { + AttributeInfo? _attributeInfo; + + public LinkAttributesParser(LinkContext context, Stream documentStream, string xmlDocumentLocation) + : base(context, documentStream, xmlDocumentLocation) + { + } + + public LinkAttributesParser(LinkContext context, Stream documentStream, EmbeddedResource resource, AssemblyDefinition resourceAssembly, string xmlDocumentLocation = "") + : base(context, documentStream, resource, resourceAssembly, xmlDocumentLocation) + { + } + + public void Parse(AttributeInfo xmlInfo) + { + _attributeInfo = xmlInfo; + bool stripLinkAttributes = _context.IsOptimizationEnabled(CodeOptimizations.RemoveLinkAttributes, _resource?.Assembly); + ProcessXml(stripLinkAttributes, _context.IgnoreLinkAttributes); + } + + CustomAttribute[]? ProcessAttributes(XPathNavigator nav, ICustomAttributeProvider provider) + { + var builder = new ArrayBuilder(); + foreach (XPathNavigator argumentNav in nav.SelectChildren("attribute", string.Empty)) + { + if (!ShouldProcessElement(argumentNav)) + continue; + + TypeDefinition? attributeType; + string internalAttribute = GetAttribute(argumentNav, "internal"); + if (!string.IsNullOrEmpty(internalAttribute)) + { + attributeType = GenerateRemoveAttributeInstancesAttribute(); + if (attributeType == null) + continue; + + // TODO: Replace with IsAttributeType check once we have it + if (provider is not TypeDefinition) + { + LogWarning(argumentNav, DiagnosticId.XmlRemoveAttributeInstancesCanOnlyBeUsedOnType, attributeType.Name); + continue; + } + } + else + { + string attributeFullName = GetFullName(argumentNav); + if (string.IsNullOrEmpty(attributeFullName)) + { + LogWarning(argumentNav, DiagnosticId.XmlElementDoesNotContainRequiredAttributeFullname); + continue; + } + + if (!GetAttributeType(argumentNav, attributeFullName, out attributeType)) + continue; + } + + CustomAttribute? customAttribute = CreateCustomAttribute(argumentNav, attributeType); + if (customAttribute != null) + { + _context.LogMessage($"Assigning external custom attribute '{FormatCustomAttribute(customAttribute)}' instance to '{provider}'."); + builder.Add(customAttribute); + } + } + + return builder.ToArray(); + + static string FormatCustomAttribute(CustomAttribute ca) + { + StringBuilder sb = new StringBuilder(); + sb.Append(ca.Constructor.GetDisplayName()); + sb.Append(" { args: "); + for (int i = 0; i < ca.ConstructorArguments.Count; ++i) + { + if (i > 0) + sb.Append(", "); + + var caa = ca.ConstructorArguments[i]; + sb.Append($"{caa.Type.GetDisplayName()} {caa.Value}"); + } + sb.Append(" }"); + + return sb.ToString(); + } + } + + TypeDefinition? GenerateRemoveAttributeInstancesAttribute() + { + if (_context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition != null) + return _context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition; + + var voidType = BCL.FindPredefinedType("System", "Void", _context); + if (voidType == null) + return null; + + var attributeType = BCL.FindPredefinedType("System", "Attribute", _context); + if (attributeType == null) + return null; + + var objectType = BCL.FindPredefinedType("System", "Object", _context); + if (objectType == null) + return null; + + // + // Generates metadata information for internal type + // + // public sealed class RemoveAttributeInstancesAttribute : Attribute + // { + // public RemoveAttributeInstancesAttribute () {} + // public RemoveAttributeInstancesAttribute (object value1) {} + // } + // + var td = new TypeDefinition("", "RemoveAttributeInstancesAttribute", TypeAttributes.Public); + td.BaseType = attributeType; + + const MethodAttributes ctorAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.Final; + var ctor = new MethodDefinition(".ctor", ctorAttributes, voidType); + td.Methods.Add(ctor); + + ctor = new MethodDefinition(".ctor", ctorAttributes, voidType); + ctor.Parameters.Add(new ParameterDefinition(objectType)); + td.Methods.Add(ctor); + + return _context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition = td; + } + + CustomAttribute? CreateCustomAttribute(XPathNavigator nav, TypeDefinition attributeType) + { + CustomAttributeArgument[] arguments = ReadCustomAttributeArguments(nav, attributeType); + + MethodDefinition? constructor = FindBestMatchingConstructor(attributeType, arguments); + if (constructor == null) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindMatchingConstructorForCustomAttribute, attributeType.GetDisplayName()); + return null; + } + + CustomAttribute customAttribute = new CustomAttribute(constructor); + foreach (var argument in arguments) + customAttribute.ConstructorArguments.Add(argument); + + ReadCustomAttributeProperties(nav, attributeType, customAttribute); + + return customAttribute; + } + + MethodDefinition? FindBestMatchingConstructor(TypeDefinition attributeType, CustomAttributeArgument[] args) + { + var methods = attributeType.Methods; + for (int i = 0; i < attributeType.Methods.Count; ++i) + { + var m = methods[i]; + if (!m.IsInstanceConstructor()) + continue; + + var p = m.Parameters; + if (args.Length != p.Count) + continue; + + bool match = true; + for (int ii = 0; match && ii != args.Length; ++ii) + { + // + // No candidates betterness, only exact matches are supported + // + var parameterType = _context.TryResolve(p[ii].ParameterType); + if (parameterType == null || parameterType != _context.TryResolve(args[ii].Type)) + match = false; + } + + if (match) + return m; + } + + return null; + } + + void ReadCustomAttributeProperties(XPathNavigator nav, TypeDefinition attributeType, CustomAttribute customAttribute) + { + foreach (XPathNavigator propertyNav in nav.SelectChildren("property", string.Empty)) + { + string propertyName = GetName(propertyNav); + if (string.IsNullOrEmpty(propertyName)) + { + LogWarning(propertyNav, DiagnosticId.XmlPropertyDoesNotContainAttributeName); + continue; + } + + PropertyDefinition? property = attributeType.Properties.Where(prop => prop.Name == propertyName).FirstOrDefault(); + if (property == null) + { + LogWarning(propertyNav, DiagnosticId.XmlCouldNotFindProperty, propertyName); + continue; + } + + var caa = ReadCustomAttributeArgument(propertyNav, property); + if (caa is null) + continue; + + customAttribute.Properties.Add(new CustomAttributeNamedArgument(property.Name, caa.Value)); + } + } + + CustomAttributeArgument[] ReadCustomAttributeArguments(XPathNavigator nav, TypeDefinition attributeType) + { + var args = new ArrayBuilder(); + + foreach (XPathNavigator argumentNav in nav.SelectChildren("argument", string.Empty)) + { + CustomAttributeArgument? caa = ReadCustomAttributeArgument(argumentNav, attributeType); + if (caa is not null) + args.Add(caa.Value); + } + + return args.ToArray() ?? Array.Empty(); + } + + CustomAttributeArgument? ReadCustomAttributeArgument(XPathNavigator nav, IMemberDefinition memberWithAttribute) + { + TypeReference? typeref = ResolveArgumentType(nav, memberWithAttribute); + if (typeref is null) + return null; + + string svalue = nav.Value; + + // + // Builds CustomAttributeArgument in the same way as it would be + // represented in the metadata if encoded there. This simplifies + // any custom attributes handling in linker by using same attributes + // value extraction or mathing logic. + // + switch (typeref.MetadataType) + { + case MetadataType.Object: + var argumentIterator = nav.SelectChildren("argument", string.Empty); + if (argumentIterator?.MoveNext() != true) + { + _context.LogError(null, DiagnosticId.CustomAttributeArgumentForTypeRequiresNestedNode, "System.Object", "argument"); + return null; + } + + var typedef = _context.TryResolve(typeref); + if (typedef == null) + return null; + + var boxedValue = ReadCustomAttributeArgument(argumentIterator.Current!, typedef); + if (boxedValue is null) + return null; + + return new CustomAttributeArgument(typeref, boxedValue); + + case MetadataType.Char: + case MetadataType.Byte: + case MetadataType.SByte: + case MetadataType.Int16: + case MetadataType.UInt16: + case MetadataType.Int32: + case MetadataType.UInt32: + case MetadataType.UInt64: + case MetadataType.Int64: + case MetadataType.String: + return new CustomAttributeArgument(typeref, ConvertStringValue(svalue, typeref)); + + case MetadataType.ValueType: + var enumType = _context.Resolve(typeref); + if (enumType?.IsEnum != true) + goto default; + + var enumField = enumType.Fields.Where(f => f.IsStatic && f.Name == svalue).FirstOrDefault(); + object evalue = enumField?.Constant ?? svalue; + + typeref = enumType.GetEnumUnderlyingType(); + return new CustomAttributeArgument(enumType, ConvertStringValue(evalue, typeref)); + + case MetadataType.Class: + if (!typeref.IsTypeOf("System", "Type")) + goto default; + + if (!_context.TypeNameResolver.TryResolveTypeName(svalue, memberWithAttribute, out TypeReference? type, out _)) + { + _context.LogError(GetMessageOriginForPosition(nav), DiagnosticId.CouldNotResolveCustomAttributeTypeValue, svalue); + return null; + } + + return new CustomAttributeArgument(typeref, type); + default: + // No support for null and arrays, consider adding - dotnet/linker/issues/1957 + _context.LogError(GetMessageOriginForPosition(nav), DiagnosticId.UnexpectedAttributeArgumentType, typeref.GetDisplayName()); + return null; + } + + TypeReference? ResolveArgumentType(XPathNavigator nav, IMemberDefinition memberWithAttribute) + { + string typeName = GetAttribute(nav, "type"); + if (string.IsNullOrEmpty(typeName)) + typeName = "System.String"; + + if (!_context.TypeNameResolver.TryResolveTypeName(typeName, memberWithAttribute, out TypeReference? typeref, out _)) + { + _context.LogError(GetMessageOriginForPosition(nav), DiagnosticId.TypeUsedWithAttributeValueCouldNotBeFound, typeName, nav.Value); + return null; + } + + return typeref; + } + } + + object? ConvertStringValue(object value, TypeReference targetType) + { + TypeCode typeCode; + switch (targetType.MetadataType) + { + case MetadataType.String: + typeCode = TypeCode.String; + break; + case MetadataType.Char: + typeCode = TypeCode.Char; + break; + case MetadataType.Byte: + typeCode = TypeCode.Byte; + break; + case MetadataType.SByte: + typeCode = TypeCode.SByte; + break; + case MetadataType.Int16: + typeCode = TypeCode.Int16; + break; + case MetadataType.UInt16: + typeCode = TypeCode.UInt16; + break; + case MetadataType.Int32: + typeCode = TypeCode.Int32; + break; + case MetadataType.UInt32: + typeCode = TypeCode.UInt32; + break; + case MetadataType.UInt64: + typeCode = TypeCode.UInt64; + break; + case MetadataType.Int64: + typeCode = TypeCode.Int64; + break; + case MetadataType.Boolean: + typeCode = TypeCode.Boolean; + break; + case MetadataType.Single: + typeCode = TypeCode.Single; + break; + case MetadataType.Double: + typeCode = TypeCode.Double; + break; + default: + throw new NotSupportedException(targetType.ToString()); + } + + try + { + return Convert.ChangeType(value, typeCode); + } + catch + { + _context.LogError(null, DiagnosticId.CannotConverValueToType, value.ToString() ?? "", targetType.GetDisplayName()); + return null; + } + } + + bool GetAttributeType(XPathNavigator nav, string attributeFullName, [NotNullWhen(true)] out TypeDefinition? attributeType) + { + string assemblyName = GetAttribute(nav, "assembly"); + if (string.IsNullOrEmpty(assemblyName)) + { + attributeType = _context.GetType(attributeFullName); + } + else + { + AssemblyDefinition? assembly; + try + { + assembly = _context.TryResolve(AssemblyNameReference.Parse(assemblyName)); + if (assembly == null) + { + LogWarning(nav, DiagnosticId.XmlCouldNotResolveAssemblyForAttribute, assemblyName, attributeFullName); + + attributeType = default; + return false; + } + } + catch (Exception) + { + LogWarning(nav, DiagnosticId.XmlCouldNotResolveAssemblyForAttribute, assemblyName, attributeFullName); + attributeType = default; + return false; + } + + attributeType = _context.TryResolve(assembly, attributeFullName); + } + + if (attributeType == null) + { + LogWarning(nav, DiagnosticId.XmlAttributeTypeCouldNotBeFound, attributeFullName); + return false; + } + + return true; + } + + protected override AllowedAssemblies AllowedAssemblySelector + { + get + { + if (_resource?.Assembly == null) + return AllowedAssemblies.AllAssemblies; + + // Corelib XML may contain assembly wildcard to support compiler-injected attribute types + if (_resource?.Assembly.Name.Name == PlatformAssemblies.CoreLib) + return AllowedAssemblies.AllAssemblies; + + return AllowedAssemblies.ContainingAssembly; + } + } + + protected override void ProcessAssembly(AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes) + { + PopulateAttributeInfo(assembly, nav); + ProcessTypes(assembly, nav, warnOnUnresolvedTypes); + } + + protected override void ProcessType(TypeDefinition type, XPathNavigator nav) + { + Debug.Assert(ShouldProcessElement(nav)); + + PopulateAttributeInfo(type, nav); + ProcessTypeChildren(type, nav); + + if (!type.HasNestedTypes) + return; + + foreach (XPathNavigator nestedTypeNav in nav.SelectChildren("type", string.Empty)) + { + foreach (TypeDefinition nested in type.NestedTypes) + { + if (nested.Name == GetAttribute(nestedTypeNav, "name") && ShouldProcessElement(nestedTypeNav)) + ProcessType(nested, nestedTypeNav); + } + } + } + + protected override void ProcessField(TypeDefinition type, FieldDefinition field, XPathNavigator nav) + { + PopulateAttributeInfo(field, nav); + } + + protected override void ProcessMethod(TypeDefinition type, MethodDefinition method, XPathNavigator nav, object? customData) + { + PopulateAttributeInfo(method, nav); + ProcessReturnParameters(method, nav); + ProcessParameters(method, nav); + } + + void ProcessParameters(MethodDefinition method, XPathNavigator nav) + { + Debug.Assert(_attributeInfo != null); + foreach (XPathNavigator parameterNav in nav.SelectChildren("parameter", string.Empty)) + { + var attributes = ProcessAttributes(parameterNav, method); + if (attributes != null) + { + string paramName = GetAttribute(parameterNav, "name"); + foreach (ParameterDefinition parameter in method.Parameters) + { + if (paramName == parameter.Name) + { + if (parameter.HasCustomAttributes || _attributeInfo.CustomAttributes.ContainsKey(parameter)) + LogWarning(parameterNav, DiagnosticId.XmlMoreThanOneValyForParameterOfMethod, paramName, method.GetDisplayName()); + _attributeInfo.AddCustomAttributes(parameter, attributes); + break; + } + } + } + } + } + + void ProcessReturnParameters(MethodDefinition method, XPathNavigator nav) + { + bool firstAppearance = true; + foreach (XPathNavigator returnNav in nav.SelectChildren("return", string.Empty)) + { + if (firstAppearance) + { + firstAppearance = false; + PopulateAttributeInfo(method.MethodReturnType, returnNav); + } + else + { + LogWarning(returnNav, DiagnosticId.XmlMoreThanOneReturnElementForMethod, method.GetDisplayName()); + } + } + } + + protected override MethodDefinition? GetMethod(TypeDefinition type, string signature) + { + if (type.HasMethods) + foreach (MethodDefinition method in type.Methods) + if (signature.Replace(" ", "") == GetMethodSignature(method) || signature.Replace(" ", "") == GetMethodSignature(method, true)) + return method; + + return null; + } + + static string GetMethodSignature(MethodDefinition method, bool includeReturnType = false) + { + StringBuilder sb = new StringBuilder(); + if (includeReturnType) + { + sb.Append(method.ReturnType.FullName); + } + sb.Append(method.Name); + if (method.HasGenericParameters) + { + sb.Append("<"); + for (int i = 0; i < method.GenericParameters.Count; i++) + { + if (i > 0) + sb.Append(","); + + sb.Append(method.GenericParameters[i].Name); + } + sb.Append(">"); + } + sb.Append("("); + if (method.HasParameters) + { + for (int i = 0; i < method.Parameters.Count; i++) + { + if (i > 0) + sb.Append(","); + + sb.Append(method.Parameters[i].ParameterType.FullName); + } + } + sb.Append(")"); + return sb.ToString(); + } + + protected override void ProcessProperty(TypeDefinition type, PropertyDefinition property, XPathNavigator nav, object? customData, bool fromSignature) + { + PopulateAttributeInfo(property, nav); + } + + protected override void ProcessEvent(TypeDefinition type, EventDefinition @event, XPathNavigator nav, object? customData) + { + PopulateAttributeInfo(@event, nav); + } + + void PopulateAttributeInfo(ICustomAttributeProvider provider, XPathNavigator nav) + { + Debug.Assert(_attributeInfo != null); + var attributes = ProcessAttributes(nav, provider); + if (attributes != null) + _attributeInfo.AddCustomAttributes(provider, attributes); + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/ProcessLinkerXmlBase.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/ProcessLinkerXmlBase.cs new file mode 100644 index 0000000000000..842c56639fdd0 --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/ProcessLinkerXmlBase.cs @@ -0,0 +1,662 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Linq; +using System.Xml.XPath; +using ILLink.Shared; +using Mono.Cecil; + +namespace Mono.Linker.Steps +{ + [Flags] + public enum AllowedAssemblies + { + ContainingAssembly = 0x1, + AnyAssembly = 0x2 | ContainingAssembly, + AllAssemblies = 0x4 | AnyAssembly + } + + public abstract class ProcessLinkerXmlBase + { + const string FullNameAttributeName = "fullname"; + const string LinkerElementName = "linker"; + const string TypeElementName = "type"; + const string SignatureAttributeName = "signature"; + const string NameAttributeName = "name"; + const string FieldElementName = "field"; + const string MethodElementName = "method"; + const string EventElementName = "event"; + const string PropertyElementName = "property"; + const string AllAssembliesFullName = "*"; + protected const string XmlNamespace = ""; + + protected readonly string _xmlDocumentLocation; + readonly XPathNavigator _document; + protected readonly (EmbeddedResource Resource, AssemblyDefinition Assembly)? _resource; + protected readonly LinkContext _context; + + protected ProcessLinkerXmlBase(LinkContext context, Stream documentStream, string xmlDocumentLocation) + { + _context = context; + using (documentStream) + { + _document = XDocument.Load(documentStream, LoadOptions.SetLineInfo).CreateNavigator(); + } + _xmlDocumentLocation = xmlDocumentLocation; + } + + protected ProcessLinkerXmlBase(LinkContext context, Stream documentStream, EmbeddedResource resource, AssemblyDefinition resourceAssembly, string xmlDocumentLocation) + : this(context, documentStream, xmlDocumentLocation) + { + _resource = ( + resource ?? throw new ArgumentNullException(nameof(resource)), + resourceAssembly ?? throw new ArgumentNullException(nameof(resourceAssembly)) + ); + } + + protected virtual bool ShouldProcessElement(XPathNavigator nav) => FeatureSettings.ShouldProcessElement(nav, _context, _xmlDocumentLocation); + + protected virtual void ProcessXml(bool stripResource, bool ignoreResource) + { + if (!AllowedAssemblySelector.HasFlag(AllowedAssemblies.AnyAssembly) && _resource == null) + throw new InvalidOperationException("The containing assembly must be specified for XML which is restricted to modifying that assembly only."); + + try + { + XPathNavigator nav = _document.CreateNavigator(); + + // Initial structure check - ignore XML document which don't look like linker XML format + if (!nav.MoveToChild(LinkerElementName, XmlNamespace)) + return; + + if (_resource != null) + { + if (stripResource) + _context.Annotations.AddResourceToRemove(_resource.Value.Assembly, _resource.Value.Resource); + if (ignoreResource) + return; + } + + if (!ShouldProcessElement(nav)) + return; + + ProcessAssemblies(nav); + + // For embedded XML, allow not specifying the assembly explicitly in XML. + if (_resource != null) + ProcessAssembly(_resource.Value.Assembly, nav, warnOnUnresolvedTypes: true); + + } + catch (Exception ex) when (!(ex is LinkerFatalErrorException)) + { + throw new LinkerFatalErrorException(MessageContainer.CreateErrorMessage(null, DiagnosticId.ErrorProcessingXmlLocation, _xmlDocumentLocation), ex); + } + } + + protected virtual AllowedAssemblies AllowedAssemblySelector { get => _resource != null ? AllowedAssemblies.ContainingAssembly : AllowedAssemblies.AnyAssembly; } + + bool ShouldProcessAllAssemblies(XPathNavigator nav, [NotNullWhen(false)] out AssemblyNameReference? assemblyName) + { + assemblyName = null; + if (GetFullName(nav) == AllAssembliesFullName) + return true; + + assemblyName = GetAssemblyName(nav); + return false; + } + + protected virtual void ProcessAssemblies(XPathNavigator nav) + { + foreach (XPathNavigator assemblyNav in nav.SelectChildren("assembly", "")) + { + // Errors for invalid assembly names should show up even if this element will be + // skipped due to feature conditions. + bool processAllAssemblies = ShouldProcessAllAssemblies(assemblyNav, out AssemblyNameReference? name); + if (processAllAssemblies && AllowedAssemblySelector != AllowedAssemblies.AllAssemblies) + { + LogWarning(assemblyNav, DiagnosticId.XmlUnsuportedWildcard); + continue; + } + + AssemblyDefinition? assemblyToProcess = null; + if (!AllowedAssemblySelector.HasFlag(AllowedAssemblies.AnyAssembly)) + { + Debug.Assert(!processAllAssemblies); + Debug.Assert(_resource != null); + if (_resource.Value.Assembly.Name.Name != name!.Name) + { + LogWarning(assemblyNav, DiagnosticId.AssemblyWithEmbeddedXmlApplyToAnotherAssembly, _resource.Value.Assembly.Name.Name, name.ToString()); + continue; + } + assemblyToProcess = _resource.Value.Assembly; + } + + if (!ShouldProcessElement(assemblyNav)) + continue; + + if (processAllAssemblies) + { + // We could avoid loading all references in this case: https://github.com/dotnet/linker/issues/1708 + foreach (AssemblyDefinition assembly in _context.GetReferencedAssemblies()) + ProcessAssembly(assembly, assemblyNav, warnOnUnresolvedTypes: false); + } + else + { + Debug.Assert(!processAllAssemblies); + AssemblyDefinition? assembly = assemblyToProcess ?? _context.TryResolve(name!); + + if (assembly == null) + { + LogWarning(assemblyNav, DiagnosticId.XmlCouldNotResolveAssembly, name!.Name); + continue; + } + + ProcessAssembly(assembly, assemblyNav, warnOnUnresolvedTypes: true); + } + } + } + + protected abstract void ProcessAssembly(AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes); + + protected virtual void ProcessTypes(AssemblyDefinition assembly, XPathNavigator nav, bool warnOnUnresolvedTypes) + { + foreach (XPathNavigator typeNav in nav.SelectChildren(TypeElementName, XmlNamespace)) + { + + if (!ShouldProcessElement(typeNav)) + continue; + + string fullname = GetFullName(typeNav); + + if (fullname.IndexOf("*") != -1) + { + if (ProcessTypePattern(fullname, assembly, typeNav)) + continue; + } + + TypeDefinition type = assembly.MainModule.GetType(fullname); + + if (type == null && assembly.MainModule.HasExportedTypes) + { + foreach (var exported in assembly.MainModule.ExportedTypes) + { + if (fullname == exported.FullName) + { + var resolvedExternal = ProcessExportedType(exported, assembly, typeNav); + if (resolvedExternal != null) + { + type = resolvedExternal; + break; + } + } + } + } + + if (type == null) + { + if (warnOnUnresolvedTypes) + LogWarning(typeNav, DiagnosticId.XmlCouldNotResolveType, fullname); + continue; + } + + ProcessType(type, typeNav); + } + } + + protected virtual TypeDefinition? ProcessExportedType(ExportedType exported, AssemblyDefinition assembly, XPathNavigator nav) => exported.Resolve(); + + void MatchType(TypeDefinition type, Regex regex, XPathNavigator nav) + { + if (regex.Match(type.FullName).Success) + ProcessType(type, nav); + + if (!type.HasNestedTypes) + return; + + foreach (var nt in type.NestedTypes) + MatchType(nt, regex, nav); + } + + protected virtual bool ProcessTypePattern(string fullname, AssemblyDefinition assembly, XPathNavigator nav) + { + Regex regex = new Regex(fullname.Replace(".", @"\.").Replace("*", "(.*)")); + + foreach (TypeDefinition type in assembly.MainModule.Types) + { + MatchType(type, regex, nav); + } + + if (assembly.MainModule.HasExportedTypes) + { + foreach (var exported in assembly.MainModule.ExportedTypes) + { + if (regex.Match(exported.FullName).Success) + { + var type = ProcessExportedType(exported, assembly, nav); + if (type != null) + { + ProcessType(type, nav); + } + } + } + } + + return true; + } + + protected abstract void ProcessType(TypeDefinition type, XPathNavigator nav); + + protected void ProcessTypeChildren(TypeDefinition type, XPathNavigator nav, object? customData = null) + { + if (nav.HasChildren) + { + ProcessSelectedFields(nav, type); + ProcessSelectedMethods(nav, type, customData); + ProcessSelectedEvents(nav, type, customData); + ProcessSelectedProperties(nav, type, customData); + } + } + + void ProcessSelectedFields(XPathNavigator nav, TypeDefinition type) + { + foreach (XPathNavigator fieldNav in nav.SelectChildren(FieldElementName, XmlNamespace)) + { + if (!ShouldProcessElement(fieldNav)) + continue; + ProcessField(type, fieldNav); + } + } + + protected virtual void ProcessField(TypeDefinition type, XPathNavigator nav) + { + string signature = GetSignature(nav); + if (!String.IsNullOrEmpty(signature)) + { + FieldDefinition? field = GetField(type, signature); + if (field == null) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindFieldOnType, signature, type.GetDisplayName()); + return; + } + + ProcessField(type, field, nav); + } + + string name = GetName(nav); + if (!String.IsNullOrEmpty(name)) + { + bool foundMatch = false; + if (type.HasFields) + { + foreach (FieldDefinition field in type.Fields) + { + if (field.Name == name) + { + foundMatch = true; + ProcessField(type, field, nav); + } + } + } + + if (!foundMatch) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindFieldOnType, name, type.GetDisplayName()); + } + } + } + + protected static FieldDefinition? GetField(TypeDefinition type, string signature) + { + if (!type.HasFields) + return null; + + foreach (FieldDefinition field in type.Fields) + if (signature == field.FieldType.FullName + " " + field.Name) + return field; + + return null; + } + + protected virtual void ProcessField(TypeDefinition type, FieldDefinition field, XPathNavigator nav) { } + + void ProcessSelectedMethods(XPathNavigator nav, TypeDefinition type, object? customData) + { + foreach (XPathNavigator methodNav in nav.SelectChildren(MethodElementName, XmlNamespace)) + { + if (!ShouldProcessElement(methodNav)) + continue; + ProcessMethod(type, methodNav, customData); + } + } + + protected virtual void ProcessMethod(TypeDefinition type, XPathNavigator nav, object? customData) + { + string signature = GetSignature(nav); + if (!String.IsNullOrEmpty(signature)) + { + MethodDefinition? method = GetMethod(type, signature); + if (method == null) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindMethodOnType, signature, type.GetDisplayName()); + return; + } + + ProcessMethod(type, method, nav, customData); + } + + string name = GetAttribute(nav, NameAttributeName); + if (!String.IsNullOrEmpty(name)) + { + bool foundMatch = false; + if (type.HasMethods) + { + foreach (MethodDefinition method in type.Methods) + { + if (name == method.Name) + { + foundMatch = true; + ProcessMethod(type, method, nav, customData); + } + } + } + + if (!foundMatch) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindMethodOnType, name, type.GetDisplayName()); + } + } + } + + protected virtual MethodDefinition? GetMethod(TypeDefinition type, string signature) => null; + + protected virtual void ProcessMethod(TypeDefinition type, MethodDefinition method, XPathNavigator nav, object? customData) { } + + void ProcessSelectedEvents(XPathNavigator nav, TypeDefinition type, object? customData) + { + foreach (XPathNavigator eventNav in nav.SelectChildren(EventElementName, XmlNamespace)) + { + if (!ShouldProcessElement(eventNav)) + continue; + ProcessEvent(type, eventNav, customData); + } + } + + protected virtual void ProcessEvent(TypeDefinition type, XPathNavigator nav, object? customData) + { + string signature = GetSignature(nav); + if (!String.IsNullOrEmpty(signature)) + { + EventDefinition? @event = GetEvent(type, signature); + if (@event == null) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindEventOnType, signature, type.GetDisplayName()); + return; + } + + ProcessEvent(type, @event, nav, customData); + } + + string name = GetAttribute(nav, NameAttributeName); + if (!String.IsNullOrEmpty(name)) + { + bool foundMatch = false; + foreach (EventDefinition @event in type.Events) + { + if (@event.Name == name) + { + foundMatch = true; + ProcessEvent(type, @event, nav, customData); + } + } + + if (!foundMatch) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindEventOnType, name, type.GetDisplayName()); + } + } + } + + protected static EventDefinition? GetEvent(TypeDefinition type, string signature) + { + if (!type.HasEvents) + return null; + + foreach (EventDefinition @event in type.Events) + if (signature == @event.EventType.FullName + " " + @event.Name) + return @event; + + return null; + } + + protected virtual void ProcessEvent(TypeDefinition type, EventDefinition @event, XPathNavigator nav, object? customData) { } + + void ProcessSelectedProperties(XPathNavigator nav, TypeDefinition type, object? customData) + { + foreach (XPathNavigator propertyNav in nav.SelectChildren(PropertyElementName, XmlNamespace)) + { + if (!ShouldProcessElement(propertyNav)) + continue; + ProcessProperty(type, propertyNav, customData); + } + } + + protected virtual void ProcessProperty(TypeDefinition type, XPathNavigator nav, object? customData) + { + string signature = GetSignature(nav); + if (!String.IsNullOrEmpty(signature)) + { + PropertyDefinition? property = GetProperty(type, signature); + if (property == null) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindPropertyOnType, signature, type.GetDisplayName()); + return; + } + + ProcessProperty(type, property, nav, customData, true); + } + + string name = GetAttribute(nav, NameAttributeName); + if (!String.IsNullOrEmpty(name)) + { + bool foundMatch = false; + foreach (PropertyDefinition property in type.Properties) + { + if (property.Name == name) + { + foundMatch = true; + ProcessProperty(type, property, nav, customData, false); + } + } + + if (!foundMatch) + { + LogWarning(nav, DiagnosticId.XmlCouldNotFindPropertyOnType, name, type.GetDisplayName()); + } + } + } + + protected static PropertyDefinition? GetProperty(TypeDefinition type, string signature) + { + if (!type.HasProperties) + return null; + + foreach (PropertyDefinition property in type.Properties) + if (signature == property.PropertyType.FullName + " " + property.Name) + return property; + + return null; + } + + protected virtual void ProcessProperty(TypeDefinition type, PropertyDefinition property, XPathNavigator nav, object? customData, bool fromSignature) { } + + protected virtual AssemblyNameReference GetAssemblyName(XPathNavigator nav) + { + return AssemblyNameReference.Parse(GetFullName(nav)); + } + + protected static string GetFullName(XPathNavigator nav) + { + return GetAttribute(nav, FullNameAttributeName); + } + + protected static string GetName(XPathNavigator nav) + { + return GetAttribute(nav, NameAttributeName); + } + + protected static string GetSignature(XPathNavigator nav) + { + return GetAttribute(nav, SignatureAttributeName); + } + + protected static string GetAttribute(XPathNavigator nav, string attribute) + { + return nav.GetAttribute(attribute, XmlNamespace); + } + + protected MessageOrigin GetMessageOriginForPosition(XPathNavigator position) + { + return (position is IXmlLineInfo lineInfo) + ? new MessageOrigin(_xmlDocumentLocation, lineInfo.LineNumber, lineInfo.LinePosition, _resource?.Assembly) + : new MessageOrigin(_xmlDocumentLocation, 0, 0, _resource?.Assembly); + } + protected void LogWarning(string message, int warningCode, XPathNavigator position) + { + _context.LogWarning(message, warningCode, GetMessageOriginForPosition(position)); + } + + protected void LogWarning(XPathNavigator position, DiagnosticId id, params string[] args) + { + _context.LogWarning(GetMessageOriginForPosition(position), id, args); + } + + public override string ToString() => GetType().Name + ": " + _xmlDocumentLocation; + + public bool TryConvertValue(string value, TypeReference target, out object? result) + { + switch (target.MetadataType) + { + case MetadataType.Boolean: + if (bool.TryParse(value, out bool bvalue)) + { + result = bvalue ? 1 : 0; + return true; + } + + goto case MetadataType.Int32; + + case MetadataType.Byte: + if (!byte.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out byte byteresult)) + break; + + result = (int)byteresult; + return true; + + case MetadataType.SByte: + if (!sbyte.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out sbyte sbyteresult)) + break; + + result = (int)sbyteresult; + return true; + + case MetadataType.Int16: + if (!short.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out short shortresult)) + break; + + result = (int)shortresult; + return true; + + case MetadataType.UInt16: + if (!ushort.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out ushort ushortresult)) + break; + + result = (int)ushortresult; + return true; + + case MetadataType.Int32: + if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int iresult)) + break; + + result = iresult; + return true; + + case MetadataType.UInt32: + if (!uint.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out uint uresult)) + break; + + result = (int)uresult; + return true; + + case MetadataType.Double: + if (!double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double dresult)) + break; + + result = dresult; + return true; + + case MetadataType.Single: + if (!float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float fresult)) + break; + + result = fresult; + return true; + + case MetadataType.Int64: + if (!long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out long lresult)) + break; + + result = lresult; + return true; + + case MetadataType.UInt64: + if (!ulong.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out ulong ulresult)) + break; + + result = (long)ulresult; + return true; + + case MetadataType.Char: + if (!char.TryParse(value, out char chresult)) + break; + + result = (int)chresult; + return true; + + case MetadataType.String: + if (value is string || value == null) + { + result = value; + return true; + } + + break; + + case MetadataType.ValueType: + if (value is string && + _context.TryResolve(target) is TypeDefinition typeDefinition && + typeDefinition.IsEnum) + { + var enumField = typeDefinition.Fields.Where(f => f.IsStatic && f.Name == value).FirstOrDefault(); + if (enumField != null) + { + result = Convert.ToInt32(enumField.Constant); + return true; + } + } + + break; + } + + result = null; + return false; + } + } +} diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/README.md b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/README.md new file mode 100644 index 0000000000000..a75e53a1f949a --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/ReferenceSource/README.md @@ -0,0 +1 @@ +Sources taken from https://github.com/dotnet/linker/tree/c4abaf33f967a8fa42eb20fc386b774ad74ef319/src/linker/Linker.Steps. diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedInteropStubManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedInteropStubManager.cs index 9aa675ca738fc..fe42b62526b77 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedInteropStubManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedInteropStubManager.cs @@ -5,7 +5,9 @@ using Internal.TypeSystem; using Internal.TypeSystem.Interop; +using ILCompiler.Dataflow; using ILCompiler.DependencyAnalysis; +using ILLink.Shared; using Debug = System.Diagnostics.Debug; using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; @@ -18,9 +20,12 @@ namespace ILCompiler /// public class UsageBasedInteropStubManager : CompilerGeneratedInteropStubManager { - public UsageBasedInteropStubManager(InteropStateManager interopStateManager, PInvokeILEmitterConfiguration pInvokeILEmitterConfiguration) + private Logger _logger; + + public UsageBasedInteropStubManager(InteropStateManager interopStateManager, PInvokeILEmitterConfiguration pInvokeILEmitterConfiguration, Logger logger) : base(interopStateManager, pInvokeILEmitterConfiguration) { + _logger = logger; } public override void AddDependeciesDueToPInvoke(ref DependencyList dependencies, NodeFactory factory, MethodDesc method) @@ -30,11 +35,11 @@ public override void AddDependeciesDueToPInvoke(ref DependencyList dependencies, dependencies = dependencies ?? new DependencyList(); MethodSignature methodSig = method.Signature; - AddParameterMarshallingDependencies(ref dependencies, factory, methodSig.ReturnType); + AddParameterMarshallingDependencies(ref dependencies, factory, method, methodSig.ReturnType); for (int i = 0; i < methodSig.Length; i++) { - AddParameterMarshallingDependencies(ref dependencies, factory, methodSig[i]); + AddParameterMarshallingDependencies(ref dependencies, factory, method, methodSig[i]); } } @@ -45,13 +50,37 @@ public override void AddDependeciesDueToPInvoke(ref DependencyList dependencies, } } - private static void AddParameterMarshallingDependencies(ref DependencyList dependencies, NodeFactory factory, TypeDesc type) + private void AddParameterMarshallingDependencies(ref DependencyList dependencies, NodeFactory factory, MethodDesc method, TypeDesc type) { if (type.IsDelegate) { dependencies.Add(factory.DelegateMarshallingData((DefType)type), "Delegate marshaling"); } + TypeSystemContext context = type.Context; + if ((type.IsWellKnownType(WellKnownType.MulticastDelegate) + || type == context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType)) + { + // If we hit this p/invoke as part of delegate marshalling (i.e. this is a delegate + // that has another delegate in the signature), blame the delegate type, not the marshalling thunk. + // This should ideally warn from the use site (e.g. where GetDelegateForFunctionPointer + // is called) but it's currently hard to get a warning from those spots and this guarantees + // we won't miss a spot (e.g. a p/invoke that has a delegate and that delegate contains + // a System.Delegate parameter). + MethodDesc reportedMethod = method; + if (reportedMethod is Internal.IL.Stubs.DelegateMarshallingMethodThunk delegateThunkMethod) + { + reportedMethod = delegateThunkMethod.InvokeMethod; + } + + var message = new DiagnosticString(DiagnosticId.CorrectnessOfAbstractDelegatesCannotBeGuaranteed).GetMessage(DiagnosticUtilities.GetMethodSignatureDisplayName(method)); + _logger.LogWarning( + message, + (int)DiagnosticId.CorrectnessOfAbstractDelegatesCannotBeGuaranteed, + reportedMethod, + MessageSubCategory.AotAnalysis); + } + // struct may contain delegate fields, hence we need to add dependencies for it if (type.IsByRef) type = ((ParameterizedType)type).ParameterType; @@ -63,7 +92,7 @@ private static void AddParameterMarshallingDependencies(ref DependencyList depen if (field.IsStatic) continue; - AddParameterMarshallingDependencies(ref dependencies, factory, field.FieldType); + AddParameterMarshallingDependencies(ref dependencies, factory, method, field.FieldType); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs index bd649904129bf..439d4e014e6db 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/UsageBasedMetadataManager.cs @@ -973,7 +973,7 @@ public AssemblyFeatureInfo(EcmaModule module, IReadOnlyDictionary } } - private class LinkAttributesReader : ProcessLinkerXmlBase + private class LinkAttributesReader : ProcessXmlBase { private readonly HashSet _removedAttributes; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj index 3420564b0715e..d2df0a825ca40 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/ILCompiler.Compiler.csproj @@ -373,6 +373,7 @@ + @@ -527,6 +528,7 @@ + diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ArgIterator.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ArgIterator.cs index b9671aa485022..28d10f23a28f0 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ArgIterator.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ArgIterator.cs @@ -1606,9 +1606,8 @@ private void ForceSigWalk() int byteArgSize = GetArgSize(); - // Composites greater than 16bytes are passed by reference - TypeHandle dummy; - if (GetArgType(out dummy) == CorElementType.ELEMENT_TYPE_VALUETYPE && GetArgSize() > _transitionBlock.EnregisteredParamTypeMaxSize) + // On ARM64 some composites are implicitly passed by reference. + if (IsArgPassedByRef()) { byteArgSize = _transitionBlock.PointerSize; } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunHashCode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunHashCode.cs index e506bb8b3b6ef..9380a829b8f3c 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunHashCode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/ReadyToRunHashCode.cs @@ -34,10 +34,10 @@ public static int NameHashCode(string name) byte[] src = Encoding.UTF8.GetBytes(name); for (int i = 0; i < src.Length; i += 2) { - hash1 = unchecked(hash1 + RotateLeft(hash1, 5)) ^ src[i]; + hash1 = unchecked(hash1 + RotateLeft(hash1, 5)) ^ (int)unchecked((sbyte)src[i]); if (i + 1 < src.Length) { - hash2 = unchecked(hash2 + RotateLeft(hash2, 5)) ^ src[i + 1]; + hash2 = unchecked(hash2 + RotateLeft(hash2, 5)) ^ (int)unchecked((sbyte)src[i + 1]); } else { diff --git a/src/coreclr/tools/aot/ILCompiler/Program.cs b/src/coreclr/tools/aot/ILCompiler/Program.cs index 5d774ce90c011..e973c05b08c2c 100644 --- a/src/coreclr/tools/aot/ILCompiler/Program.cs +++ b/src/coreclr/tools/aot/ILCompiler/Program.cs @@ -705,7 +705,7 @@ static string ILLinkify(string rootedAssembly) _trimmedAssemblies); InteropStateManager interopStateManager = new InteropStateManager(typeSystemContext.GeneratedAssembly); - InteropStubManager interopStubManager = new UsageBasedInteropStubManager(interopStateManager, pinvokePolicy); + InteropStubManager interopStubManager = new UsageBasedInteropStubManager(interopStateManager, pinvokePolicy, logger); // Unless explicitly opted in at the command line, we enable scanner for retail builds by default. // We also don't do this for multifile because scanner doesn't simulate inlining (this would be diff --git a/src/coreclr/tools/aot/ILCompiler/repro/repro.csproj b/src/coreclr/tools/aot/ILCompiler/repro/repro.csproj index 0194a7f6e4320..c0df3bfd2c6ee 100644 --- a/src/coreclr/tools/aot/ILCompiler/repro/repro.csproj +++ b/src/coreclr/tools/aot/ILCompiler/repro/repro.csproj @@ -9,6 +9,7 @@ linux-x64;win-x64;osx-x64 Debug;Release;Checked true + false P/invoke method '{0}' declares a parameter with COM marshalling. Correctness of COM interop cannot be guaranteed after trimming. Interfaces and interface members might be removed. + + P/invoke method '{0}' declares a parameter with an abstract delegate. Correctness of interop for abstract delegates cannot be guaranteed after native compilation: the marshalling code for the delegate might not be available. Use a non-abstract delegate type or ensure any delegate instance passed as parameter is marked with `UnmanagedFunctionPointerAttribute`. + diff --git a/src/coreclr/tools/aot/jitinterface/jitinterface.h b/src/coreclr/tools/aot/jitinterface/jitinterface.h index f0158199fea1a..14286588063b2 100644 --- a/src/coreclr/tools/aot/jitinterface/jitinterface.h +++ b/src/coreclr/tools/aot/jitinterface/jitinterface.h @@ -159,7 +159,6 @@ struct JitInterfaceCallbacks InfoAccessType (* constructStringLiteral)(void * thisHandle, CorInfoExceptionClass** ppException, CORINFO_MODULE_HANDLE module, unsigned int metaTok, void** ppValue); InfoAccessType (* emptyStringLiteral)(void * thisHandle, CorInfoExceptionClass** ppException, void** ppValue); uint32_t (* getFieldThreadLocalStoreID)(void * thisHandle, CorInfoExceptionClass** ppException, CORINFO_FIELD_HANDLE field, void** ppIndirection); - void (* setOverride)(void * thisHandle, CorInfoExceptionClass** ppException, ICorDynamicInfo* pOverride, CORINFO_METHOD_HANDLE currentMethod); void (* addActiveDependency)(void * thisHandle, CorInfoExceptionClass** ppException, CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo); CORINFO_METHOD_HANDLE (* GetDelegateCtor)(void * thisHandle, CorInfoExceptionClass** ppException, CORINFO_METHOD_HANDLE methHnd, CORINFO_CLASS_HANDLE clsHnd, CORINFO_METHOD_HANDLE targetMethodHnd, DelegateCtorArgs* pCtorData); void (* MethodCompileComplete)(void * thisHandle, CorInfoExceptionClass** ppException, CORINFO_METHOD_HANDLE methHnd); @@ -1617,15 +1616,6 @@ class JitInterfaceWrapper : public ICorJitInfo return temp; } - virtual void setOverride( - ICorDynamicInfo* pOverride, - CORINFO_METHOD_HANDLE currentMethod) -{ - CorInfoExceptionClass* pException = nullptr; - _callbacks->setOverride(_thisHandle, &pException, pOverride, currentMethod); - if (pException != nullptr) throw pException; -} - virtual void addActiveDependency( CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo) diff --git a/src/coreclr/ToolBox/superpmi/.clang-format b/src/coreclr/tools/superpmi/.clang-format similarity index 100% rename from src/coreclr/ToolBox/superpmi/.clang-format rename to src/coreclr/tools/superpmi/.clang-format diff --git a/src/coreclr/ToolBox/superpmi/CMakeLists.txt b/src/coreclr/tools/superpmi/CMakeLists.txt similarity index 100% rename from src/coreclr/ToolBox/superpmi/CMakeLists.txt rename to src/coreclr/tools/superpmi/CMakeLists.txt diff --git a/src/coreclr/ToolBox/superpmi/mcs/CMakeLists.txt b/src/coreclr/tools/superpmi/mcs/CMakeLists.txt similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/CMakeLists.txt rename to src/coreclr/tools/superpmi/mcs/CMakeLists.txt diff --git a/src/coreclr/ToolBox/superpmi/mcs/commandline.cpp b/src/coreclr/tools/superpmi/mcs/commandline.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/commandline.cpp rename to src/coreclr/tools/superpmi/mcs/commandline.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/commandline.h b/src/coreclr/tools/superpmi/mcs/commandline.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/commandline.h rename to src/coreclr/tools/superpmi/mcs/commandline.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/mcs.cpp b/src/coreclr/tools/superpmi/mcs/mcs.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/mcs.cpp rename to src/coreclr/tools/superpmi/mcs/mcs.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/mcs.h b/src/coreclr/tools/superpmi/mcs/mcs.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/mcs.h rename to src/coreclr/tools/superpmi/mcs/mcs.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/removedup.cpp b/src/coreclr/tools/superpmi/mcs/removedup.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/removedup.cpp rename to src/coreclr/tools/superpmi/mcs/removedup.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/removedup.h b/src/coreclr/tools/superpmi/mcs/removedup.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/removedup.h rename to src/coreclr/tools/superpmi/mcs/removedup.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbasmdump.cpp b/src/coreclr/tools/superpmi/mcs/verbasmdump.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbasmdump.cpp rename to src/coreclr/tools/superpmi/mcs/verbasmdump.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbasmdump.h b/src/coreclr/tools/superpmi/mcs/verbasmdump.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbasmdump.h rename to src/coreclr/tools/superpmi/mcs/verbasmdump.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbconcat.cpp b/src/coreclr/tools/superpmi/mcs/verbconcat.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbconcat.cpp rename to src/coreclr/tools/superpmi/mcs/verbconcat.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbconcat.h b/src/coreclr/tools/superpmi/mcs/verbconcat.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbconcat.h rename to src/coreclr/tools/superpmi/mcs/verbconcat.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbdump.cpp b/src/coreclr/tools/superpmi/mcs/verbdump.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbdump.cpp rename to src/coreclr/tools/superpmi/mcs/verbdump.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbdump.h b/src/coreclr/tools/superpmi/mcs/verbdump.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbdump.h rename to src/coreclr/tools/superpmi/mcs/verbdump.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.cpp b/src/coreclr/tools/superpmi/mcs/verbdumpmap.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.cpp rename to src/coreclr/tools/superpmi/mcs/verbdumpmap.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.h b/src/coreclr/tools/superpmi/mcs/verbdumpmap.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbdumpmap.h rename to src/coreclr/tools/superpmi/mcs/verbdumpmap.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbdumptoc.cpp b/src/coreclr/tools/superpmi/mcs/verbdumptoc.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbdumptoc.cpp rename to src/coreclr/tools/superpmi/mcs/verbdumptoc.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbdumptoc.h b/src/coreclr/tools/superpmi/mcs/verbdumptoc.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbdumptoc.h rename to src/coreclr/tools/superpmi/mcs/verbdumptoc.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbfracture.cpp b/src/coreclr/tools/superpmi/mcs/verbfracture.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbfracture.cpp rename to src/coreclr/tools/superpmi/mcs/verbfracture.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbfracture.h b/src/coreclr/tools/superpmi/mcs/verbfracture.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbfracture.h rename to src/coreclr/tools/superpmi/mcs/verbfracture.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbildump.cpp b/src/coreclr/tools/superpmi/mcs/verbildump.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbildump.cpp rename to src/coreclr/tools/superpmi/mcs/verbildump.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbildump.h b/src/coreclr/tools/superpmi/mcs/verbildump.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbildump.h rename to src/coreclr/tools/superpmi/mcs/verbildump.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbinteg.cpp b/src/coreclr/tools/superpmi/mcs/verbinteg.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbinteg.cpp rename to src/coreclr/tools/superpmi/mcs/verbinteg.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbinteg.h b/src/coreclr/tools/superpmi/mcs/verbinteg.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbinteg.h rename to src/coreclr/tools/superpmi/mcs/verbinteg.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbjitflags.cpp b/src/coreclr/tools/superpmi/mcs/verbjitflags.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbjitflags.cpp rename to src/coreclr/tools/superpmi/mcs/verbjitflags.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbjitflags.h b/src/coreclr/tools/superpmi/mcs/verbjitflags.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbjitflags.h rename to src/coreclr/tools/superpmi/mcs/verbjitflags.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbmerge.cpp b/src/coreclr/tools/superpmi/mcs/verbmerge.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbmerge.cpp rename to src/coreclr/tools/superpmi/mcs/verbmerge.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbmerge.h b/src/coreclr/tools/superpmi/mcs/verbmerge.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbmerge.h rename to src/coreclr/tools/superpmi/mcs/verbmerge.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbprintjiteeversion.cpp b/src/coreclr/tools/superpmi/mcs/verbprintjiteeversion.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbprintjiteeversion.cpp rename to src/coreclr/tools/superpmi/mcs/verbprintjiteeversion.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbprintjiteeversion.h b/src/coreclr/tools/superpmi/mcs/verbprintjiteeversion.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbprintjiteeversion.h rename to src/coreclr/tools/superpmi/mcs/verbprintjiteeversion.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbremovedup.cpp b/src/coreclr/tools/superpmi/mcs/verbremovedup.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbremovedup.cpp rename to src/coreclr/tools/superpmi/mcs/verbremovedup.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbremovedup.h b/src/coreclr/tools/superpmi/mcs/verbremovedup.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbremovedup.h rename to src/coreclr/tools/superpmi/mcs/verbremovedup.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbstat.cpp b/src/coreclr/tools/superpmi/mcs/verbstat.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbstat.cpp rename to src/coreclr/tools/superpmi/mcs/verbstat.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbstat.h b/src/coreclr/tools/superpmi/mcs/verbstat.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbstat.h rename to src/coreclr/tools/superpmi/mcs/verbstat.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbstrip.cpp b/src/coreclr/tools/superpmi/mcs/verbstrip.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbstrip.cpp rename to src/coreclr/tools/superpmi/mcs/verbstrip.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbstrip.h b/src/coreclr/tools/superpmi/mcs/verbstrip.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbstrip.h rename to src/coreclr/tools/superpmi/mcs/verbstrip.h diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbtoc.cpp b/src/coreclr/tools/superpmi/mcs/verbtoc.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbtoc.cpp rename to src/coreclr/tools/superpmi/mcs/verbtoc.cpp diff --git a/src/coreclr/ToolBox/superpmi/mcs/verbtoc.h b/src/coreclr/tools/superpmi/mcs/verbtoc.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/mcs/verbtoc.h rename to src/coreclr/tools/superpmi/mcs/verbtoc.h diff --git a/src/coreclr/ToolBox/superpmi/readme.md b/src/coreclr/tools/superpmi/readme.md similarity index 99% rename from src/coreclr/ToolBox/superpmi/readme.md rename to src/coreclr/tools/superpmi/readme.md index c3de3dfe94288..b84e8d01697bd 100644 --- a/src/coreclr/ToolBox/superpmi/readme.md +++ b/src/coreclr/tools/superpmi/readme.md @@ -1,6 +1,6 @@ # Overview -This directory (`src/coreclr/ToolBox/superpmi` in the GitHub +This directory (`src/coreclr/tools/superpmi` in the GitHub https://github.com/dotnet/runtime repository) contains the SuperPMI tool used for testing the .NET just-in-time (JIT) compiler. diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/agnostic.h b/src/coreclr/tools/superpmi/superpmi-shared/agnostic.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/agnostic.h rename to src/coreclr/tools/superpmi/superpmi-shared/agnostic.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/asmdumper.cpp b/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/asmdumper.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/asmdumper.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/asmdumper.h b/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/asmdumper.h rename to src/coreclr/tools/superpmi/superpmi-shared/asmdumper.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/callutils.cpp b/src/coreclr/tools/superpmi/superpmi-shared/callutils.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/callutils.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/callutils.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/callutils.h b/src/coreclr/tools/superpmi/superpmi-shared/callutils.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/callutils.h rename to src/coreclr/tools/superpmi/superpmi-shared/callutils.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/compileresult.cpp b/src/coreclr/tools/superpmi/superpmi-shared/compileresult.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/compileresult.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/compileresult.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/compileresult.h b/src/coreclr/tools/superpmi/superpmi-shared/compileresult.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/compileresult.h rename to src/coreclr/tools/superpmi/superpmi-shared/compileresult.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/crlwmlist.h b/src/coreclr/tools/superpmi/superpmi-shared/crlwmlist.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/crlwmlist.h rename to src/coreclr/tools/superpmi/superpmi-shared/crlwmlist.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/errorhandling.cpp b/src/coreclr/tools/superpmi/superpmi-shared/errorhandling.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/errorhandling.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/errorhandling.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/errorhandling.h b/src/coreclr/tools/superpmi/superpmi-shared/errorhandling.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/errorhandling.h rename to src/coreclr/tools/superpmi/superpmi-shared/errorhandling.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/hash.cpp b/src/coreclr/tools/superpmi/superpmi-shared/hash.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/hash.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/hash.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/hash.h b/src/coreclr/tools/superpmi/superpmi-shared/hash.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/hash.h rename to src/coreclr/tools/superpmi/superpmi-shared/hash.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/icorjitcompilerimpl.h b/src/coreclr/tools/superpmi/superpmi-shared/icorjitcompilerimpl.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/icorjitcompilerimpl.h rename to src/coreclr/tools/superpmi/superpmi-shared/icorjitcompilerimpl.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/icorjithostimpl.h b/src/coreclr/tools/superpmi/superpmi-shared/icorjithostimpl.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/icorjithostimpl.h rename to src/coreclr/tools/superpmi/superpmi-shared/icorjithostimpl.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/icorjitinfoimpl.h b/src/coreclr/tools/superpmi/superpmi-shared/icorjitinfoimpl.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/icorjitinfoimpl.h rename to src/coreclr/tools/superpmi/superpmi-shared/icorjitinfoimpl.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/lightweightmap.h b/src/coreclr/tools/superpmi/superpmi-shared/lightweightmap.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/lightweightmap.h rename to src/coreclr/tools/superpmi/superpmi-shared/lightweightmap.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/logging.cpp b/src/coreclr/tools/superpmi/superpmi-shared/logging.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/logging.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/logging.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/logging.h b/src/coreclr/tools/superpmi/superpmi-shared/logging.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/logging.h rename to src/coreclr/tools/superpmi/superpmi-shared/logging.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/lwmlist.h b/src/coreclr/tools/superpmi/superpmi-shared/lwmlist.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/lwmlist.h rename to src/coreclr/tools/superpmi/superpmi-shared/lwmlist.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/mclist.cpp b/src/coreclr/tools/superpmi/superpmi-shared/mclist.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/mclist.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/mclist.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/mclist.h b/src/coreclr/tools/superpmi/superpmi-shared/mclist.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/mclist.h rename to src/coreclr/tools/superpmi/superpmi-shared/mclist.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontext.cpp b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontext.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontext.h b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontext.h rename to src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontextiterator.cpp b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontextiterator.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontextiterator.h b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontextiterator.h rename to src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontextreader.cpp b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontextreader.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontextreader.h b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/methodcontextreader.h rename to src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/runtimedetails.h b/src/coreclr/tools/superpmi/superpmi-shared/runtimedetails.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/runtimedetails.h rename to src/coreclr/tools/superpmi/superpmi-shared/runtimedetails.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/simpletimer.cpp b/src/coreclr/tools/superpmi/superpmi-shared/simpletimer.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/simpletimer.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/simpletimer.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/simpletimer.h b/src/coreclr/tools/superpmi/superpmi-shared/simpletimer.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/simpletimer.h rename to src/coreclr/tools/superpmi/superpmi-shared/simpletimer.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/spmidumphelper.cpp b/src/coreclr/tools/superpmi/superpmi-shared/spmidumphelper.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/spmidumphelper.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/spmidumphelper.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/spmidumphelper.h b/src/coreclr/tools/superpmi/superpmi-shared/spmidumphelper.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/spmidumphelper.h rename to src/coreclr/tools/superpmi/superpmi-shared/spmidumphelper.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/spmirecordhelper.h b/src/coreclr/tools/superpmi/superpmi-shared/spmirecordhelper.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/spmirecordhelper.h rename to src/coreclr/tools/superpmi/superpmi-shared/spmirecordhelper.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/spmiutil.cpp b/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/spmiutil.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/spmiutil.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/spmiutil.h b/src/coreclr/tools/superpmi/superpmi-shared/spmiutil.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/spmiutil.h rename to src/coreclr/tools/superpmi/superpmi-shared/spmiutil.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/standardpch.h b/src/coreclr/tools/superpmi/superpmi-shared/standardpch.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/standardpch.h rename to src/coreclr/tools/superpmi/superpmi-shared/standardpch.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/tocfile.cpp b/src/coreclr/tools/superpmi/superpmi-shared/tocfile.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/tocfile.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/tocfile.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/tocfile.h b/src/coreclr/tools/superpmi/superpmi-shared/tocfile.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/tocfile.h rename to src/coreclr/tools/superpmi/superpmi-shared/tocfile.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/typeutils.cpp b/src/coreclr/tools/superpmi/superpmi-shared/typeutils.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/typeutils.cpp rename to src/coreclr/tools/superpmi/superpmi-shared/typeutils.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shared/typeutils.h b/src/coreclr/tools/superpmi/superpmi-shared/typeutils.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shared/typeutils.h rename to src/coreclr/tools/superpmi/superpmi-shared/typeutils.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/CMakeLists.txt b/src/coreclr/tools/superpmi/superpmi-shim-collector/CMakeLists.txt similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/CMakeLists.txt rename to src/coreclr/tools/superpmi/superpmi-shim-collector/CMakeLists.txt diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitcompiler.cpp b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitcompiler.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitcompiler.h b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitcompiler.h rename to src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitinfo.cpp b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.cpp similarity index 99% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitinfo.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.cpp index a79cbb3c0ff0c..061d3d6a77b92 100644 --- a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitinfo.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.cpp @@ -1716,13 +1716,6 @@ uint32_t interceptor_ICJI::getFieldThreadLocalStoreID(CORINFO_FIELD_HANDLE field return temp; } -// Sets another object to intercept calls to "self" and current method being compiled -void interceptor_ICJI::setOverride(ICorDynamicInfo* pOverride, CORINFO_METHOD_HANDLE currentMethod) -{ - mc->cr->AddCall("setOverride"); - original_ICorJitInfo->setOverride(pOverride, currentMethod); -} - // Adds an active dependency from the context method's module to the given module // This is internal callback for the EE. JIT should not call it directly. void interceptor_ICJI::addActiveDependency(CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo) diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitinfo.h b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/icorjitinfo.h rename to src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitinfo.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/jithost.cpp b/src/coreclr/tools/superpmi/superpmi-shim-collector/jithost.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/jithost.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-collector/jithost.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/jithost.h b/src/coreclr/tools/superpmi/superpmi-shim-collector/jithost.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/jithost.h rename to src/coreclr/tools/superpmi/superpmi-shim-collector/jithost.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp b/src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/superpmi-shim-collector.def b/src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.def similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/superpmi-shim-collector.def rename to src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.def diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-collector/superpmi-shim-collector.h b/src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-collector/superpmi-shim-collector.h rename to src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/CMakeLists.txt b/src/coreclr/tools/superpmi/superpmi-shim-counter/CMakeLists.txt similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/CMakeLists.txt rename to src/coreclr/tools/superpmi/superpmi-shim-counter/CMakeLists.txt diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitcompiler.cpp b/src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitcompiler.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitcompiler.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitcompiler.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitcompiler.h b/src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitcompiler.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitcompiler.h rename to src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitcompiler.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitinfo.cpp b/src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitinfo.cpp similarity index 99% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitinfo.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitinfo.cpp index 88e0e03e42d98..657575cce71fe 100644 --- a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitinfo.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitinfo.cpp @@ -1184,14 +1184,6 @@ uint32_t interceptor_ICJI::getFieldThreadLocalStoreID( return original_ICorJitInfo->getFieldThreadLocalStoreID(field, ppIndirection); } -void interceptor_ICJI::setOverride( - ICorDynamicInfo* pOverride, - CORINFO_METHOD_HANDLE currentMethod) -{ - mcs->AddCall("setOverride"); - original_ICorJitInfo->setOverride(pOverride, currentMethod); -} - void interceptor_ICJI::addActiveDependency( CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo) diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitinfo.h b/src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitinfo.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/icorjitinfo.h rename to src/coreclr/tools/superpmi/superpmi-shim-counter/icorjitinfo.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/jithost.cpp b/src/coreclr/tools/superpmi/superpmi-shim-counter/jithost.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/jithost.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-counter/jithost.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/jithost.h b/src/coreclr/tools/superpmi/superpmi-shim-counter/jithost.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/jithost.h rename to src/coreclr/tools/superpmi/superpmi-shim-counter/jithost.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/methodcallsummarizer.cpp b/src/coreclr/tools/superpmi/superpmi-shim-counter/methodcallsummarizer.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/methodcallsummarizer.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-counter/methodcallsummarizer.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/methodcallsummarizer.h b/src/coreclr/tools/superpmi/superpmi-shim-counter/methodcallsummarizer.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/methodcallsummarizer.h rename to src/coreclr/tools/superpmi/superpmi-shim-counter/methodcallsummarizer.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/superpmi-shim-counter.cpp b/src/coreclr/tools/superpmi/superpmi-shim-counter/superpmi-shim-counter.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/superpmi-shim-counter.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-counter/superpmi-shim-counter.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/superpmi-shim-counter.def b/src/coreclr/tools/superpmi/superpmi-shim-counter/superpmi-shim-counter.def similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/superpmi-shim-counter.def rename to src/coreclr/tools/superpmi/superpmi-shim-counter/superpmi-shim-counter.def diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-counter/superpmi-shim-counter.h b/src/coreclr/tools/superpmi/superpmi-shim-counter/superpmi-shim-counter.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-counter/superpmi-shim-counter.h rename to src/coreclr/tools/superpmi/superpmi-shim-counter/superpmi-shim-counter.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/CMakeLists.txt b/src/coreclr/tools/superpmi/superpmi-shim-simple/CMakeLists.txt similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/CMakeLists.txt rename to src/coreclr/tools/superpmi/superpmi-shim-simple/CMakeLists.txt diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitcompiler.cpp b/src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitcompiler.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitcompiler.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitcompiler.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitcompiler.h b/src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitcompiler.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitcompiler.h rename to src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitcompiler.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitinfo.cpp b/src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitinfo.cpp similarity index 99% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitinfo.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitinfo.cpp index 1692685887178..294750ccde5c1 100644 --- a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitinfo.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitinfo.cpp @@ -1036,13 +1036,6 @@ uint32_t interceptor_ICJI::getFieldThreadLocalStoreID( return original_ICorJitInfo->getFieldThreadLocalStoreID(field, ppIndirection); } -void interceptor_ICJI::setOverride( - ICorDynamicInfo* pOverride, - CORINFO_METHOD_HANDLE currentMethod) -{ - original_ICorJitInfo->setOverride(pOverride, currentMethod); -} - void interceptor_ICJI::addActiveDependency( CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo) diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitinfo.h b/src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitinfo.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/icorjitinfo.h rename to src/coreclr/tools/superpmi/superpmi-shim-simple/icorjitinfo.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/jithost.cpp b/src/coreclr/tools/superpmi/superpmi-shim-simple/jithost.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/jithost.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-simple/jithost.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/jithost.h b/src/coreclr/tools/superpmi/superpmi-shim-simple/jithost.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/jithost.h rename to src/coreclr/tools/superpmi/superpmi-shim-simple/jithost.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/superpmi-shim-simple.cpp b/src/coreclr/tools/superpmi/superpmi-shim-simple/superpmi-shim-simple.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/superpmi-shim-simple.cpp rename to src/coreclr/tools/superpmi/superpmi-shim-simple/superpmi-shim-simple.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/superpmi-shim-simple.def b/src/coreclr/tools/superpmi/superpmi-shim-simple/superpmi-shim-simple.def similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/superpmi-shim-simple.def rename to src/coreclr/tools/superpmi/superpmi-shim-simple/superpmi-shim-simple.def diff --git a/src/coreclr/ToolBox/superpmi/superpmi-shim-simple/superpmi-shim-simple.h b/src/coreclr/tools/superpmi/superpmi-shim-simple/superpmi-shim-simple.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi-shim-simple/superpmi-shim-simple.h rename to src/coreclr/tools/superpmi/superpmi-shim-simple/superpmi-shim-simple.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/CMakeLists.txt b/src/coreclr/tools/superpmi/superpmi/CMakeLists.txt similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/CMakeLists.txt rename to src/coreclr/tools/superpmi/superpmi/CMakeLists.txt diff --git a/src/coreclr/ToolBox/superpmi/superpmi/commandline.cpp b/src/coreclr/tools/superpmi/superpmi/commandline.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/commandline.cpp rename to src/coreclr/tools/superpmi/superpmi/commandline.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/commandline.h b/src/coreclr/tools/superpmi/superpmi/commandline.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/commandline.h rename to src/coreclr/tools/superpmi/superpmi/commandline.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/cycletimer.cpp b/src/coreclr/tools/superpmi/superpmi/cycletimer.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/cycletimer.cpp rename to src/coreclr/tools/superpmi/superpmi/cycletimer.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/cycletimer.h b/src/coreclr/tools/superpmi/superpmi/cycletimer.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/cycletimer.h rename to src/coreclr/tools/superpmi/superpmi/cycletimer.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/icorjitinfo.cpp b/src/coreclr/tools/superpmi/superpmi/icorjitinfo.cpp similarity index 99% rename from src/coreclr/ToolBox/superpmi/superpmi/icorjitinfo.cpp rename to src/coreclr/tools/superpmi/superpmi/icorjitinfo.cpp index 17faf7a144262..16c66a6a39847 100644 --- a/src/coreclr/ToolBox/superpmi/superpmi/icorjitinfo.cpp +++ b/src/coreclr/tools/superpmi/superpmi/icorjitinfo.cpp @@ -1490,14 +1490,6 @@ uint32_t MyICJI::getFieldThreadLocalStoreID(CORINFO_FIELD_HANDLE field, void** p return jitInstance->mc->repGetFieldThreadLocalStoreID(field, ppIndirection); } -// Sets another object to intercept calls to "self" and current method being compiled -void MyICJI::setOverride(ICorDynamicInfo* pOverride, CORINFO_METHOD_HANDLE currentMethod) -{ - jitInstance->mc->cr->AddCall("setOverride"); - LogError("Hit unimplemented setOverride"); - DebugBreakorAV(115); -} - // Adds an active dependency from the context method's module to the given module // This is internal callback for the EE. JIT should not call it directly. void MyICJI::addActiveDependency(CORINFO_MODULE_HANDLE moduleFrom, CORINFO_MODULE_HANDLE moduleTo) diff --git a/src/coreclr/ToolBox/superpmi/superpmi/icorjitinfo.h b/src/coreclr/tools/superpmi/superpmi/icorjitinfo.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/icorjitinfo.h rename to src/coreclr/tools/superpmi/superpmi/icorjitinfo.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/jitdebugger.cpp b/src/coreclr/tools/superpmi/superpmi/jitdebugger.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/jitdebugger.cpp rename to src/coreclr/tools/superpmi/superpmi/jitdebugger.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/jitdebugger.h b/src/coreclr/tools/superpmi/superpmi/jitdebugger.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/jitdebugger.h rename to src/coreclr/tools/superpmi/superpmi/jitdebugger.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/jithost.cpp b/src/coreclr/tools/superpmi/superpmi/jithost.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/jithost.cpp rename to src/coreclr/tools/superpmi/superpmi/jithost.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/jithost.h b/src/coreclr/tools/superpmi/superpmi/jithost.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/jithost.h rename to src/coreclr/tools/superpmi/superpmi/jithost.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/jitinstance.cpp b/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/jitinstance.cpp rename to src/coreclr/tools/superpmi/superpmi/jitinstance.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/jitinstance.h b/src/coreclr/tools/superpmi/superpmi/jitinstance.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/jitinstance.h rename to src/coreclr/tools/superpmi/superpmi/jitinstance.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/methodstatsemitter.cpp b/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/methodstatsemitter.cpp rename to src/coreclr/tools/superpmi/superpmi/methodstatsemitter.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/methodstatsemitter.h b/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/methodstatsemitter.h rename to src/coreclr/tools/superpmi/superpmi/methodstatsemitter.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/metricssummary.cpp b/src/coreclr/tools/superpmi/superpmi/metricssummary.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/metricssummary.cpp rename to src/coreclr/tools/superpmi/superpmi/metricssummary.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/metricssummary.h b/src/coreclr/tools/superpmi/superpmi/metricssummary.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/metricssummary.h rename to src/coreclr/tools/superpmi/superpmi/metricssummary.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/neardiffer.cpp b/src/coreclr/tools/superpmi/superpmi/neardiffer.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/neardiffer.cpp rename to src/coreclr/tools/superpmi/superpmi/neardiffer.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/neardiffer.h b/src/coreclr/tools/superpmi/superpmi/neardiffer.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/neardiffer.h rename to src/coreclr/tools/superpmi/superpmi/neardiffer.h diff --git a/src/coreclr/ToolBox/superpmi/superpmi/parallelsuperpmi.cpp b/src/coreclr/tools/superpmi/superpmi/parallelsuperpmi.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/parallelsuperpmi.cpp rename to src/coreclr/tools/superpmi/superpmi/parallelsuperpmi.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/superpmi.cpp b/src/coreclr/tools/superpmi/superpmi/superpmi.cpp similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/superpmi.cpp rename to src/coreclr/tools/superpmi/superpmi/superpmi.cpp diff --git a/src/coreclr/ToolBox/superpmi/superpmi/superpmi.h b/src/coreclr/tools/superpmi/superpmi/superpmi.h similarity index 100% rename from src/coreclr/ToolBox/superpmi/superpmi/superpmi.h rename to src/coreclr/tools/superpmi/superpmi/superpmi.h diff --git a/src/coreclr/utilcode/log.cpp b/src/coreclr/utilcode/log.cpp index b4a73f2cb6baf..b889c7d341ce3 100644 --- a/src/coreclr/utilcode/log.cpp +++ b/src/coreclr/utilcode/log.cpp @@ -76,7 +76,7 @@ VOID InitLogging() if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_LogWithPid)) { WCHAR szPid[20]; - swprintf_s(szPid, COUNTOF(szPid), W(".%d"), GetCurrentProcessId()); + swprintf_s(szPid, ARRAY_SIZE(szPid), W(".%d"), GetCurrentProcessId()); wcscat_s(szLogFileName.Ptr(), szLogFileName.Size(), szPid); } @@ -323,7 +323,7 @@ VOID LogSpewAlwaysValist(const char *fmt, va_list args) static bool needsPrefix = true; if (needsPrefix) - buflen = sprintf_s(pBuffer, COUNTOF(rgchBuffer), "TID %04x: ", GetCurrentThreadId()); + buflen = sprintf_s(pBuffer, ARRAY_SIZE(rgchBuffer), "TID %04x: ", GetCurrentThreadId()); needsPrefix = (fmt[strlen(fmt)-1] == '\n'); diff --git a/src/coreclr/vm/CMakeLists.txt b/src/coreclr/vm/CMakeLists.txt index bbc411c324cde..2f34d2c0ceaa1 100644 --- a/src/coreclr/vm/CMakeLists.txt +++ b/src/coreclr/vm/CMakeLists.txt @@ -617,7 +617,6 @@ if(CLR_CMAKE_TARGET_WIN32) dispatchinfo.cpp dispparammarshaler.cpp mngstdinterfaces.cpp - notifyexternals.cpp olecontexthelpers.cpp runtimecallablewrapper.cpp stdinterfaces.cpp @@ -634,7 +633,6 @@ if(CLR_CMAKE_TARGET_WIN32) dispatchinfo.h dispparammarshaler.h mngstdinterfaces.h - notifyexternals.h olecontexthelpers.h runtimecallablewrapper.h stdinterfaces.h diff --git a/src/coreclr/vm/amd64/cgencpu.h b/src/coreclr/vm/amd64/cgencpu.h index 29b9dddfb7de4..33589c27bae39 100644 --- a/src/coreclr/vm/amd64/cgencpu.h +++ b/src/coreclr/vm/amd64/cgencpu.h @@ -415,8 +415,6 @@ extern "C" void setFPReturn(int fpSize, INT64 retVal); extern "C" void getFPReturn(int fpSize, INT64 *retval); -struct ComToManagedExRecord; // defined in cgencpu.cpp - #include struct DECLSPEC_ALIGN(8) UMEntryThunkCode { diff --git a/src/coreclr/vm/arm64/asmhelpers.S b/src/coreclr/vm/arm64/asmhelpers.S index 7d8b3c7dd88b2..e7725cd16e63b 100644 --- a/src/coreclr/vm/arm64/asmhelpers.S +++ b/src/coreclr/vm/arm64/asmhelpers.S @@ -551,152 +551,6 @@ LOCAL_LABEL(LNullThis): LEAF_END SinglecastDelegateInvokeStub, _TEXT -#ifdef FEATURE_COMINTEROP - -#define ComCallPreStub_FrameSize (SIZEOF__GSCookie + SIZEOF__ComMethodFrame) -#define ComCallPreStub_FirstStackAdjust (8 + SIZEOF__ArgumentRegisters + 2 * 8) // x8, reg args , fp & lr already pushed -#define ComCallPreStub_StackAlloc0 (ComCallPreStub_FrameSize - ComCallPreStub_FirstStackAdjust) -#define ComCallPreStub_StackAlloc1 (ComCallPreStub_StackAlloc0 + SIZEOF__FloatArgumentRegisters + 8)// 8 for ErrorReturn -#define ComCallPreStub_StackAlloc (ComCallPreStub_StackAlloc1 + (ComCallPreStub_StackAlloc1 & 8)) - -#define ComCallPreStub_FrameOffset (ComCallPreStub_StackAlloc - (SIZEOF__ComMethodFrame - ComCallPreStub_FirstStackAdjust)) -#define ComCallPreStub_ErrorReturnOffset0 SIZEOF__FloatArgumentRegisters - -#define ComCallPreStub_FirstStackAdjust (ComCallPreStub_ErrorReturnOffset0 + (ComCallPreStub_ErrorReturnOffset0 & 8)) - -// ------------------------------------------------------------------ -// COM to CLR stub called the first time a particular method is invoked.// -// -// On entry: -// x12 : ComCallMethodDesc* provided by prepad thunk -// plus user arguments in registers and on the stack -// -// On exit: -// tail calls to real method -// -NESTED_ENTRY ComCallPreStub, _TEXT, NoHandler - - // Save arguments and return address - PROLOG_SAVE_REG_PAIR fp, lr, -ComCallPreStub_FirstStackAdjust! - PROLOG_STACK_ALLOC ComCallPreStub_StackAlloc - - SAVE_ARGUMENT_REGISTERS sp, (16+ComCallPreStub_StackAlloc) - - SAVE_FLOAT_ARGUMENT_REGISTERS sp, 0 - - str x12, [sp, #(ComCallPreStub_FrameOffset + UnmanagedToManagedFrame__m_pvDatum)] - add x0, sp, #(ComCallPreStub_FrameOffset) - add x1, sp, #(ComCallPreStub_ErrorReturnOffset) - bl C_FUNC(ComPreStubWorker) - - cbz x0, LOCAL_LABEL(ComCallPreStub_ErrorExit) - - mov x12, x0 - - // pop the stack and restore original register state - RESTORE_FLOAT_ARGUMENT_REGISTERS sp, 0 - RESTORE_ARGUMENT_REGISTERS sp, (16+ComCallPreStub_StackAlloc) - - EPILOG_STACK_FREE ComCallPreStub_StackAlloc - EPILOG_RESTORE_REG_PAIR fp, lr, ComCallPreStub_FirstStackAdjust! - - // and tailcall to the actual method - EPILOG_BRANCH_REG x12 - -ComCallPreStub_ErrorExit - ldr x0, [sp, #(ComCallPreStub_ErrorReturnOffset)] // ErrorReturn - - // pop the stack - EPILOG_STACK_FREE ComCallPreStub_StackAlloc - EPILOG_RESTORE_REG_PAIR fp, lr, ComCallPreStub_FirstStackAdjust! - - EPILOG_RETURN - -NESTED_END ComCallPreStub, _TEXT - -// ------------------------------------------------------------------ -// COM to CLR stub which sets up a ComMethodFrame and calls COMToCLRWorker. -// -// On entry: -// x12 : ComCallMethodDesc* provided by prepad thunk -// plus user arguments in registers and on the stack -// -// On exit: -// Result in x0/d0 as per the real method being called -// - NESTED_ENTRY GenericComCallStub, _TEXT, NoHandler - - // Save arguments and return address - PROLOG_SAVE_REG_PAIR fp, lr, -GenericComCallStub_FirstStackAdjust! - PROLOG_STACK_ALLOC GenericComCallStub_StackAlloc - - SAVE_ARGUMENT_REGISTERS sp, (16+GenericComCallStub_StackAlloc) - SAVE_FLOAT_ARGUMENT_REGISTERS sp, 0 - - str x12, [sp, #(GenericComCallStub_FrameOffset + UnmanagedToManagedFrame__m_pvDatum)] - add x1, sp, #GenericComCallStub_FrameOffset - bl C_FUNC(COMToCLRWorker) - - // pop the stack - EPILOG_STACK_FREE GenericComCallStub_StackAlloc - EPILOG_RESTORE_REG_PAIR fp, lr, GenericComCallStub_FirstStackAdjust! - - EPILOG_RETURN - - NESTED_END GenericComCallStub, _TEXT - -// ------------------------------------------------------------------ -// COM to CLR stub called from COMToCLRWorker that actually dispatches to the real managed method. -// -// On entry: -// x0 : dwStackSlots, count of argument stack slots to copy -// x1 : pFrame, ComMethodFrame pushed by GenericComCallStub above -// x2 : pTarget, address of code to call -// x3 : pSecretArg, hidden argument passed to target above in x12 -// x4 : pDangerousThis, managed 'this' reference -// -// On exit: -// Result in x0/d0 as per the real method being called -// - NESTED_ENTRY COMToCLRDispatchHelper, _TEXT,CallDescrWorkerUnwindFrameChainHandler - - PROLOG_SAVE_REG_PAIR fp, lr, -16! - - cbz x0, LOCAL_LABEL(COMToCLRDispatchHelper_RegSetup) - - add x9, x1, #SIZEOF__ComMethodFrame - add x9, x9, x0, LSL #3 -COMToCLRDispatchHelper_StackLoop - ldr x8, [x9, #-8]! - str x8, [sp, #-8]! - sub x0, x0, #1 - cbnz x0, LOCAL_LABEL(COMToCLRDispatchHelper_StackLoop) - -COMToCLRDispatchHelper_RegSetup - - RESTORE_FLOAT_ARGUMENT_REGISTERS x1, -1 * GenericComCallStub_FrameOffset - - mov lr, x2 - mov x12, x3 - - mov x0, x4 - - ldp x2, x3, [x1, #(SIZEOF__ComMethodFrame - SIZEOF__ArgumentRegisters + 16)] - ldp x4, x5, [x1, #(SIZEOF__ComMethodFrame - SIZEOF__ArgumentRegisters + 32)] - ldp x6, x7, [x1, #(SIZEOF__ComMethodFrame - SIZEOF__ArgumentRegisters + 48)] - ldr x8, [x1, #(SIZEOF__ComMethodFrame - SIZEOF__ArgumentRegisters - 8)] - - ldr x1, [x1, #(SIZEOF__ComMethodFrame - SIZEOF__ArgumentRegisters + 8)] - - blr lr - - EPILOG_STACK_RESTORE - EPILOG_RESTORE_REG_PAIR fp, lr, 16! - EPILOG_RETURN - - NESTED_END COMToCLRDispatchHelper, _TEXT - -#endif // FEATURE_COMINTEROP // // x12 = UMEntryThunk* // @@ -1039,39 +893,6 @@ DynamicHelper DynamicHelperFrameFlags_ObjectArg, _Obj DynamicHelper DynamicHelperFrameFlags_ObjectArg | DynamicHelperFrameFlags_ObjectArg2, _ObjObj #endif -#ifdef FEATURE_COMINTEROP - -// Function used by COM interop to get floating point return value (since it's not in the same -// register(s) as non-floating point values). -// -// On entry// -// x0 : size of the FP result (4 or 8 bytes) -// x1 : pointer to 64-bit buffer to receive result -// -// On exit: -// buffer pointed to by x1 on entry contains the float or double argument as appropriate -// -LEAF_ENTRY getFPReturn, _TEXT - str d0, [x1] -LEAF_END getFPReturn, _TEXT - -// ------------------------------------------------------------------ -// Function used by COM interop to set floating point return value (since it's not in the same -// register(s) as non-floating point values). -// -// On entry: -// x0 : size of the FP result (4 or 8 bytes) -// x1 : 32-bit or 64-bit FP result -// -// On exit: -// s0 : float result if x0 == 4 -// d0 : double result if x0 == 8 -// -LEAF_ENTRY setFPReturn, _TEXT - fmov d0, x1 -LEAF_END setFPReturn, _TEXT -#endif - // // JIT Static access helpers when coreclr host specifies single appdomain flag // diff --git a/src/coreclr/vm/array.cpp b/src/coreclr/vm/array.cpp index a8494c45d8ed6..1088bacb6275b 100644 --- a/src/coreclr/vm/array.cpp +++ b/src/coreclr/vm/array.cpp @@ -981,7 +981,7 @@ Stub *GenerateArrayOpStub(ArrayMethodDesc* pMD) static const ILStubTypes stubTypes[3] = { ILSTUB_ARRAYOP_GET, ILSTUB_ARRAYOP_SET, ILSTUB_ARRAYOP_ADDRESS }; - _ASSERTE(pMD->GetArrayFuncIndex() <= COUNTOF(stubTypes)); + _ASSERTE(pMD->GetArrayFuncIndex() <= ARRAY_SIZE(stubTypes)); NDirectStubFlags arrayOpStubFlag = (NDirectStubFlags)stubTypes[pMD->GetArrayFuncIndex()]; MethodDesc * pStubMD = ILStubCache::CreateAndLinkNewILStubMethodDesc(pMD->GetLoaderAllocator(), diff --git a/src/coreclr/vm/callingconvention.h b/src/coreclr/vm/callingconvention.h index 00cc47e9661d0..1fe96fde98922 100644 --- a/src/coreclr/vm/callingconvention.h +++ b/src/coreclr/vm/callingconvention.h @@ -694,9 +694,8 @@ class ArgIteratorTemplate : public ARGITERATOR_BASE unsigned byteArgSize = GetArgSize(); - // Question: why do not arm and x86 have similar checks? - // Composites greater than 16 bytes are passed by reference - if ((GetArgType() == ELEMENT_TYPE_VALUETYPE) && (byteArgSize > ENREGISTERED_PARAMTYPE_MAXSIZE)) + // On ARM64 some composites are implicitly passed by reference. + if (IsArgPassedByRef()) { byteArgSize = TARGET_POINTER_SIZE; } diff --git a/src/coreclr/vm/ceeload.cpp b/src/coreclr/vm/ceeload.cpp index 1fb144d663c7c..72a2e1152210b 100644 --- a/src/coreclr/vm/ceeload.cpp +++ b/src/coreclr/vm/ceeload.cpp @@ -3857,7 +3857,7 @@ MethodDesc *Module::FindMethod(mdToken pMethod) #ifdef _DEBUG CONTRACT_VIOLATION(ThrowsViolation); char szMethodName [MAX_CLASSNAME_LENGTH]; - CEEInfo::findNameOfToken(this, pMethod, szMethodName, COUNTOF (szMethodName)); + CEEInfo::findNameOfToken(this, pMethod, szMethodName, ARRAY_SIZE(szMethodName)); // This used to be IJW, but changed to LW_INTEROP to reclaim a bit in our log facilities LOG((LF_INTEROP, LL_INFO10, "Failed to find Method: %s for Vtable Fixup\n", szMethodName)); #endif // _DEBUG diff --git a/src/coreclr/vm/ceeload.h b/src/coreclr/vm/ceeload.h index e7dd5629a2c84..8a3caaddc7dbf 100644 --- a/src/coreclr/vm/ceeload.h +++ b/src/coreclr/vm/ceeload.h @@ -1985,18 +1985,6 @@ class Module return dac_cast(m_ModuleID); } - SIZE_T * GetAddrModuleID() - { - LIMITED_METHOD_CONTRACT; - return (SIZE_T*) &m_ModuleID; - } - - static SIZE_T GetOffsetOfModuleID() - { - LIMITED_METHOD_CONTRACT; - return offsetof(Module, m_ModuleID); - } - PTR_DomainLocalModule GetDomainLocalModule(); // LoaderHeap for storing IJW thunks diff --git a/src/coreclr/vm/ceemain.cpp b/src/coreclr/vm/ceemain.cpp index a162022b901d3..93ea7df27ed8c 100644 --- a/src/coreclr/vm/ceemain.cpp +++ b/src/coreclr/vm/ceemain.cpp @@ -185,7 +185,6 @@ #ifdef FEATURE_COMINTEROP #include "runtimecallablewrapper.h" -#include "notifyexternals.h" #include "mngstdinterfaces.h" #include "interoplibinterface.h" #endif // FEATURE_COMINTEROP diff --git a/src/coreclr/vm/clrtocomcall.cpp b/src/coreclr/vm/clrtocomcall.cpp index a7f91f7e13d39..3a7847089b682 100644 --- a/src/coreclr/vm/clrtocomcall.cpp +++ b/src/coreclr/vm/clrtocomcall.cpp @@ -617,7 +617,7 @@ UINT32 CLRToCOMLateBoundWorker( if (hr == S_OK) { WCHAR strTmp[ARRAY_SIZE(DISPID_NAME_FORMAT_STRING W("4294967295"))]; - _snwprintf_s(strTmp, COUNTOF(strTmp), _TRUNCATE, DISPID_NAME_FORMAT_STRING, dispId); + _snwprintf_s(strTmp, ARRAY_SIZE(strTmp), _TRUNCATE, DISPID_NAME_FORMAT_STRING, dispId); gc.MemberName = StringObject::NewString(strTmp); } else diff --git a/src/coreclr/vm/codeman.cpp b/src/coreclr/vm/codeman.cpp index 25af4f44ed8e5..fe68c6a0f0d17 100644 --- a/src/coreclr/vm/codeman.cpp +++ b/src/coreclr/vm/codeman.cpp @@ -1257,7 +1257,7 @@ void EEJitManager::SetCpuInfo() #endif // TARGET_X86 #if defined(TARGET_X86) || defined(TARGET_AMD64) - CPUCompileFlags.Set(InstructionSet_X86Base); + CPUCompileFlags.Set(InstructionSet_X86Base); // NOTE: The below checks are based on the information reported by // Intel® 64 and IA-32 Architectures Software Developer’s Manual. Volume 2 @@ -1469,6 +1469,7 @@ void EEJitManager::SetCpuInfo() // FP and SIMD support are enabled by default CPUCompileFlags.Set(InstructionSet_ArmBase); CPUCompileFlags.Set(InstructionSet_AdvSimd); + // PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE (30) if (IsProcessorFeaturePresent(PF_ARM_V8_CRYPTO_INSTRUCTIONS_AVAILABLE)) { @@ -1492,6 +1493,152 @@ void EEJitManager::SetCpuInfo() } #endif // TARGET_ARM64 + // Now that we've queried the actual hardware support, we need to adjust what is actually supported based + // on some externally available config switches that exist so users can test code for downlevel hardware. + +#if defined(TARGET_AMD64) || defined(TARGET_X86) + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableHWIntrinsic)) + { + CPUCompileFlags.Clear(InstructionSet_X86Base); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAES)) + { + CPUCompileFlags.Clear(InstructionSet_AES); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX)) + { + CPUCompileFlags.Clear(InstructionSet_AVX); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVX2)) + { + CPUCompileFlags.Clear(InstructionSet_AVX2); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableAVXVNNI)) + { + CPUCompileFlags.Clear(InstructionSet_AVXVNNI); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableBMI1)) + { + CPUCompileFlags.Clear(InstructionSet_BMI1); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableBMI2)) + { + CPUCompileFlags.Clear(InstructionSet_BMI2); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableFMA)) + { + CPUCompileFlags.Clear(InstructionSet_FMA); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableLZCNT)) + { + CPUCompileFlags.Clear(InstructionSet_LZCNT); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnablePCLMULQDQ)) + { + CPUCompileFlags.Clear(InstructionSet_PCLMULQDQ); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnablePOPCNT)) + { + CPUCompileFlags.Clear(InstructionSet_POPCNT); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE)) + { + CPUCompileFlags.Clear(InstructionSet_SSE); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE2)) + { + CPUCompileFlags.Clear(InstructionSet_SSE2); + } + + // We need to additionally check that EXTERNAL_EnableSSE3_4 is set, as that + // is a prexisting config flag that controls the SSE3+ ISAs + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE3) || !CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE3_4)) + { + CPUCompileFlags.Clear(InstructionSet_SSE3); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE41)) + { + CPUCompileFlags.Clear(InstructionSet_SSE41); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSE42)) + { + CPUCompileFlags.Clear(InstructionSet_SSE42); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableSSSE3)) + { + CPUCompileFlags.Clear(InstructionSet_SSSE3); + } +#elif defined(TARGET_ARM64) + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableHWIntrinsic)) + { + CPUCompileFlags.Clear(InstructionSet_ArmBase); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64AdvSimd)) + { + CPUCompileFlags.Clear(InstructionSet_AdvSimd); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Aes)) + { + CPUCompileFlags.Clear(InstructionSet_Aes); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Atomics)) + { + CPUCompileFlags.Clear(InstructionSet_Atomics); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Crc32)) + { + CPUCompileFlags.Clear(InstructionSet_Crc32); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Dczva)) + { + CPUCompileFlags.Clear(InstructionSet_Dczva); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Dp)) + { + CPUCompileFlags.Clear(InstructionSet_Dp); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Rdm)) + { + CPUCompileFlags.Clear(InstructionSet_Rdm); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Sha1)) + { + CPUCompileFlags.Clear(InstructionSet_Sha1); + } + + if (!CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_EnableArm64Sha256)) + { + CPUCompileFlags.Clear(InstructionSet_Sha256); + } +#endif + + // These calls are very important as it ensures the flags are consistent with any + // removals specified above. This includes removing corresponding 64-bit ISAs + // and any other implications such as SSE2 depending on SSE or AdvSimd on ArmBase + CPUCompileFlags.Set64BitInstructionSetVariants(); CPUCompileFlags.EnsureValidInstructionSetSupport(); diff --git a/src/coreclr/vm/cominterfacemarshaler.cpp b/src/coreclr/vm/cominterfacemarshaler.cpp index c3a3fef8b8ad6..93101305133e1 100644 --- a/src/coreclr/vm/cominterfacemarshaler.cpp +++ b/src/coreclr/vm/cominterfacemarshaler.cpp @@ -14,7 +14,6 @@ #include "runtimecallablewrapper.h" #include "cominterfacemarshaler.h" #include "interopconverter.h" -#include "notifyexternals.h" #include "comdelegate.h" #include "olecontexthelpers.h" diff --git a/src/coreclr/vm/comreflectioncache.hpp b/src/coreclr/vm/comreflectioncache.hpp index 80909f94a0876..f2ac4b84ae64a 100644 --- a/src/coreclr/vm/comreflectioncache.hpp +++ b/src/coreclr/vm/comreflectioncache.hpp @@ -233,7 +233,7 @@ struct DispIDCacheElement pMT = var.pMT; strNameLength = var.strNameLength; lcid = var.lcid; - wcscpy_s (strName, COUNTOF(strName), var.strName); + wcscpy_s (strName, ARRAY_SIZE(strName), var.strName); return *this; } diff --git a/src/coreclr/vm/comtoclrcall.cpp b/src/coreclr/vm/comtoclrcall.cpp index 6337e9436b975..4568d9884f6e8 100644 --- a/src/coreclr/vm/comtoclrcall.cpp +++ b/src/coreclr/vm/comtoclrcall.cpp @@ -32,7 +32,6 @@ #include "mlinfo.h" #include "dbginterface.h" #include "sigbuilder.h" -#include "notifyexternals.h" #include "callconvbuilder.hpp" #include "comdelegate.h" #include "finalizerthread.h" diff --git a/src/coreclr/vm/dacenumerablehash.inl b/src/coreclr/vm/dacenumerablehash.inl index 4216ef3503372..049329bbfbc67 100644 --- a/src/coreclr/vm/dacenumerablehash.inl +++ b/src/coreclr/vm/dacenumerablehash.inl @@ -243,7 +243,7 @@ void DacEnumerableHashTable::GrowTable() template DWORD DacEnumerableHashTable::NextLargestPrime(DWORD dwNumber) { - for (DWORD i = 0; i < COUNTOF(g_rgPrimes); i++) + for (DWORD i = 0; i < ARRAY_SIZE(g_rgPrimes); i++) if (g_rgPrimes[i] >= dwNumber) { dwNumber = g_rgPrimes[i]; @@ -400,8 +400,8 @@ namespace HashTableDetail { // Use the C++ detection idiom (https://isocpp.org/blog/2017/09/detection-idiom-a-stopgap-for-concepts-simon-brand) to call the // derived table's EnumMemoryRegionsForEntry method if it defines one. - template - using void_t = void; + template struct make_void { using type = void; }; + template using void_t = typename make_void::type; template struct negation : std::integral_constant { }; diff --git a/src/coreclr/vm/debughelp.cpp b/src/coreclr/vm/debughelp.cpp index 56af42e9d4790..822ee4a233fb4 100644 --- a/src/coreclr/vm/debughelp.cpp +++ b/src/coreclr/vm/debughelp.cpp @@ -1015,7 +1015,7 @@ void printfToDbgOut(const char* fmt, ...) va_start(args, fmt); char buffer[4096]; - _vsnprintf_s(buffer, COUNTOF(buffer), _TRUNCATE, fmt, args); + _vsnprintf_s(buffer, ARRAY_SIZE(buffer), _TRUNCATE, fmt, args); va_end(args); OutputDebugStringA( buffer ); diff --git a/src/coreclr/vm/dllimport.cpp b/src/coreclr/vm/dllimport.cpp index 6c4ce7608660e..b9b86e3708cbd 100644 --- a/src/coreclr/vm/dllimport.cpp +++ b/src/coreclr/vm/dllimport.cpp @@ -959,7 +959,7 @@ class ILStubState : public StubState if (pTargetMD) { pTargetMD->GetMethodInfoWithNewSig(strNamespaceOrClassName, strMethodName, strMethodSignature); - uModuleId = (UINT64)pTargetMD->GetModule()->GetAddrModuleID(); + uModuleId = (UINT64)(TADDR)pTargetMD->GetModule_NoLogging(); } // diff --git a/src/coreclr/vm/dllimportcallback.cpp b/src/coreclr/vm/dllimportcallback.cpp index 455d33813eec0..65d2afd7d0512 100644 --- a/src/coreclr/vm/dllimportcallback.cpp +++ b/src/coreclr/vm/dllimportcallback.cpp @@ -195,37 +195,6 @@ extern "C" VOID STDCALL ReversePInvokeBadTransition() ); } -// Disable from a place that is calling into managed code via a UMEntryThunk. -extern "C" VOID STDCALL UMThunkStubRareDisableWorker(Thread *pThread, UMEntryThunk *pUMEntryThunk) -{ - STATIC_CONTRACT_THROWS; - STATIC_CONTRACT_GC_TRIGGERS; - - // Do not add a CONTRACT here. We haven't set up SEH. - - // WARNING!!!! - // when we start executing here, we are actually in cooperative mode. But we - // haven't synchronized with the barrier to reentry yet. So we are in a highly - // dangerous mode. If we call managed code, we will potentially be active in - // the GC heap, even as GC's are occuring! - - // We must do the following in this order, because otherwise we would be constructing - // the exception for the abort without synchronizing with the GC. Also, we have no - // CLR SEH set up, despite the fact that we may throw a ThreadAbortException. - pThread->RareDisablePreemptiveGC(); - pThread->HandleThreadAbort(); - -#ifdef DEBUGGING_SUPPORTED - // If the debugger is attached, we use this opportunity to see if - // we're disabling preemptive GC on the way into the runtime from - // unmanaged code. We end up here because - // Increment/DecrementTraceCallCount() will bump - // g_TrapReturningThreads for us. - if (CORDebuggerTraceCall()) - g_pDebugInterface->TraceCall((const BYTE *)pUMEntryThunk->GetManagedTarget()); -#endif // DEBUGGING_SUPPORTED -} - PCODE TheUMEntryPrestubWorker(UMEntryThunk * pUMEntryThunk) { STATIC_CONTRACT_THROWS; @@ -234,39 +203,13 @@ PCODE TheUMEntryPrestubWorker(UMEntryThunk * pUMEntryThunk) Thread * pThread = GetThreadNULLOk(); if (pThread == NULL) - pThread = CreateThreadBlockThrow(); - - GCX_COOP_THREAD_EXISTS(pThread); - - if (pThread->IsAbortRequested()) - pThread->HandleThreadAbort(); - - UMEntryThunk::DoRunTimeInit(pUMEntryThunk); - - return (PCODE)pUMEntryThunk->GetCode(); -} - -void RunTimeInit_Wrapper(LPVOID /* UMThunkMarshInfo * */ ptr) -{ - WRAPPER_NO_CONTRACT; - - UMEntryThunk::DoRunTimeInit((UMEntryThunk*)ptr); -} - - -// asm entrypoint -void STDCALL UMEntryThunk::DoRunTimeInit(UMEntryThunk* pUMEntryThunk) -{ - - CONTRACTL { - THROWS; - GC_TRIGGERS; - MODE_COOPERATIVE; - ENTRY_POINT; - PRECONDITION(CheckPointer(pUMEntryThunk)); + CREATETHREAD_IF_NULL_FAILFAST(pThread, W("Failed to setup new thread during reverse P/Invoke")); } - CONTRACTL_END; + + // Verify the current thread isn't in COOP mode. + if (pThread->PreemptiveGCDisabled()) + ReversePInvokeBadTransition(); INSTALL_MANAGED_EXCEPTION_DISPATCHER; // this method is called by stubs which are called by managed code, @@ -274,15 +217,13 @@ void STDCALL UMEntryThunk::DoRunTimeInit(UMEntryThunk* pUMEntryThunk) // exceptions don't leak out into managed code. INSTALL_UNWIND_AND_CONTINUE_HANDLER; - { - GCX_PREEMP(); - - ExecutableWriterHolder uMEntryThunkWriterHolder(pUMEntryThunk, sizeof(UMEntryThunk)); - uMEntryThunkWriterHolder.GetRW()->RunTimeInit(pUMEntryThunk); - } + ExecutableWriterHolder uMEntryThunkWriterHolder(pUMEntryThunk, sizeof(UMEntryThunk)); + uMEntryThunkWriterHolder.GetRW()->RunTimeInit(pUMEntryThunk); UNINSTALL_UNWIND_AND_CONTINUE_HANDLER; UNINSTALL_MANAGED_EXCEPTION_DISPATCHER; + + return (PCODE)pUMEntryThunk->GetCode(); } UMEntryThunk* UMEntryThunk::CreateUMEntryThunk() diff --git a/src/coreclr/vm/dllimportcallback.h b/src/coreclr/vm/dllimportcallback.h index 14b7db5704824..fb2214a8c18d5 100644 --- a/src/coreclr/vm/dllimportcallback.h +++ b/src/coreclr/vm/dllimportcallback.h @@ -16,6 +16,12 @@ #include "class.h" #include "dllimport.h" +class UMThunkMarshInfo; +typedef DPTR(class UMThunkMarshInfo) PTR_UMThunkMarshInfo; + +class UMEntryThunk; +typedef DPTR(class UMEntryThunk) PTR_UMEntryThunk; + //---------------------------------------------------------------------- // This structure collects all information needed to marshal an // unmanaged->managed thunk. The only information missing is the @@ -189,9 +195,6 @@ class UMEntryThunk #endif // _DEBUG } - // asm entrypoint - static VOID STDCALL DoRunTimeInit(UMEntryThunk* pThis); - PCODE GetManagedTarget() const { CONTRACT (PCODE) @@ -396,14 +399,7 @@ class UMEntryThunkCache }; #if defined(TARGET_X86) && !defined(FEATURE_STUBS_AS_IL) -//------------------------------------------------------------------------- -// One-time creation of special prestub to initialize UMEntryThunks. -//------------------------------------------------------------------------- -Stub *GenerateUMThunkPrestub(); - EXCEPTION_HANDLER_DECL(FastNExportExceptHandler); -EXCEPTION_HANDLER_DECL(UMThunkPrestubHandler); - #endif // TARGET_X86 && !FEATURE_STUBS_AS_IL extern "C" void TheUMEntryPrestub(void); diff --git a/src/coreclr/vm/dwreport.cpp b/src/coreclr/vm/dwreport.cpp index dac79b49206e1..1032725eb854b 100644 --- a/src/coreclr/vm/dwreport.cpp +++ b/src/coreclr/vm/dwreport.cpp @@ -888,19 +888,19 @@ HRESULT GetBucketParametersForCurrentException( if (hr == S_OK) { // Event type name. - wcsncpy_s(pParams->pszEventTypeName, COUNTOF(pParams->pszEventTypeName), gmb.wzEventTypeName, _TRUNCATE); + wcsncpy_s(pParams->pszEventTypeName, ARRAY_SIZE(pParams->pszEventTypeName), gmb.wzEventTypeName, _TRUNCATE); // Buckets. Mind the 1-based vs 0-based. - wcsncpy_s(pParams->pszParams[0], COUNTOF(pParams->pszParams[0]), gmb.wzP1, _TRUNCATE); - wcsncpy_s(pParams->pszParams[1], COUNTOF(pParams->pszParams[1]), gmb.wzP2, _TRUNCATE); - wcsncpy_s(pParams->pszParams[2], COUNTOF(pParams->pszParams[2]), gmb.wzP3, _TRUNCATE); - wcsncpy_s(pParams->pszParams[3], COUNTOF(pParams->pszParams[3]), gmb.wzP4, _TRUNCATE); - wcsncpy_s(pParams->pszParams[4], COUNTOF(pParams->pszParams[4]), gmb.wzP5, _TRUNCATE); - wcsncpy_s(pParams->pszParams[5], COUNTOF(pParams->pszParams[5]), gmb.wzP6, _TRUNCATE); - wcsncpy_s(pParams->pszParams[6], COUNTOF(pParams->pszParams[6]), gmb.wzP7, _TRUNCATE); - wcsncpy_s(pParams->pszParams[7], COUNTOF(pParams->pszParams[7]), gmb.wzP8, _TRUNCATE); - wcsncpy_s(pParams->pszParams[8], COUNTOF(pParams->pszParams[8]), gmb.wzP9, _TRUNCATE); - wcsncpy_s(pParams->pszParams[9], COUNTOF(pParams->pszParams[9]), gmb.wzP10, _TRUNCATE); + wcsncpy_s(pParams->pszParams[0], ARRAY_SIZE(pParams->pszParams[0]), gmb.wzP1, _TRUNCATE); + wcsncpy_s(pParams->pszParams[1], ARRAY_SIZE(pParams->pszParams[1]), gmb.wzP2, _TRUNCATE); + wcsncpy_s(pParams->pszParams[2], ARRAY_SIZE(pParams->pszParams[2]), gmb.wzP3, _TRUNCATE); + wcsncpy_s(pParams->pszParams[3], ARRAY_SIZE(pParams->pszParams[3]), gmb.wzP4, _TRUNCATE); + wcsncpy_s(pParams->pszParams[4], ARRAY_SIZE(pParams->pszParams[4]), gmb.wzP5, _TRUNCATE); + wcsncpy_s(pParams->pszParams[5], ARRAY_SIZE(pParams->pszParams[5]), gmb.wzP6, _TRUNCATE); + wcsncpy_s(pParams->pszParams[6], ARRAY_SIZE(pParams->pszParams[6]), gmb.wzP7, _TRUNCATE); + wcsncpy_s(pParams->pszParams[7], ARRAY_SIZE(pParams->pszParams[7]), gmb.wzP8, _TRUNCATE); + wcsncpy_s(pParams->pszParams[8], ARRAY_SIZE(pParams->pszParams[8]), gmb.wzP9, _TRUNCATE); + wcsncpy_s(pParams->pszParams[9], ARRAY_SIZE(pParams->pszParams[9]), gmb.wzP10, _TRUNCATE); // All good. pParams->fInited = TRUE; diff --git a/src/coreclr/vm/ecalllist.h b/src/coreclr/vm/ecalllist.h index be7a6826854f0..f3ada145b6839 100644 --- a/src/coreclr/vm/ecalllist.h +++ b/src/coreclr/vm/ecalllist.h @@ -322,8 +322,6 @@ FCFuncStart(gDelegateFuncs) FCFuncEnd() FCFuncStart(gMathFuncs) - FCFuncElementSig("Abs", &gsig_SM_Dbl_RetDbl, COMDouble::Abs) - FCFuncElementSig("Abs", &gsig_SM_Flt_RetFlt, COMSingle::Abs) FCFuncElement("Acos", COMDouble::Acos) FCFuncElement("Acosh", COMDouble::Acosh) FCFuncElement("Asin", COMDouble::Asin) diff --git a/src/coreclr/vm/excep.cpp b/src/coreclr/vm/excep.cpp index 6c92766557acd..fa2b8ffc7dfe3 100644 --- a/src/coreclr/vm/excep.cpp +++ b/src/coreclr/vm/excep.cpp @@ -11906,8 +11906,8 @@ VOID DECLSPEC_NORETURN ThrowFieldLayoutError(mdTypeDef cl, // cl } CHAR offsetBuf[16]; - sprintf_s(offsetBuf, COUNTOF(offsetBuf), "%d", dwOffset); - offsetBuf[COUNTOF(offsetBuf) - 1] = '\0'; + sprintf_s(offsetBuf, ARRAY_SIZE(offsetBuf), "%d", dwOffset); + offsetBuf[ARRAY_SIZE(offsetBuf) - 1] = '\0'; pModule->GetAssembly()->ThrowTypeLoadException(pszNamespace, pszName, diff --git a/src/coreclr/vm/frames.cpp b/src/coreclr/vm/frames.cpp index 77bcb178bb49c..9377b4ec028b7 100644 --- a/src/coreclr/vm/frames.cpp +++ b/src/coreclr/vm/frames.cpp @@ -63,24 +63,15 @@ void Frame::Log() { MethodDesc* method = GetFunction(); -#ifdef TARGET_X86 - if (GetVTablePtr() == UMThkCallFrame::GetMethodFrameVPtr()) - method = ((UMThkCallFrame*) this)->GetUMEntryThunk()->GetMethod(); -#endif - STRESS_LOG3(LF_STUBS, LL_INFO1000000, "STUBS: In Stub with Frame %p assoc Method %pM FrameType = %pV\n", this, method, *((void**) this)); char buff[64]; const char* frameType; if (GetVTablePtr() == PrestubMethodFrame::GetMethodFrameVPtr()) frameType = "PreStub"; -#ifdef TARGET_X86 - else if (GetVTablePtr() == UMThkCallFrame::GetMethodFrameVPtr()) - frameType = "UMThkCallFrame"; -#endif else if (GetVTablePtr() == PInvokeCalliFrame::GetMethodFrameVPtr()) { - sprintf_s(buff, COUNTOF(buff), "PInvoke CALLI target" FMT_ADDR, + sprintf_s(buff, ARRAY_SIZE(buff), "PInvoke CALLI target" FMT_ADDR, DBG_ADDR(((PInvokeCalliFrame*)this)->GetPInvokeCalliTarget())); frameType = buff; } @@ -257,7 +248,7 @@ void Frame::LogFrame( { _ASSERTE(!"New Frame type needs to be added to FrameTypeName()"); // Pointer is up to 17chars + vtbl@ = 22 chars - sprintf_s(buf, COUNTOF(buf), "vtbl@%p", (VOID *)GetVTablePtr()); + sprintf_s(buf, ARRAY_SIZE(buf), "vtbl@%p", (VOID *)GetVTablePtr()); pFrameType = buf; } @@ -1603,32 +1594,6 @@ void ComMethodFrame::DoSecondPassHandlerCleanup(Frame * pCurFrame) #endif // FEATURE_COMINTEROP - -#ifdef TARGET_X86 - -PTR_UMEntryThunk UMThkCallFrame::GetUMEntryThunk() -{ - LIMITED_METHOD_DAC_CONTRACT; - return dac_cast(GetDatum()); -} - -#ifdef DACCESS_COMPILE -void UMThkCallFrame::EnumMemoryRegions(CLRDataEnumMemoryFlags flags) -{ - WRAPPER_NO_CONTRACT; - UnmanagedToManagedFrame::EnumMemoryRegions(flags); - - // Pieces of the UMEntryThunk need to be saved. - UMEntryThunk *pThunk = GetUMEntryThunk(); - DacEnumMemoryRegion(dac_cast(pThunk), sizeof(UMEntryThunk)); - - UMThunkMarshInfo *pMarshInfo = pThunk->GetUMThunkMarshInfo(); - DacEnumMemoryRegion(dac_cast(pMarshInfo), sizeof(UMThunkMarshInfo)); -} -#endif - -#endif // TARGET_X86 - #ifndef DACCESS_COMPILE #if defined(_MSC_VER) && defined(TARGET_X86) @@ -1952,16 +1917,18 @@ VOID InlinedCallFrame::Init() } - +#ifdef FEATURE_COMINTEROP void UnmanagedToManagedFrame::ExceptionUnwind() { WRAPPER_NO_CONTRACT; AppDomain::ExceptionUnwind(this); } +#endif // FEATURE_COMINTEROP #endif // !DACCESS_COMPILE +#ifdef FEATURE_COMINTEROP PCODE UnmanagedToManagedFrame::GetReturnAddress() { WRAPPER_NO_CONTRACT; @@ -1980,6 +1947,7 @@ PCODE UnmanagedToManagedFrame::GetReturnAddress() return pRetAddr; } } +#endif // FEATURE_COMINTEROP #ifndef DACCESS_COMPILE //================================================================================= diff --git a/src/coreclr/vm/frames.h b/src/coreclr/vm/frames.h index c2946ced0b2f6..82e57cbbb0401 100644 --- a/src/coreclr/vm/frames.h +++ b/src/coreclr/vm/frames.h @@ -90,23 +90,18 @@ // | | // | +-TPMethodFrame - for calls on transparent proxy // | +#ifdef FEATURE_COMINTEROP // +-UnmanagedToManagedFrame - this frame represents a transition from // | | unmanaged code back to managed code. It's // | | main functions are to stop COM+ exception // | | propagation and to expose unmanaged parameters. // | | -#ifdef FEATURE_COMINTEROP -// | | // | +-ComMethodFrame - this frame represents a transition from // | | com to com+ // | | // | +-ComPrestubMethodFrame - prestub frame for calls from COM to CLR // | #endif //FEATURE_COMINTEROP -#ifdef TARGET_X86 -// | +-UMThkCallFrame - this frame represents an unmanaged->managed -// | transition through N/Direct -#endif #if defined(TARGET_X86) && !defined(UNIX_X86_ABI) // +-TailCallFrame - padding for tailcalls // | @@ -172,16 +167,9 @@ Delegate over a native function pointer: Reverse P/Invoke (used for C++ exports & fixups as well as delegates obtained from function pointers): Normal stub: - x86: The stub is generated by UMEntryThunk::CompileUMThunkWorker - (in DllImportCallback.cpp) and it is frameless. It calls directly - the managed target or to IL stub if marshaling is required. - non-x86: The stub exists statically as UMThunkStub and calls to IL stub. + The stub exists statically as UMThunkStub and calls to IL stub. Prestub: - The prestub is generated by GenerateUMThunkPrestub (x86) or exists statically - as TheUMEntryPrestub (64-bit), and it erects an UMThkCallFrame frame. - -Reverse P/Invoke AppDomain selector stub: - The asm helper is IJWNOADThunkJumpTarget (in asmhelpers.asm) and it is frameless. + The prestub exists statically as TheUMEntryPrestub. //------------------------------------------------------------------------ #endif // 0 @@ -212,8 +200,8 @@ FRAME_TYPE_NAME(HelperMethodFrame_3OBJ) FRAME_TYPE_NAME(HelperMethodFrame_PROTECTOBJ) FRAME_ABSTRACT_TYPE_NAME(FramedMethodFrame) FRAME_TYPE_NAME(MulticastFrame) -FRAME_ABSTRACT_TYPE_NAME(UnmanagedToManagedFrame) #ifdef FEATURE_COMINTEROP +FRAME_ABSTRACT_TYPE_NAME(UnmanagedToManagedFrame) FRAME_TYPE_NAME(ComMethodFrame) FRAME_TYPE_NAME(ComPlusMethodFrame) FRAME_TYPE_NAME(ComPrestubMethodFrame) @@ -238,9 +226,6 @@ FRAME_TYPE_NAME(DebuggerClassInitMarkFrame) FRAME_TYPE_NAME(DebuggerSecurityCodeMarkFrame) FRAME_TYPE_NAME(DebuggerExitFrame) FRAME_TYPE_NAME(DebuggerU2MCatchHandlerFrame) -#ifdef TARGET_X86 -FRAME_TYPE_NAME(UMThkCallFrame) -#endif FRAME_TYPE_NAME(InlinedCallFrame) #if defined(TARGET_X86) && !defined(UNIX_X86_ABI) FRAME_TYPE_NAME(TailCallFrame) @@ -281,9 +266,6 @@ class Frame; class FramedMethodFrame; typedef VPTR(class FramedMethodFrame) PTR_FramedMethodFrame; struct HijackArgs; -class UMEntryThunk; -class UMThunkMarshInfo; -class Marshaler; struct ResolveCacheElem; #if defined(DACCESS_COMPILE) class DacDbiInterfaceImpl; @@ -1814,6 +1796,8 @@ class MulticastFrame : public TransitionFrame }; +#ifdef FEATURE_COMINTEROP + //----------------------------------------------------------------------- // Transition frame from unmanaged to managed //----------------------------------------------------------------------- @@ -1922,8 +1906,6 @@ class UnmanagedToManagedFrame : public Frame #endif }; -#ifdef FEATURE_COMINTEROP - //------------------------------------------------------------------------ // This frame represents a transition from COM to COM+ //------------------------------------------------------------------------ @@ -2774,43 +2756,6 @@ class DebuggerU2MCatchHandlerFrame : public Frame DEFINE_VTABLE_GETTER_AND_DTOR(DebuggerU2MCatchHandlerFrame) }; - -class UMThunkMarshInfo; -typedef DPTR(class UMThunkMarshInfo) PTR_UMThunkMarshInfo; - -class UMEntryThunk; -typedef DPTR(class UMEntryThunk) PTR_UMEntryThunk; - -#if defined(TARGET_X86) -//------------------------------------------------------------------------ -// This frame guards an unmanaged->managed transition thru a UMThk -//------------------------------------------------------------------------ - -class UMThkCallFrame : public UnmanagedToManagedFrame -{ - VPTR_VTABLE_CLASS(UMThkCallFrame, UnmanagedToManagedFrame) - -public: - -#ifdef DACCESS_COMPILE - virtual void EnumMemoryRegions(CLRDataEnumMemoryFlags flags); -#endif - - PTR_UMEntryThunk GetUMEntryThunk(); - - static int GetOffsetOfUMEntryThunk() - { - WRAPPER_NO_CONTRACT; - return GetOffsetOfDatum(); - } - -protected: - - // Keep as last entry in class - DEFINE_VTABLE_GETTER_AND_CTOR_AND_DTOR(UMThkCallFrame) -}; -#endif // TARGET_X86 && !TARGET_UNIX - // Frame for the Reverse PInvoke (i.e. UnmanagedCallersOnlyAttribute). struct ReversePInvokeFrame { @@ -2821,29 +2766,6 @@ struct ReversePInvokeFrame #endif }; -#if defined(TARGET_X86) && defined(FEATURE_COMINTEROP) -//------------------------------------------------------------------------- -// Exception handler for COM to managed frame -// and the layout of the exception registration record structure in the stack -// the layout is similar to the NT's EXCEPTIONREGISTRATION record -// followed by the UnmanagedToManagedFrame specific info - -struct ComToManagedExRecord -{ - EXCEPTION_REGISTRATION_RECORD m_ExReg; - ArgumentRegisters m_argRegs; - GSCookie m_gsCookie; - UMThkCallFrame m_frame; - - UnmanagedToManagedFrame * GetCurrFrame() - { - LIMITED_METHOD_CONTRACT; - return &m_frame; - } -}; -#endif // TARGET_X86 && FEATURE_COMINTEROP - - //------------------------------------------------------------------------ // This frame is pushed by any JIT'ted method that contains one or more // inlined N/Direct calls. Note that the JIT'ted method keeps it pushed diff --git a/src/coreclr/vm/h2inc.pl b/src/coreclr/vm/h2inc.pl deleted file mode 100644 index 6d2e0c3e03dcf..0000000000000 --- a/src/coreclr/vm/h2inc.pl +++ /dev/null @@ -1,61 +0,0 @@ -# Licensed to the .NET Foundation under one or more agreements. -# The .NET Foundation licenses this file to you under the MIT license. - -# C to MASM include file translator -# This is replacement for the deprecated h2inc tool that used to be part of VS. - -use File::Basename; - -sub ProcessFile($) { - my ($input_file) = @_; - - local *INPUT_FILE; - if (!open(INPUT_FILE, $input_file)) - { - print "#error: File can not be opened: $input_file\n"; - return; - } - - print ("// File start: $input_file\n"); - - while() { - # Skip all pragmas - if (m/^\s*#\s*pragma/) { - next; - } - - # Expand includes. - if (m/\s*#\s*include\s*\"(.+)\"/) { - ProcessFile(dirname($input_file) . "/" . $1); - next; - } - - # Augment #defines with their MASM equivalent - if (m/^\s*#\s*define\s+(\S+)\s+(.*)/) { - my $name = $1; - my $value = $2; - - # Note that we do not handle multiline constants - - # Strip comments from value - $value =~ s/\/\/.*//; - $value =~ s/\/\*.*\*\///g; - - # Strip whitespaces from value - $value =~ s/\s+$//; - - # ignore #defines with arguments - if (!($name =~ m/\(/)) { - my $number = 0; - $number |= ($value =~ s/\b0x(\w+)\b/0\1h/g); # Convert hex constants - $number |= ($value =~ s/(-?\b\d+\b)/\1t/g); # Convert dec constants - print $number ? "$name EQU $value\n" : "$name TEXTEQU <$value>\n"; - } - } - print; - } - - print ("// File end: $input_file\n"); -} - -ProcessFile($ARGV[0]); diff --git a/src/coreclr/vm/h2inc.ps1 b/src/coreclr/vm/h2inc.ps1 deleted file mode 100644 index f2c2c07f26582..0000000000000 --- a/src/coreclr/vm/h2inc.ps1 +++ /dev/null @@ -1,69 +0,0 @@ -# Licensed to the .NET Foundation under one or more agreements. -# The .NET Foundation licenses this file to you under the MIT license. - -# C to MASM include file translator -# This is replacement for the deprecated h2inc tool that used to be part of VS. - -# -# The use of [console]::WriteLine (instead of Write-Output) is intentional. -# PowerShell 2.0 (installed by default on Windows 7) wraps lines written with -# Write-Output at whatever column width is being used by the current terminal, -# even when output is being redirected to a file. We can't have this behavior -# because it will cause the generated file to be malformed. -# - -Function ProcessFile($filePath) { - - [console]::WriteLine("// File start: $filePath") - - Get-Content $filePath | ForEach-Object { - - if ($_ -match "^\s*#\spragma") { - # Ignore pragmas - return - } - - if ($_ -match "^\s*#\s*include\s*`"(.*)`"") - { - # Expand includes. - ProcessFile(Join-Path (Split-Path -Parent $filePath) $Matches[1]) - return - } - - if ($_ -match "^\s*#define\s+(\S+)\s*(.*)") - { - # Augment #defines with their MASM equivalent - $name = $Matches[1] - $value = $Matches[2] - - # Note that we do not handle multiline constants - - # Strip comments from value - $value = $value -replace "//.*", "" - $value = $value -replace "/\*.*\*/", "" - - # Strip whitespaces from value - $value = $value -replace "\s+$", "" - - # ignore #defines with arguments - if ($name -notmatch "\(") { - $HEX_NUMBER_PATTERN = "\b0x(\w+)\b" - $DECIMAL_NUMBER_PATTERN = "(-?\b\d+\b)" - - if ($value -match $HEX_NUMBER_PATTERN -or $value -match $DECIMAL_NUMBER_PATTERN) { - $value = $value -replace $HEX_NUMBER_PATTERN, "0`$1h" # Convert hex constants - $value = $value -replace $DECIMAL_NUMBER_PATTERN, "`$1t" # Convert dec constants - [console]::WriteLine("$name EQU $value") - } else { - [console]::WriteLine("$name TEXTEQU <$value>") - } - } - } - - [console]::WriteLine("$_") - } - - [console]::WriteLine("// File end: $filePath") -} - -ProcessFile $args[0] diff --git a/src/coreclr/vm/i386/asmhelpers.asm b/src/coreclr/vm/i386/asmhelpers.asm index d3eb78da47256..896c249822c55 100644 --- a/src/coreclr/vm/i386/asmhelpers.asm +++ b/src/coreclr/vm/i386/asmhelpers.asm @@ -43,7 +43,6 @@ EXTERN _COMPlusFrameHandlerRevCom:PROC endif ; FEATURE_COMINTEROP EXTERN __alloca_probe:PROC EXTERN _NDirectImportWorker@4:PROC -EXTERN _UMThunkStubRareDisableWorker@8:PROC EXTERN _VarargPInvokeStubWorker@12:PROC EXTERN _GenericPInvokeCalliStubWorker@12:PROC @@ -53,6 +52,7 @@ EXTERN _CopyCtorCallStubWorker@4:PROC endif EXTERN _PreStubWorker@8:PROC +EXTERN _TheUMEntryPrestubWorker@4:PROC ifdef FEATURE_COMINTEROP EXTERN _CLRToCOMWorker@8:PROC @@ -255,9 +255,6 @@ COMPlusNestedExceptionHandler proto c FastNExportExceptHandler proto c .safeseh FastNExportExceptHandler -UMThunkPrestubHandler proto c -.safeseh UMThunkPrestubHandler - ifdef FEATURE_COMINTEROP COMPlusFrameHandlerRevCom proto c .safeseh COMPlusFrameHandlerRevCom @@ -872,23 +869,6 @@ getFPReturn4: retn 8 _getFPReturn@8 endp -; VOID __cdecl UMThunkStubRareDisable() -; -; @todo: this is very similar to StubRareDisable -; -_UMThunkStubRareDisable proc public - push eax - push ecx - - push eax ; Push the UMEntryThunk - push ecx ; Push thread - call _UMThunkStubRareDisableWorker@8 - - pop ecx - pop eax - retn -_UMThunkStubRareDisable endp - ; void __stdcall JIT_ProfilerEnterLeaveTailcallStub(UINT_PTR ProfilerHandle) _JIT_ProfilerEnterLeaveTailcallStub@4 proc public @@ -1432,6 +1412,22 @@ public _ThePreStubPatchLabel@0 ret _ThePreStubPatch@0 endp +_TheUMEntryPrestub@0 proc public + ; push argument registers + push ecx + push edx + + push eax ; UMEntryThunk* + call _TheUMEntryPrestubWorker@4 + + ; pop argument registers + pop edx + pop ecx + + ; eax = PCODE + jmp eax ; Tail Jmp +_TheUMEntryPrestub@0 endp + ifdef FEATURE_COMINTEROP ;========================================================================== ; CLR -> COM generic or late-bound call diff --git a/src/coreclr/vm/i386/cgenx86.cpp b/src/coreclr/vm/i386/cgenx86.cpp index f0a81d6daeea1..d2d5d1676e95c 100644 --- a/src/coreclr/vm/i386/cgenx86.cpp +++ b/src/coreclr/vm/i386/cgenx86.cpp @@ -931,58 +931,6 @@ WORD GetUnpatchedCodeData(LPCBYTE pAddr) #ifndef DACCESS_COMPILE -#if defined(TARGET_X86) && !defined(FEATURE_STUBS_AS_IL) -//------------------------------------------------------------------------- -// One-time creation of special prestub to initialize UMEntryThunks. -//------------------------------------------------------------------------- -Stub *GenerateUMThunkPrestub() -{ - CONTRACT(Stub*) - { - STANDARD_VM_CHECK; - POSTCONDITION(CheckPointer(RETVAL)); - } - CONTRACT_END; - - CPUSTUBLINKER sl; - CPUSTUBLINKER *psl = &sl; - - CodeLabel* rgRareLabels[] = { psl->NewCodeLabel(), - psl->NewCodeLabel(), - psl->NewCodeLabel() - }; - - - CodeLabel* rgRejoinLabels[] = { psl->NewCodeLabel(), - psl->NewCodeLabel(), - psl->NewCodeLabel() - }; - - // emit the initial prolog - psl->EmitComMethodStubProlog(UMThkCallFrame::GetMethodFrameVPtr(), rgRareLabels, rgRejoinLabels, FALSE /*Don't profile*/); - - // mov ecx, [esi+UMThkCallFrame.pUMEntryThunk] - psl->X86EmitIndexRegLoad(kECX, kESI, UMThkCallFrame::GetOffsetOfUMEntryThunk()); - - // The call conv is a __stdcall - psl->X86EmitPushReg(kECX); - - // call UMEntryThunk::DoRunTimeInit - psl->X86EmitCall(psl->NewExternalCodeLabel((LPVOID)UMEntryThunk::DoRunTimeInit), 4); - - // mov ecx, [esi+UMThkCallFrame.pUMEntryThunk] - psl->X86EmitIndexRegLoad(kEAX, kESI, UMThkCallFrame::GetOffsetOfUMEntryThunk()); - - // lea eax, [eax + UMEntryThunk.m_code] // point to fixedup UMEntryThunk - psl->X86EmitOp(0x8d, kEAX, kEAX, - UMEntryThunk::GetCodeOffset() + UMEntryThunkCode::GetEntryPointOffset()); - - psl->EmitComMethodStubEpilog(UMThkCallFrame::GetMethodFrameVPtr(), rgRareLabels, rgRejoinLabels, FALSE /*Don't profile*/); - - RETURN psl->Link(SystemDomain::GetGlobalLoaderAllocator()->GetExecutableHeap()); -} -#endif // TARGET_X86 && !FEATURE_STUBS_AS_IL - Stub *GenerateInitPInvokeFrameHelper() { CONTRACT(Stub*) diff --git a/src/coreclr/vm/i386/excepx86.cpp b/src/coreclr/vm/i386/excepx86.cpp index 3d2e0e4dddeca..15dd0667dd6c4 100644 --- a/src/coreclr/vm/i386/excepx86.cpp +++ b/src/coreclr/vm/i386/excepx86.cpp @@ -113,17 +113,6 @@ static void RtlUnwindCallback() _ASSERTE(!"Should never get here"); } -BOOL NExportSEH(EXCEPTION_REGISTRATION_RECORD* pEHR) -{ - LIMITED_METHOD_CONTRACT; - - if ((LPVOID)pEHR->Handler == (LPVOID)UMThunkPrestubHandler) - { - return TRUE; - } - return FALSE; -} - BOOL FastNExportSEH(EXCEPTION_REGISTRATION_RECORD* pEHR) { LIMITED_METHOD_CONTRACT; @@ -156,9 +145,8 @@ BOOL IsUnmanagedToManagedSEHHandler(EXCEPTION_REGISTRATION_RECORD *pEstablisherF // // ComPlusFrameSEH() is for COMPlusFrameHandler & COMPlusNestedExceptionHandler. // FastNExportSEH() is for FastNExportExceptHandler. - // NExportSEH() is for UMThunkPrestubHandler. // - return (ComPlusFrameSEH(pEstablisherFrame) || FastNExportSEH(pEstablisherFrame) || NExportSEH(pEstablisherFrame) || ReverseCOMSEH(pEstablisherFrame)); + return (ComPlusFrameSEH(pEstablisherFrame) || FastNExportSEH(pEstablisherFrame) || ReverseCOMSEH(pEstablisherFrame)); } Frame *GetCurrFrame(EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame) @@ -166,10 +154,7 @@ Frame *GetCurrFrame(EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame) Frame *pFrame; WRAPPER_NO_CONTRACT; _ASSERTE(IsUnmanagedToManagedSEHHandler(pEstablisherFrame)); - if (NExportSEH(pEstablisherFrame)) - pFrame = ((ComToManagedExRecord *)pEstablisherFrame)->GetCurrFrame(); - else - pFrame = ((FrameHandlerExRecord *)pEstablisherFrame)->GetCurrFrame(); + pFrame = ((FrameHandlerExRecord *)pEstablisherFrame)->GetCurrFrame(); // Assert that the exception frame is on the thread or that the exception frame is the top frame. _ASSERTE(GetThreadNULLOk() == NULL || GetThread()->GetFrame() == (Frame*)-1 || GetThread()->GetFrame() <= pFrame); @@ -3384,52 +3369,6 @@ EXCEPTION_HANDLER_IMPL(FastNExportExceptHandler) return retval; } - -// Just like a regular NExport handler -- except it pops an extra frame on unwind. A handler -// like this is needed by the COMMethodStubProlog code. It first pushes a frame -- and then -// pushes a handler. When we unwind, we need to pop the extra frame to avoid corrupting the -// frame chain in the event of an unmanaged catcher. -// -EXCEPTION_HANDLER_IMPL(UMThunkPrestubHandler) -{ - // @todo: we'd like to have a dynamic contract here, but there's a problem. (Bug 129180) Enter on the CRST used - // in HandleManagedFault leaves the no-trigger count incremented. The destructor of this contract will restore - // it to zero, then when we leave the CRST in LinkFrameAndThrow, we assert because we're trying to decrement the - // gc-trigger count down past zero. The solution is to fix what we're doing with this CRST. - STATIC_CONTRACT_THROWS; // COMPlusFrameHandler throws - STATIC_CONTRACT_GC_TRIGGERS; - STATIC_CONTRACT_MODE_ANY; - - EXCEPTION_DISPOSITION retval = ExceptionContinueSearch; - - // We must forward to the COMPlusFrameHandler. This will unwind the Frame Chain up to here, and also leave the - // preemptive GC mode set correctly. - retval = EXCEPTION_HANDLER_FWD(COMPlusFrameHandler); - -#ifdef _DEBUG - // If the exception is escaping the last CLR personality routine on the stack, - // then state a flag on the thread to indicate so. - if (retval == ExceptionContinueSearch) - { - SetReversePInvokeEscapingUnhandledExceptionStatus(IS_UNWINDING(pExceptionRecord->ExceptionFlags), pEstablisherFrame); - } -#endif // _DEBUG - - if (IS_UNWINDING(pExceptionRecord->ExceptionFlags)) - { - // Pops an extra frame on unwind. - - GCX_COOP(); // Must be cooperative to modify frame chain. - - Thread *pThread = GetThread(); - Frame *pFrame = pThread->GetFrame(); - pFrame->ExceptionUnwind(); - pFrame->Pop(pThread); - } - - return retval; -} - #ifdef FEATURE_COMINTEROP // The reverse COM interop path needs to be sure to pop the ComMethodFrame that is pushed, but we do not want // to have an additional FS:0 handler between the COM callsite and the call into managed. So we push this diff --git a/src/coreclr/vm/i386/stublinkerx86.cpp b/src/coreclr/vm/i386/stublinkerx86.cpp index 685883dd1ae80..74d55fd4544db 100644 --- a/src/coreclr/vm/i386/stublinkerx86.cpp +++ b/src/coreclr/vm/i386/stublinkerx86.cpp @@ -37,7 +37,6 @@ #include "runtimecallablewrapper.h" #include "comcache.h" #include "olevariant.h" -#include "notifyexternals.h" #endif // FEATURE_COMINTEROP #if defined(_DEBUG) && defined(STUBLINKER_GENERATES_UNWIND_INFO) @@ -2446,44 +2445,21 @@ VOID StubLinkerCPU::X86EmitCurrentThreadFetch(X86Reg dstreg, unsigned preservedR #endif // TARGET_UNIX } -#if defined(TARGET_X86) +#if defined(FEATURE_COMINTEROP) && defined(TARGET_X86) -#if defined(PROFILING_SUPPORTED) && !defined(FEATURE_STUBS_AS_IL) +#if defined(PROFILING_SUPPORTED) VOID StubLinkerCPU::EmitProfilerComCallProlog(TADDR pFrameVptr, X86Reg regFrame) { STANDARD_VM_CONTRACT; - if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr()) - { - // Load the methoddesc into ECX (UMThkCallFrame->m_pvDatum->m_pMD) - X86EmitIndexRegLoad(kECX, regFrame, UMThkCallFrame::GetOffsetOfDatum()); - X86EmitIndexRegLoad(kECX, kECX, UMEntryThunk::GetOffsetOfMethodDesc()); - - // Push arguments and notify profiler - X86EmitPushImm32(COR_PRF_TRANSITION_CALL); // Reason - X86EmitPushReg(kECX); // MethodDesc* - X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerUnmanagedToManagedTransitionMD), 2*sizeof(void*)); - } + // Load the methoddesc into ECX (Frame->m_pvDatum->m_pMD) + X86EmitIndexRegLoad(kECX, regFrame, ComMethodFrame::GetOffsetOfDatum()); + X86EmitIndexRegLoad(kECX, kECX, ComCallMethodDesc::GetOffsetOfMethodDesc()); -#ifdef FEATURE_COMINTEROP - else if (pFrameVptr == ComMethodFrame::GetMethodFrameVPtr()) - { - // Load the methoddesc into ECX (Frame->m_pvDatum->m_pMD) - X86EmitIndexRegLoad(kECX, regFrame, ComMethodFrame::GetOffsetOfDatum()); - X86EmitIndexRegLoad(kECX, kECX, ComCallMethodDesc::GetOffsetOfMethodDesc()); - - // Push arguments and notify profiler - X86EmitPushImm32(COR_PRF_TRANSITION_CALL); // Reason - X86EmitPushReg(kECX); // MethodDesc* - X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerUnmanagedToManagedTransitionMD), 2*sizeof(void*)); - } -#endif // FEATURE_COMINTEROP - - // Unrecognized frame vtbl - else - { - _ASSERTE(!"Unrecognized vtble passed to EmitComMethodStubProlog with profiling turned on."); - } + // Push arguments and notify profiler + X86EmitPushImm32(COR_PRF_TRANSITION_CALL); // Reason + X86EmitPushReg(kECX); // MethodDesc* + X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerUnmanagedToManagedTransitionMD), 2*sizeof(void*)); } @@ -2492,50 +2468,21 @@ VOID StubLinkerCPU::EmitProfilerComCallEpilog(TADDR pFrameVptr, X86Reg regFrame) CONTRACTL { STANDARD_VM_CHECK; -#ifdef FEATURE_COMINTEROP - PRECONDITION(pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr() || pFrameVptr == ComMethodFrame::GetMethodFrameVPtr()); -#else - PRECONDITION(pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr()); -#endif // FEATURE_COMINTEROP + PRECONDITION(pFrameVptr == ComMethodFrame::GetMethodFrameVPtr()); } CONTRACTL_END; - if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr()) - { - // Load the methoddesc into ECX (UMThkCallFrame->m_pvDatum->m_pMD) - X86EmitIndexRegLoad(kECX, regFrame, UMThkCallFrame::GetOffsetOfDatum()); - X86EmitIndexRegLoad(kECX, kECX, UMEntryThunk::GetOffsetOfMethodDesc()); - - // Push arguments and notify profiler - X86EmitPushImm32(COR_PRF_TRANSITION_RETURN); // Reason - X86EmitPushReg(kECX); // MethodDesc* - X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerManagedToUnmanagedTransitionMD), 2*sizeof(void*)); - } - -#ifdef FEATURE_COMINTEROP - else if (pFrameVptr == ComMethodFrame::GetMethodFrameVPtr()) - { - // Load the methoddesc into ECX (Frame->m_pvDatum->m_pMD) - X86EmitIndexRegLoad(kECX, regFrame, ComMethodFrame::GetOffsetOfDatum()); - X86EmitIndexRegLoad(kECX, kECX, ComCallMethodDesc::GetOffsetOfMethodDesc()); - - // Push arguments and notify profiler - X86EmitPushImm32(COR_PRF_TRANSITION_RETURN); // Reason - X86EmitPushReg(kECX); // MethodDesc* - X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerManagedToUnmanagedTransitionMD), 2*sizeof(void*)); - } -#endif // FEATURE_COMINTEROP + // Load the methoddesc into ECX (Frame->m_pvDatum->m_pMD) + X86EmitIndexRegLoad(kECX, regFrame, ComMethodFrame::GetOffsetOfDatum()); + X86EmitIndexRegLoad(kECX, kECX, ComCallMethodDesc::GetOffsetOfMethodDesc()); - // Unrecognized frame vtbl - else - { - _ASSERTE(!"Unrecognized vtble passed to EmitComMethodStubEpilog with profiling turned on."); - } + // Push arguments and notify profiler + X86EmitPushImm32(COR_PRF_TRANSITION_RETURN); // Reason + X86EmitPushReg(kECX); // MethodDesc* + X86EmitCall(NewExternalCodeLabel((LPVOID) ProfilerManagedToUnmanagedTransitionMD), 2*sizeof(void*)); } -#endif // PROFILING_SUPPORTED && !FEATURE_STUBS_AS_IL - +#endif // PROFILING_SUPPORTED -#ifndef FEATURE_STUBS_AS_IL //======================================================================== // Prolog for entering managed code from COM // pushes the appropriate frame ptr @@ -2585,13 +2532,6 @@ void StubLinkerCPU::EmitComMethodStubProlog(TADDR pFrameVptr, // lea esi, [esp+4] ;; set ESI -> new frame X86EmitEspOffset(0x8d, kESI, 4); // lea ESI, [ESP+4] - if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr()) - { - // Preserve argument registers for thiscall/fastcall - X86EmitPushReg(kECX); - X86EmitPushReg(kEDX); - } - // Emit Setup thread EmitSetup(rgRareLabels[0]); // rareLabel for rare setup EmitLabel(rgRejoinLabels[0]); // rejoin label for rare setup @@ -2640,23 +2580,6 @@ void StubLinkerCPU::EmitComMethodStubProlog(TADDR pFrameVptr, // mov [ebx + Thread.GetFrame()], esi X86EmitIndexRegStore(kEBX, Thread::GetOffsetOfCurrentFrame(), kESI); - if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr()) - { - // push UnmanagedToManagedExceptHandler - X86EmitPushImmPtr((LPVOID)UMThunkPrestubHandler); - - // mov eax, fs:[0] - static const BYTE codeSEH1[] = { 0x64, 0xA1, 0x0, 0x0, 0x0, 0x0}; - EmitBytes(codeSEH1, sizeof(codeSEH1)); - - // push eax - X86EmitPushReg(kEAX); - - // mov dword ptr fs:[0], esp - static const BYTE codeSEH2[] = { 0x64, 0x89, 0x25, 0x0, 0x0, 0x0, 0x0}; - EmitBytes(codeSEH2, sizeof(codeSEH2)); - } - #if _DEBUG if (Frame::ShouldLogTransitions()) { @@ -2693,19 +2616,6 @@ void StubLinkerCPU::EmitComMethodStubEpilog(TADDR pFrameVptr, EmitCheckGSCookie(kESI, UnmanagedToManagedFrame::GetOffsetOfGSCookie()); - if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr()) - { - // if we are using exceptions, unlink the SEH - // mov ecx,[esp] ;;pointer to the next exception record - X86EmitEspOffset(0x8b, kECX, 0); - - // mov dword ptr fs:[0], ecx - static const BYTE codeSEH[] = { 0x64, 0x89, 0x0D, 0x0, 0x0, 0x0, 0x0 }; - EmitBytes(codeSEH, sizeof(codeSEH)); - - X86EmitAddEsp(sizeof(EXCEPTION_REGISTRATION_RECORD)); - } - // mov [ebx + Thread.GetFrame()], edi ;; restore previous frame X86EmitIndexRegStore(kEBX, Thread::GetOffsetOfCurrentFrame(), kEDI); @@ -2715,13 +2625,6 @@ void StubLinkerCPU::EmitComMethodStubEpilog(TADDR pFrameVptr, EmitEnable(rgRareLabels[2]); // rare gc EmitLabel(rgRejoinLabels[2]); // rejoin for rare gc - if (pFrameVptr == UMThkCallFrame::GetMethodFrameVPtr()) - { - // Restore argument registers for thiscall/fastcall - X86EmitPopReg(kEDX); - X86EmitPopReg(kECX); - } - // add esp, popstack X86EmitAddEsp(sizeof(GSCookie) + UnmanagedToManagedFrame::GetOffsetOfCalleeSavedRegisters()); @@ -2762,7 +2665,6 @@ void StubLinkerCPU::EmitComMethodStubEpilog(TADDR pFrameVptr, EmitLabel(rgRareLabels[0]); // label for rare setup thread EmitRareSetup(rgRejoinLabels[0], /*fThrow*/ TRUE); // emit rare setup thread } -#endif // !FEATURE_STUBS_AS_IL //--------------------------------------------------------------- // Emit code to store the setup current Thread structure in eax. @@ -2793,16 +2695,12 @@ VOID StubLinkerCPU::EmitRareSetup(CodeLabel *pRejoinPoint, BOOL fThrow) { STANDARD_VM_CONTRACT; -#ifndef FEATURE_COMINTEROP - _ASSERTE(fThrow); -#else // !FEATURE_COMINTEROP if (!fThrow) { X86EmitPushReg(kESI); X86EmitCall(NewExternalCodeLabel((LPVOID) CreateThreadBlockReturnHr), sizeof(void*)); } else -#endif // !FEATURE_COMINTEROP { X86EmitCall(NewExternalCodeLabel((LPVOID) CreateThreadBlockThrow), 0); } @@ -2812,10 +2710,6 @@ VOID StubLinkerCPU::EmitRareSetup(CodeLabel *pRejoinPoint, BOOL fThrow) X86EmitNearJump(pRejoinPoint); } -//======================================================================== -#endif // TARGET_X86 -//======================================================================== -#if defined(FEATURE_COMINTEROP) && defined(TARGET_X86) //======================================================================== // Epilog for stubs that enter managed code from COM // @@ -2921,9 +2815,9 @@ void StubLinkerCPU::EmitSharedComMethodStubEpilog(TADDR pFrameVptr, EmitRareSetup(rgRejoinLabels[0],/*fThrow*/ FALSE); // emit rare setup thread } -//======================================================================== #endif // defined(FEATURE_COMINTEROP) && defined(TARGET_X86) + #if !defined(FEATURE_STUBS_AS_IL) && defined(TARGET_X86) /*============================================================================== Pushes a TransitionFrame on the stack @@ -3438,7 +3332,7 @@ VOID StubLinkerCPU::EmitUnwindInfoCheckSubfunction() #endif // defined(_DEBUG) && defined(STUBLINKER_GENERATES_UNWIND_INFO) -#ifdef TARGET_X86 +#if defined(FEATURE_COMINTEROP) && defined(TARGET_X86) //----------------------------------------------------------------------- // Generates the inline portion of the code to enable preemptive GC. Hopefully, @@ -3547,49 +3441,6 @@ VOID StubLinkerCPU::EmitDisable(CodeLabel *pForwardRef, BOOL fCallIn, X86Reg Thr // jnz RarePath X86EmitCondJump(pForwardRef, X86CondCode::kJNZ); -#if defined(FEATURE_COMINTEROP) && !defined(FEATURE_CORESYSTEM) - // If we are checking whether the current thread holds the loader lock, vector - // such cases to the rare disable pathway, where we can check again. - if (fCallIn && ShouldCheckLoaderLock()) - { - X86EmitPushReg(kEAX); - X86EmitPushReg(kEDX); - - if (ThreadReg == kECX) - X86EmitPushReg(kECX); - - // BOOL AuxUlibIsDLLSynchronizationHeld(BOOL *IsHeld) - // - // So we need to be sure that both the return value and the passed BOOL are both TRUE. - // If either is FALSE, then the call failed or the lock is not held. Either way, the - // probe should not fire. - - X86EmitPushReg(kEDX); // BOOL temp - Emit8(0x54); // push ESP because arg is &temp - X86EmitCall(NewExternalCodeLabel((LPVOID) AuxUlibIsDLLSynchronizationHeld), 0); - - // callee has popped. - X86EmitPopReg(kEDX); // recover temp - - CodeLabel *pPopLabel = NewCodeLabel(); - - Emit16(0xc085); // test eax, eax - X86EmitCondJump(pPopLabel, X86CondCode::kJZ); - - Emit16(0xd285); // test edx, edx - - EmitLabel(pPopLabel); // retain the conditional flags across the pops - - if (ThreadReg == kECX) - X86EmitPopReg(kECX); - - X86EmitPopReg(kEDX); - X86EmitPopReg(kEAX); - - X86EmitCondJump(pForwardRef, X86CondCode::kJNZ); - } -#endif - #ifdef _DEBUG if (ThreadReg != kECX) X86EmitDebugTrashReg(kECX); @@ -3623,7 +3474,6 @@ VOID StubLinkerCPU::EmitRareDisable(CodeLabel *pRejoinPoint) X86EmitNearJump(pRejoinPoint); } -#ifdef FEATURE_COMINTEROP //----------------------------------------------------------------------- // Generates the out-of-line portion of the code to disable preemptive GC. // After the work is done, the code normally jumps back to the "pRejoinPoint" @@ -3655,10 +3505,8 @@ VOID StubLinkerCPU::EmitRareDisableHRESULT(CodeLabel *pRejoinPoint, CodeLabel *p X86EmitNearJump(pExitPoint); } -#endif // FEATURE_COMINTEROP - -#endif // TARGET_X86 +#endif // defined(FEATURE_COMINTEROP) && defined(TARGET_X86) VOID StubLinkerCPU::EmitShuffleThunk(ShuffleEntry *pShuffleEntryArray) diff --git a/src/coreclr/vm/i386/stublinkerx86.h b/src/coreclr/vm/i386/stublinkerx86.h index 02ab6e9d253ea..c719057e97ea3 100644 --- a/src/coreclr/vm/i386/stublinkerx86.h +++ b/src/coreclr/vm/i386/stublinkerx86.h @@ -250,17 +250,6 @@ class StubLinkerCPU : public StubLinker ); VOID X86EmitPushEBPframe(); -#if defined(TARGET_X86) -#if defined(PROFILING_SUPPORTED) && !defined(FEATURE_STUBS_AS_IL) - // These are used to emit calls to notify the profiler of transitions in and out of - // managed code through COM->COM+ interop or N/Direct - VOID EmitProfilerComCallProlog(TADDR pFrameVptr, X86Reg regFrame); - VOID EmitProfilerComCallEpilog(TADDR pFrameVptr, X86Reg regFrame); -#endif // PROFILING_SUPPORTED && !FEATURE_STUBS_AS_IL -#endif // TARGET_X86 - - - // Emits the most efficient form of the operation: // // opcode altreg, [basereg + scaledreg*scale + ofs] @@ -340,6 +329,7 @@ class StubLinkerCPU : public StubLinker #endif } +#if defined(FEATURE_COMINTEROP) && defined(TARGET_X86) VOID EmitEnable(CodeLabel *pForwardRef); VOID EmitRareEnable(CodeLabel *pRejoinPoint); @@ -349,20 +339,13 @@ class StubLinkerCPU : public StubLinker VOID EmitSetup(CodeLabel *pForwardRef); VOID EmitRareSetup(CodeLabel* pRejoinPoint, BOOL fThrow); +#endif // FEATURE_COMINTEROP && TARGET_X86 #ifndef FEATURE_STUBS_AS_IL VOID EmitMethodStubProlog(TADDR pFrameVptr, int transitionBlockOffset); VOID EmitMethodStubEpilog(WORD numArgBytes, int transitionBlockOffset); VOID EmitCheckGSCookie(X86Reg frameReg, int gsCookieOffset); - -#ifdef TARGET_X86 - void EmitComMethodStubProlog(TADDR pFrameVptr, CodeLabel** rgRareLabels, - CodeLabel** rgRejoinLabels, BOOL bShouldProfile); - - void EmitComMethodStubEpilog(TADDR pFrameVptr, CodeLabel** rgRareLabels, - CodeLabel** rgRejoinLabels, BOOL bShouldProfile); -#endif // TARGET_X86 #endif // !FEATURE_STUBS_AS_IL #ifdef TARGET_X86 @@ -379,6 +362,20 @@ class StubLinkerCPU : public StubLinker VOID EmitComputedInstantiatingMethodStub(MethodDesc* pSharedMD, struct ShuffleEntry *pShuffleEntryArray, void* extraArg); #if defined(FEATURE_COMINTEROP) && defined(TARGET_X86) + +#if defined(PROFILING_SUPPORTED) + // These are used to emit calls to notify the profiler of transitions in and out of + // managed code through COM->COM+ interop or N/Direct + VOID EmitProfilerComCallProlog(TADDR pFrameVptr, X86Reg regFrame); + VOID EmitProfilerComCallEpilog(TADDR pFrameVptr, X86Reg regFrame); +#endif // PROFILING_SUPPORTED + + void EmitComMethodStubProlog(TADDR pFrameVptr, CodeLabel** rgRareLabels, + CodeLabel** rgRejoinLabels, BOOL bShouldProfile); + + void EmitComMethodStubEpilog(TADDR pFrameVptr, CodeLabel** rgRareLabels, + CodeLabel** rgRejoinLabels, BOOL bShouldProfile); + //======================================================================== // shared Epilog for stubs that enter managed code from COM // uses a return thunk within the method desc diff --git a/src/coreclr/vm/ilmarshalers.cpp b/src/coreclr/vm/ilmarshalers.cpp index 4782df6281b12..b6cb70ccf56c7 100644 --- a/src/coreclr/vm/ilmarshalers.cpp +++ b/src/coreclr/vm/ilmarshalers.cpp @@ -4922,8 +4922,8 @@ FCIMPL3(void, MngdSafeArrayMarshaler::ConvertSpaceToManaged, MngdSafeArrayMarsha { WCHAR strExpectedRank[64]; WCHAR strActualRank[64]; - _ltow_s(pThis->m_iRank, strExpectedRank, COUNTOF(strExpectedRank), 10); - _ltow_s(iSafeArrayRank, strActualRank, COUNTOF(strActualRank), 10); + _ltow_s(pThis->m_iRank, strExpectedRank, ARRAY_SIZE(strExpectedRank), 10); + _ltow_s(iSafeArrayRank, strActualRank, ARRAY_SIZE(strActualRank), 10); COMPlusThrow(kSafeArrayRankMismatchException, IDS_EE_SAFEARRAYRANKMISMATCH, strActualRank, strExpectedRank); } } diff --git a/src/coreclr/vm/interoputil.cpp b/src/coreclr/vm/interoputil.cpp index 959bf51c859cb..3bf1abcfcfbee 100644 --- a/src/coreclr/vm/interoputil.cpp +++ b/src/coreclr/vm/interoputil.cpp @@ -43,7 +43,6 @@ #include "commtmemberinfomap.h" #include "olevariant.h" #include "stdinterfaces.h" -#include "notifyexternals.h" #include "typeparse.h" #include "interoputil.inl" #include "typestring.h" @@ -3316,7 +3315,7 @@ void IUInvokeDispMethod( vDispIDElement.pMT = pInvokedMT; vDispIDElement.strNameLength = strNameLength; vDispIDElement.lcid = lcid; - wcscpy_s(vDispIDElement.strName, COUNTOF(vDispIDElement.strName), aNamesToConvert[0]); + wcscpy_s(vDispIDElement.strName, ARRAY_SIZE(vDispIDElement.strName), aNamesToConvert[0]); // Only look up if the cache has already been created. DispIDCache* pDispIDCache = GetAppDomain()->GetRefDispIDCache(); diff --git a/src/coreclr/vm/interpreter.h b/src/coreclr/vm/interpreter.h index a6346cebc4ccf..041484855c4dc 100644 --- a/src/coreclr/vm/interpreter.h +++ b/src/coreclr/vm/interpreter.h @@ -722,7 +722,7 @@ class InterpreterCEEInfo: public CEEInfo { CEEJitInfo m_jitInfo; public: - InterpreterCEEInfo(CORINFO_METHOD_HANDLE meth): CEEInfo((MethodDesc*)meth), m_jitInfo((MethodDesc*)meth, NULL, NULL, CORJIT_FLAGS::CORJIT_FLAG_SPEED_OPT) { m_pOverride = this; } + InterpreterCEEInfo(CORINFO_METHOD_HANDLE meth): CEEInfo((MethodDesc*)meth), m_jitInfo((MethodDesc*)meth, NULL, NULL, CORJIT_FLAGS::CORJIT_FLAG_SPEED_OPT) { } // Certain methods are unimplemented by CEEInfo (they hit an assert). They are implemented by CEEJitInfo, yet // don't seem to require any of the CEEJitInfo state we can't provide. For those case, delegate to the "partial" diff --git a/src/coreclr/vm/jithelpers.cpp b/src/coreclr/vm/jithelpers.cpp index 3e92144dca122..109f98ceecfe1 100644 --- a/src/coreclr/vm/jithelpers.cpp +++ b/src/coreclr/vm/jithelpers.cpp @@ -5950,7 +5950,7 @@ void InitJitHelperLogging() else { _ASSERTE(((size_t)hlpFunc->pfnHelper - 1) >= 0 && - ((size_t)hlpFunc->pfnHelper - 1) < COUNTOF(hlpDynamicFuncTable)); + ((size_t)hlpFunc->pfnHelper - 1) < ARRAY_SIZE(hlpDynamicFuncTable)); VMHELPDEF* dynamicHlpFunc = &hlpDynamicFuncTable[((size_t)hlpFunc->pfnHelper - 1)]; // While we're here initialize the table of VMHELPCOUNTDEF diff --git a/src/coreclr/vm/jitinterface.cpp b/src/coreclr/vm/jitinterface.cpp index a8ba429349760..e28434acabe56 100644 --- a/src/coreclr/vm/jitinterface.cpp +++ b/src/coreclr/vm/jitinterface.cpp @@ -190,16 +190,6 @@ BOOL ModifyCheckForDynamicMethod(DynamicResolver *pResolver, /*****************************************************************************/ -void CEEInfo::setOverride(ICorDynamicInfo *pOverride, CORINFO_METHOD_HANDLE currentMethod) -{ - LIMITED_METHOD_CONTRACT; - m_pOverride = pOverride; - m_pMethodBeingCompiled = (MethodDesc *)currentMethod; // method being compiled - - m_hMethodForSecurity_Key = NULL; - m_pMethodForSecurity_Value = NULL; -} - // Initialize from data we passed across to the JIT void CEEInfo::GetTypeContext(const CORINFO_SIG_INST *info, SigTypeContext *pTypeContext) { @@ -1470,8 +1460,7 @@ void CEEInfo::getFieldInfo (CORINFO_RESOLVED_TOKEN * pResolvedToken, fieldAccessor = intrinsicAccessor; } else - if (IsCompilingForNGen() || - // Static fields are not pinned in collectible types. We will always access + if (// Static fields are not pinned in collectible types. We will always access // them using a helper since the address cannot be embeded into the code. pFieldMT->Collectible() || // We always treat accessing thread statics as if we are in domain neutral code. @@ -1633,13 +1622,6 @@ void CEEInfo::getFieldInfo (CORINFO_RESOLVED_TOKEN * pResolvedToken, pResult->accessCalloutHelper.args[0].Set(CORINFO_METHOD_HANDLE(pCallerForSecurity)); pResult->accessCalloutHelper.args[1].Set(CORINFO_FIELD_HANDLE(pField)); - - if (IsCompilingForNGen()) - { - //see code:CEEInfo::getCallInfo for more information. - if (pCallerForSecurity->ContainsGenericVariables()) - COMPlusThrowNonLocalized(kNotSupportedException, W("Cannot embed generic MethodDesc")); - } } } } @@ -2603,7 +2585,7 @@ void CEEInfo::ScanForModuleDependencies(Module* pModule, SigPointer psig) if (!pTypeDefModule->IsSystem() && (pModule != pTypeDefModule)) { - m_pOverride->addActiveDependency((CORINFO_MODULE_HANDLE)pModule, (CORINFO_MODULE_HANDLE)pTypeDefModule); + addActiveDependency((CORINFO_MODULE_HANDLE)pModule, (CORINFO_MODULE_HANDLE)pTypeDefModule); } } break; @@ -2683,7 +2665,7 @@ void CEEInfo::ScanInstantiation(Module * pModule, Instantiation inst) if (!pDefModule->IsSystem() && (pModule != pDefModule)) { - m_pOverride->addActiveDependency((CORINFO_MODULE_HANDLE)pModule, (CORINFO_MODULE_HANDLE)pDefModule); + addActiveDependency((CORINFO_MODULE_HANDLE)pModule, (CORINFO_MODULE_HANDLE)pDefModule); } if (pMT->HasInstantiation()) @@ -2765,7 +2747,7 @@ void CEEInfo::ScanToken(Module * pModule, CORINFO_RESOLVED_TOKEN * pResolvedToke if (pModule != pDefModule) { - m_pOverride->addActiveDependency((CORINFO_MODULE_HANDLE)pModule, (CORINFO_MODULE_HANDLE)pDefModule); + addActiveDependency((CORINFO_MODULE_HANDLE)pModule, (CORINFO_MODULE_HANDLE)pDefModule); } MethodTable * pParentMT = pMT->GetParentMethodTable(); @@ -3725,27 +3707,13 @@ CorInfoInitClassResult CEEInfo::initClass( MethodDesc *methodBeingCompiled = m_pMethodBeingCompiled; - BOOL fMethodZappedOrNGen = IsCompilingForNGen(); - MethodTable *pTypeToInitMT = typeToInitTH.AsMethodTable(); - // This should be the most common early-out case. - if (fMethodZappedOrNGen) - { - if (pTypeToInitMT->IsClassPreInited()) - { - result = CORINFO_INITCLASS_NOT_REQUIRED; - goto exit; - } - } - else + if (pTypeToInitMT->IsClassInited()) { - if (pTypeToInitMT->IsClassInited()) - { - // If the type is initialized there really is nothing to do. - result = CORINFO_INITCLASS_INITIALIZED; - goto exit; - } + // If the type is initialized there really is nothing to do. + result = CORINFO_INITCLASS_INITIALIZED; + goto exit; } if (pTypeToInitMT->IsGlobalClass()) @@ -3848,14 +3816,6 @@ CorInfoInitClassResult CEEInfo::initClass( } } - if (fMethodZappedOrNGen) - { - // Well, because of code sharing we can't do anything at coge generation time. - // We have to do it at runtime. - result = CORINFO_INITCLASS_USE_HELPER; - goto exit; - } - // // Optimizations for domain specific code // @@ -4830,13 +4790,6 @@ CorInfoIsAccessAllowedResult CEEInfo::canAccessClass( pAccessHelper->args[0].Set(CORINFO_METHOD_HANDLE(pCallerForSecurity)); pAccessHelper->args[1].Set(CORINFO_CLASS_HANDLE(pCalleeForSecurity.AsPtr())); - - if (IsCompilingForNGen()) - { - //see code:CEEInfo::getCallInfo for more information. - if (pCallerForSecurity->ContainsGenericVariables() || pCalleeForSecurity.ContainsGenericVariables()) - COMPlusThrowNonLocalized(kNotSupportedException, W("Cannot embed generic TypeHandle")); - } } EE_TO_JIT_TRANSITION(); @@ -5413,19 +5366,6 @@ void CEEInfo::getCallInfo( pResult->callsiteCalloutHelper.args[0].Set(CORINFO_METHOD_HANDLE(pCallerForSecurity)); pResult->callsiteCalloutHelper.args[1].Set(CORINFO_METHOD_HANDLE(pCalleeForSecurity)); - - //We now embed open instantiations in a few places for security callouts (since you can only - //do the security check on the open instantiation). We throw these methods out in - //TriageMethodForZap. In addition, NGen has problems referencing them properly. Just throw out the whole - //method and rejit at runtime. - if (IsCompilingForNGen()) - { - if (pCallerForSecurity->ContainsGenericVariables() - || pCalleeForSecurity->ContainsGenericVariables()) - { - COMPlusThrowNonLocalized(kNotSupportedException, W("Cannot embed generic MethodDesc")); - } - } } } } @@ -5895,8 +5835,8 @@ CorInfoHelpFunc CEEInfo::getCastingHelper(CORINFO_RESOLVED_TOKEN * pResolvedToke bool fClassMustBeRestored; result = getCastingHelperStatic(TypeHandle(pResolvedToken->hClass), fThrowing, &fClassMustBeRestored); - if (fClassMustBeRestored && m_pOverride != NULL) - m_pOverride->classMustBeLoadedBeforeCodeIsRun(pResolvedToken->hClass); + if (fClassMustBeRestored) + classMustBeLoadedBeforeCodeIsRun(pResolvedToken->hClass); EE_TO_JIT_TRANSITION(); @@ -6019,8 +5959,7 @@ CorInfoHelpFunc CEEInfo::getUnBoxHelper(CORINFO_CLASS_HANDLE clsHnd) { LIMITED_METHOD_CONTRACT; - if (m_pOverride != NULL) - m_pOverride->classMustBeLoadedBeforeCodeIsRun(clsHnd); + classMustBeLoadedBeforeCodeIsRun(clsHnd); TypeHandle VMClsHnd(clsHnd); if (Nullable::IsNullableType(VMClsHnd)) @@ -9359,7 +9298,7 @@ CorInfoTypeWithMod CEEInfo::getArgType ( TypeHandle thPtr = ptr.GetTypeHandleNT(pModule, &typeContext); if(!thPtr.IsNull()) { - m_pOverride->classMustBeLoadedBeforeCodeIsRun(CORINFO_CLASS_HANDLE(thPtr.AsPtr())); + classMustBeLoadedBeforeCodeIsRun(CORINFO_CLASS_HANDLE(thPtr.AsPtr())); } } break; @@ -10416,7 +10355,7 @@ bool CEEInfo::runWithErrorTrap(void (*function)(void*), void* param) #if !defined(TARGET_UNIX) RunWithErrorTrapFilterParam trapParam; - trapParam.m_corInfo = m_pOverride == nullptr ? this : m_pOverride; + trapParam.m_corInfo = this; trapParam.m_function = function; trapParam.m_param = param; diff --git a/src/coreclr/vm/jitinterface.h b/src/coreclr/vm/jitinterface.h index 6a3b1a1509507..1afac1ba80201 100644 --- a/src/coreclr/vm/jitinterface.h +++ b/src/coreclr/vm/jitinterface.h @@ -475,14 +475,6 @@ class CEEInfo : public ICorJitInfo CORINFO_GET_TAILCALL_HELPERS_FLAGS flags, CORINFO_TAILCALL_HELPERS* pResult); - // Returns whether we are generating code for NGen image. - bool IsCompilingForNGen() - { - LIMITED_METHOD_CONTRACT; - // NGen is the only place where we set the override - return this != m_pOverride; - } - // This normalizes EE type information into the form expected by the JIT. // // If typeHnd contains exact type information, then *clsRet will contain @@ -492,7 +484,6 @@ class CEEInfo : public ICorJitInfo CORINFO_CLASS_HANDLE *clsRet = NULL /* optional out */ ); CEEInfo(MethodDesc * fd = NULL, bool fVerifyOnly = false, bool fAllowInlining = true) : - m_pOverride(NULL), m_pMethodBeingCompiled(fd), m_fVerifyOnly(fVerifyOnly), m_pThread(GetThreadNULLOk()), @@ -569,13 +560,6 @@ class CEEInfo : public ICorJitInfo #endif protected: - // NGen provides its own modifications to EE-JIT interface. From technical reason it cannot simply inherit - // from code:CEEInfo class (because it has dependencies on VM that NGen does not want). - // Therefore the "normal" EE-JIT interface has code:m_pOverride hook that is set either to - // * 'this' (code:CEEInfo) at runtime, or to - // * code:ZapInfo - the NGen specific implementation of the interface. - ICorDynamicInfo * m_pOverride; - MethodDesc* m_pMethodBeingCompiled; // Top-level method being compiled bool m_fVerifyOnly; Thread * m_pThread; // Cached current thread for faster JIT-EE transitions @@ -847,8 +831,6 @@ class CEEJitInfo : public CEEInfo GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; - - m_pOverride = this; } ~CEEJitInfo() diff --git a/src/coreclr/vm/methodtablebuilder.cpp b/src/coreclr/vm/methodtablebuilder.cpp index 694e03cca35f2..68d11affa4351 100644 --- a/src/coreclr/vm/methodtablebuilder.cpp +++ b/src/coreclr/vm/methodtablebuilder.cpp @@ -8648,6 +8648,14 @@ MethodTableBuilder::HandleExplicitLayout( BuildMethodTableThrowException(IDS_CLASSLOAD_GENERAL); } } + + if (!numInstanceFieldBytes.IsOverflow() && numInstanceFieldBytes.Value() == 0) + { + // If we calculate a 0-byte size here, we should have also calculated a 0-byte size + // in the initial layout algorithm. + _ASSERTE(GetLayoutInfo()->IsZeroSized()); + numInstanceFieldBytes = S_UINT32(1); + } } // The GC requires that all valuetypes containing orefs be sized to a multiple of TARGET_POINTER_SIZE. diff --git a/src/coreclr/vm/mlinfo.cpp b/src/coreclr/vm/mlinfo.cpp index 1dcc726213640..c573184012284 100644 --- a/src/coreclr/vm/mlinfo.cpp +++ b/src/coreclr/vm/mlinfo.cpp @@ -1130,27 +1130,27 @@ MarshalInfo::MarshalInfo(Module* pModule, CHAR achDbgContext[DEBUG_CONTEXT_STR_LEN] = ""; if (!pDebugName) { - strncpy_s(achDbgContext, COUNTOF(achDbgContext), "", _TRUNCATE); + strncpy_s(achDbgContext, ARRAY_SIZE(achDbgContext), "", _TRUNCATE); } else { - strncat_s(achDbgContext, COUNTOF(achDbgContext), pDebugClassName, _TRUNCATE); - strncat_s(achDbgContext, COUNTOF(achDbgContext), NAMESPACE_SEPARATOR_STR, _TRUNCATE); - strncat_s(achDbgContext, COUNTOF(achDbgContext), pDebugName, _TRUNCATE); - strncat_s(achDbgContext, COUNTOF(achDbgContext), " ", _TRUNCATE); + strncat_s(achDbgContext, ARRAY_SIZE(achDbgContext), pDebugClassName, _TRUNCATE); + strncat_s(achDbgContext, ARRAY_SIZE(achDbgContext), NAMESPACE_SEPARATOR_STR, _TRUNCATE); + strncat_s(achDbgContext, ARRAY_SIZE(achDbgContext), pDebugName, _TRUNCATE); + strncat_s(achDbgContext, ARRAY_SIZE(achDbgContext), " ", _TRUNCATE); switch (argidx) { case (UINT)-1: - strncat_s(achDbgContext, COUNTOF(achDbgContext), "field", _TRUNCATE); + strncat_s(achDbgContext, ARRAY_SIZE(achDbgContext), "field", _TRUNCATE); break; case 0: - strncat_s(achDbgContext, COUNTOF(achDbgContext), "return value", _TRUNCATE); + strncat_s(achDbgContext, ARRAY_SIZE(achDbgContext), "return value", _TRUNCATE); break; default: { char buf[30]; - sprintf_s(buf, COUNTOF(buf), "param #%lu", (ULONG)argidx); - strncat_s(achDbgContext, COUNTOF(achDbgContext), buf, _TRUNCATE); + sprintf_s(buf, ARRAY_SIZE(buf), "param #%lu", (ULONG)argidx); + strncat_s(achDbgContext, ARRAY_SIZE(achDbgContext), buf, _TRUNCATE); } } } @@ -2896,7 +2896,7 @@ UINT16 MarshalInfo::GetNativeSize(MarshalType mtype) #include "mtypes.h" }; - _ASSERTE((SIZE_T)mtype < COUNTOF(nativeSizes)); + _ASSERTE((SIZE_T)mtype < ARRAY_SIZE(nativeSizes)); BYTE nativeSize = nativeSizes[mtype]; if (nativeSize == VARIABLESIZE) @@ -2959,7 +2959,7 @@ OVERRIDEPROC MarshalInfo::GetArgumentOverrideProc(MarshalType mtype) #include "mtypes.h" }; - _ASSERTE((SIZE_T)mtype < COUNTOF(ILArgumentOverrideProcs)); + _ASSERTE((SIZE_T)mtype < ARRAY_SIZE(ILArgumentOverrideProcs)); return ILArgumentOverrideProcs[mtype]; } @@ -2979,7 +2979,7 @@ RETURNOVERRIDEPROC MarshalInfo::GetReturnOverrideProc(MarshalType mtype) #include "mtypes.h" }; - _ASSERTE((SIZE_T)mtype < COUNTOF(ILReturnOverrideProcs)); + _ASSERTE((SIZE_T)mtype < ARRAY_SIZE(ILReturnOverrideProcs)); return ILReturnOverrideProcs[mtype]; } @@ -3172,7 +3172,7 @@ VOID MarshalInfo::DumpMarshalInfo(Module* pModule, SigPointer sig, const SigType while (cbNativeType--) { char num[100]; - sprintf_s(num, COUNTOF(num), "0x%lx ", (ULONG)*pvNativeType); + sprintf_s(num, ARRAY_SIZE(num), "0x%lx ", (ULONG)*pvNativeType); logbuf.AppendASCII(num); switch (*(pvNativeType++)) { @@ -3314,7 +3314,7 @@ VOID MarshalInfo::DumpMarshalInfo(Module* pModule, SigPointer sig, const SigType logbuf.AppendASCII("MarshalType : "); { char num[100]; - sprintf_s(num, COUNTOF(num), "0x%lx ", (ULONG)m_type); + sprintf_s(num, ARRAY_SIZE(num), "0x%lx ", (ULONG)m_type); logbuf.AppendASCII(num); } switch (m_type) diff --git a/src/coreclr/vm/nativelibrary.cpp b/src/coreclr/vm/nativelibrary.cpp index 9ec47c423311f..d5a91b4863c2f 100644 --- a/src/coreclr/vm/nativelibrary.cpp +++ b/src/coreclr/vm/nativelibrary.cpp @@ -526,7 +526,7 @@ namespace SString::CIterator it = libName.Begin(); if (libName.Find(it, PLATFORM_SHARED_LIB_SUFFIX_W)) { - it += COUNTOF(PLATFORM_SHARED_LIB_SUFFIX_W); + it += ARRAY_SIZE(PLATFORM_SHARED_LIB_SUFFIX_W); containsSuffix = it == libName.End() || *it == (WCHAR)'.'; } @@ -648,7 +648,7 @@ namespace // (both of these are typically done to smooth over cross-platform differences). // We try to dlopen with such variations on the original. const WCHAR* prefixSuffixCombinations[MaxVariationCount] = {}; - int numberOfVariations = COUNTOF(prefixSuffixCombinations); + int numberOfVariations = ARRAY_SIZE(prefixSuffixCombinations); DetermineLibNameVariations(prefixSuffixCombinations, &numberOfVariations, wszLibName, libNameIsRelativePath); for (int i = 0; i < numberOfVariations; i++) { diff --git a/src/coreclr/vm/notifyexternals.cpp b/src/coreclr/vm/notifyexternals.cpp deleted file mode 100644 index 49c2443da3bcb..0000000000000 --- a/src/coreclr/vm/notifyexternals.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// =========================================================================== -// File: notifyexternals.cpp -// - -// =========================================================================== - - -#include "common.h" - -#include "excep.h" -#include "interoputil.h" -#include "comcache.h" - -#include "notifyexternals.h" - -// On some platforms, we can detect whether the current thread holds the loader -// lock. It is unsafe to execute managed code when this is the case -BOOL ShouldCheckLoaderLock() -{ - CONTRACTL - { - NOTHROW; - GC_NOTRIGGER; - MODE_ANY; - } - CONTRACTL_END; - -#ifdef FEATURE_CORESYSTEM - // CoreSystem does not support this. - return FALSE; -#else - // Because of how C++ generates code, we must use default initialization to - // 0 here. Any explicit initialization will result in thread-safety problems. - static BOOL fInited; - static BOOL fShouldCheck; - - if (VolatileLoad(&fInited) == FALSE) - { - fShouldCheck = AuxUlibInitialize(); // may fail - - VolatileStore(&fInited, TRUE); - } - return (fShouldCheck); -#endif // FEATURE_CORESYSTEM -} diff --git a/src/coreclr/vm/notifyexternals.h b/src/coreclr/vm/notifyexternals.h deleted file mode 100644 index 8d204d1a7881e..0000000000000 --- a/src/coreclr/vm/notifyexternals.h +++ /dev/null @@ -1,19 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -//////////////////////////////////////////////////////////////////////////////// - - -#ifndef _NOTIFY_EXTERNALS_H -#define _NOTIFY_EXTERNALS_H - -#ifndef FEATURE_COMINTEROP -#error FEATURE_COMINTEROP is required for this file -#endif // FEATURE_COMINTEROP - -extern BOOL g_fComStarted; - -BOOL ShouldCheckLoaderLock(BOOL fForMDA = TRUE); - -#include "aux_ulib.h" - -#endif diff --git a/src/coreclr/vm/peimage.cpp b/src/coreclr/vm/peimage.cpp index 4c517a1bd3e5f..1b72b89106df6 100644 --- a/src/coreclr/vm/peimage.cpp +++ b/src/coreclr/vm/peimage.cpp @@ -18,7 +18,6 @@ #ifndef DACCESS_COMPILE - CrstStatic PEImage::s_hashLock; PtrHashMap *PEImage::s_Images = NULL; CrstStatic PEImage::s_ijwHashLock; @@ -95,7 +94,7 @@ PEImage::~PEImage() if(m_hFile!=INVALID_HANDLE_VALUE) CloseHandle(m_hFile); - for (unsigned int i=0;iRelease(); @@ -754,7 +753,7 @@ PEImage::PEImage(): MODE_ANY; } CONTRACTL_END; - for (DWORD i=0;iGetEntryPoint(); -#endif // TARGET_X86 && !FEATURE_STUBS_AS_IL - ThePreStubManager::Init(); } @@ -2297,11 +2289,7 @@ PCODE TheUMThunkPreStub() { LIMITED_METHOD_CONTRACT; -#if defined(TARGET_X86) && !defined(FEATURE_STUBS_AS_IL) - return g_UMThunkPreStub; -#else // TARGET_X86 && !FEATURE_STUBS_AS_IL return GetEEFuncEntryPoint(TheUMEntryPrestub); -#endif // TARGET_X86 && !FEATURE_STUBS_AS_IL } PCODE TheVarargNDirectStub(BOOL hasRetBuffArg) diff --git a/src/coreclr/vm/proftoeeinterfaceimpl.cpp b/src/coreclr/vm/proftoeeinterfaceimpl.cpp index 749fa73126b08..50e57f8144eef 100644 --- a/src/coreclr/vm/proftoeeinterfaceimpl.cpp +++ b/src/coreclr/vm/proftoeeinterfaceimpl.cpp @@ -1274,7 +1274,7 @@ bool AllocByClassHelper(Object * pBO, void * pv) _ASSERTE(pv != NULL); { - BEGIN_PROFILER_CALLBACK(CORProfilerTrackAllocations()); + BEGIN_PROFILER_CALLBACK(CORProfilerTrackGC()); // Pass along the call g_profControlBlock.AllocByClass( (ObjectID) pBO, diff --git a/src/coreclr/vm/runtimecallablewrapper.cpp b/src/coreclr/vm/runtimecallablewrapper.cpp index 9b7adbcbdc82a..fca8708ec1edc 100644 --- a/src/coreclr/vm/runtimecallablewrapper.cpp +++ b/src/coreclr/vm/runtimecallablewrapper.cpp @@ -31,7 +31,6 @@ class Object; #include "eeconfig.h" #include "comdelegate.h" #include "comcache.h" -#include "notifyexternals.h" #include "../md/compiler/custattr.h" #include "olevariant.h" #include "interopconverter.h" diff --git a/src/coreclr/vm/sigformat.cpp b/src/coreclr/vm/sigformat.cpp index f506eedf2032b..2225be54cd7bd 100644 --- a/src/coreclr/vm/sigformat.cpp +++ b/src/coreclr/vm/sigformat.cpp @@ -235,7 +235,7 @@ void SigFormat::AddTypeString(Module* pModule, SigPointer sig, const SigTypeCont else { char smallbuf[20]; - sprintf_s(smallbuf, COUNTOF(smallbuf), "!!%d", ix); + sprintf_s(smallbuf, ARRAY_SIZE(smallbuf), "!!%d", ix); AddString(smallbuf); } } @@ -253,7 +253,7 @@ void SigFormat::AddTypeString(Module* pModule, SigPointer sig, const SigTypeCont else { char smallbuf[20]; - sprintf_s(smallbuf, COUNTOF(smallbuf), "!%d", ix); + sprintf_s(smallbuf, ARRAY_SIZE(smallbuf), "!%d", ix); AddString(smallbuf); } } diff --git a/src/coreclr/vm/siginfo.cpp b/src/coreclr/vm/siginfo.cpp index f10acff25522e..a197fbc87cabd 100644 --- a/src/coreclr/vm/siginfo.cpp +++ b/src/coreclr/vm/siginfo.cpp @@ -2553,7 +2553,7 @@ UINT MetaSig::GetElemSize(CorElementType etype, TypeHandle thValueType) } CONTRACTL_END - if ((UINT)etype >= COUNTOF(gElementTypeInfo)) + if ((UINT)etype >= ARRAY_SIZE(gElementTypeInfo)) ThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_COMPLUS_SIG); int cbsize = gElementTypeInfo[(UINT)etype].m_cbSize; diff --git a/src/coreclr/vm/syncblk.cpp b/src/coreclr/vm/syncblk.cpp index 96aa9c701b916..9dfdfafc050f5 100644 --- a/src/coreclr/vm/syncblk.cpp +++ b/src/coreclr/vm/syncblk.cpp @@ -1491,7 +1491,7 @@ void DumpSyncBlockCache() param.descrip = descrip; param.oref = oref; param.buffer2 = buffer2; - param.cch2 = COUNTOF(buffer2); + param.cch2 = ARRAY_SIZE(buffer2); param.isString = isString; PAL_TRY(Param *, pParam, ¶m) @@ -1514,7 +1514,7 @@ void DumpSyncBlockCache() descrip = param.descrip; isString = param.isString; } - sprintf_s(buffer, COUNTOF(buffer), "%s", descrip); + sprintf_s(buffer, ARRAY_SIZE(buffer), "%s", descrip); descrip = buffer; } if (dumpSBStyle < 2) diff --git a/src/coreclr/vm/threadsuspend.cpp b/src/coreclr/vm/threadsuspend.cpp index 2007fec4e3ea4..b65cd74270b23 100644 --- a/src/coreclr/vm/threadsuspend.cpp +++ b/src/coreclr/vm/threadsuspend.cpp @@ -3591,12 +3591,12 @@ void ThreadSuspend::SuspendRuntime(ThreadSuspend::SUSPEND_REASON reason) DWORD id = (DWORD) thread->m_OSThreadId; if (id == 0xbaadf00d) { - sprintf_s (message, COUNTOF(message), "Thread CLR ID=%x cannot be suspended", + sprintf_s (message, ARRAY_SIZE(message), "Thread CLR ID=%x cannot be suspended", thread->GetThreadId()); } else { - sprintf_s (message, COUNTOF(message), "Thread OS ID=%x cannot be suspended", + sprintf_s (message, ARRAY_SIZE(message), "Thread OS ID=%x cannot be suspended", id); } DbgAssertDialog(__FILE__, __LINE__, message); diff --git a/src/coreclr/vm/typeparse.cpp b/src/coreclr/vm/typeparse.cpp index 6abed5799f300..524a9e595bc24 100644 --- a/src/coreclr/vm/typeparse.cpp +++ b/src/coreclr/vm/typeparse.cpp @@ -981,58 +981,6 @@ TypeHandle TypeName::GetTypeUsingCASearchRules(LPCWSTR szTypeName, Assembly *pRe -//------------------------------------------------------------------------------------------- -// Retrieves a type from an assembly. It requires the caller to know which assembly -// the type is in. -//------------------------------------------------------------------------------------------- -/* public static */ TypeHandle TypeName::GetTypeFromAssembly(LPCWSTR szTypeName, Assembly *pAssembly, BOOL bThrowIfNotFound /*= TRUE*/) -{ - STATIC_CONTRACT_THROWS; - STATIC_CONTRACT_GC_TRIGGERS; - STATIC_CONTRACT_FAULT; - - _ASSERTE(szTypeName != NULL); - _ASSERTE(pAssembly != NULL); - - if (!*szTypeName) - COMPlusThrow(kArgumentException, W("Format_StringZeroLength")); - - DWORD error = (DWORD)-1; - -#ifdef __GNUC__ - // When compiling under GCC we have to use the -fstack-check option to ensure we always spot stack - // overflow. But this option is intolerant of locals growing too large, so we have to cut back a bit - // on what we can allocate inline here. Leave the Windows versions alone to retain the perf benefits - // since we don't have the same constraints. - NewHolder pTypeName = new TypeName(szTypeName, &error); -#else // __GNUC__ - TypeName typeName(szTypeName, &error); - TypeName *pTypeName = &typeName; -#endif // __GNUC__ - - if (error != (DWORD)-1) - { - StackSString buf; - StackSString msg(W("typeName@")); - COUNT_T size = buf.GetUnicodeAllocation(); - _itow_s(error,buf.OpenUnicodeBuffer(size),size,10); - buf.CloseBuffer(); - msg.Append(buf); - COMPlusThrowArgumentException(msg.GetUnicode(), NULL); - } - - // Because the typename can come from untrusted input, we will throw an exception rather than assert. - // (This also assures that the shipping build does the right thing.) - if (!(pTypeName->GetAssembly()->IsEmpty())) - { - COMPlusThrow(kArgumentException, IDS_EE_CANNOT_HAVE_ASSEMBLY_SPEC); - } - - return pTypeName->GetTypeWorker(bThrowIfNotFound, /*bIgnoreCase = */FALSE, pAssembly, /*fEnableCASearchRules = */FALSE, FALSE, NULL, - nullptr, // pPrivHostBinder - NULL /* cannot find a collectible type unless it is in assembly */); -} - //------------------------------------------------------------------------------------------- // Retrieves a type. Will assert if the name is not fully qualified. //------------------------------------------------------------------------------------------- diff --git a/src/coreclr/vm/typeparse.h b/src/coreclr/vm/typeparse.h index 5a19c980ad5e1..2f1854da236dc 100644 --- a/src/coreclr/vm/typeparse.h +++ b/src/coreclr/vm/typeparse.h @@ -269,12 +269,6 @@ class TypeName virtual ~TypeName(); public: - //------------------------------------------------------------------------------------------- - // Retrieves a type from an assembly. It requires the caller to know which assembly - // the type is in. - //------------------------------------------------------------------------------------------- - static TypeHandle GetTypeFromAssembly(LPCWSTR szTypeName, Assembly *pAssembly, BOOL bThrowIfNotFound = TRUE); - TypeHandle GetTypeFromAsm(); //------------------------------------------------------------------------------------------- diff --git a/src/coreclr/vm/virtualcallstub.cpp b/src/coreclr/vm/virtualcallstub.cpp index 05df034829ba9..fd85071676e94 100644 --- a/src/coreclr/vm/virtualcallstub.cpp +++ b/src/coreclr/vm/virtualcallstub.cpp @@ -187,142 +187,142 @@ void VirtualCallStubManager::LoggingDump() if(g_hStubLogFile) { #ifdef STUB_LOGGING - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\nstub tuning parameters\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\nstub tuning parameters\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\t%-30s %3d (0x%02x)\r\n", "STUB_MISS_COUNT_VALUE", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\t%-30s %3d (0x%02x)\r\n", "STUB_MISS_COUNT_VALUE", STUB_MISS_COUNT_VALUE, STUB_MISS_COUNT_VALUE); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "STUB_COLLIDE_WRITE_PCT", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "STUB_COLLIDE_WRITE_PCT", STUB_COLLIDE_WRITE_PCT, STUB_COLLIDE_WRITE_PCT); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "STUB_COLLIDE_MONO_PCT", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "STUB_COLLIDE_MONO_PCT", STUB_COLLIDE_MONO_PCT, STUB_COLLIDE_MONO_PCT); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "DumpLogCounter", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "DumpLogCounter", g_dumpLogCounter, g_dumpLogCounter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "DumpLogIncr", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "DumpLogIncr", g_dumpLogCounter, g_dumpLogIncr); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "ResetCacheCounter", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "ResetCacheCounter", g_resetCacheCounter, g_resetCacheCounter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "ResetCacheIncr", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\t%-30s %3d%% (0x%02x)\r\n", "ResetCacheIncr", g_resetCacheCounter, g_resetCacheIncr); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #endif // STUB_LOGGING - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\nsite data\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\nsite data\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); //output counters - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "site_counter", g_site_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "site_counter", g_site_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "site_write", g_site_write); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "site_write", g_site_write); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "site_write_mono", g_site_write_mono); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "site_write_mono", g_site_write_mono); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "site_write_poly", g_site_write_poly); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "site_write_poly", g_site_write_poly); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\n%-30s %d\r\n", "reclaim_counter", g_reclaim_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\n%-30s %d\r\n", "reclaim_counter", g_reclaim_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\nstub data\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\nstub data\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_lookup_counter", g_stub_lookup_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_lookup_counter", g_stub_lookup_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_mono_counter", g_stub_mono_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_mono_counter", g_stub_mono_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_poly_counter", g_stub_poly_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_poly_counter", g_stub_poly_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_vtable_counter", g_stub_vtable_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_vtable_counter", g_stub_vtable_counter); WriteFile(g_hStubLogFile, szPrintStr, (DWORD)strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_space", g_stub_space); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_space", g_stub_space); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #ifdef STUB_LOGGING - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\nlookup stub data\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\nlookup stub data\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); UINT32 total_calls = g_mono_call_counter + g_poly_call_counter; - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "lookup_call_counter", g_call_lookup_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "lookup_call_counter", g_call_lookup_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\n%-30s %d\r\n", "total stub dispatch calls", total_calls); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\n%-30s %d\r\n", "total stub dispatch calls", total_calls); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\n%-30s %#5.2f%%\r\n", "mono stub data", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\n%-30s %#5.2f%%\r\n", "mono stub data", 100.0 * double(g_mono_call_counter)/double(total_calls)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "mono_call_counter", g_mono_call_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "mono_call_counter", g_mono_call_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "mono_miss_counter", g_mono_miss_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "mono_miss_counter", g_mono_miss_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_PCT, "miss percent", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_PCT, "miss percent", 100.0 * double(g_mono_miss_counter)/double(g_mono_call_counter)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\n%-30s %#5.2f%%\r\n", "poly stub data", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\n%-30s %#5.2f%%\r\n", "poly stub data", 100.0 * double(g_poly_call_counter)/double(total_calls)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "poly_call_counter", g_poly_call_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "poly_call_counter", g_poly_call_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "poly_miss_counter", g_poly_miss_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "poly_miss_counter", g_poly_miss_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_PCT, "miss percent", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_PCT, "miss percent", 100.0 * double(g_poly_miss_counter)/double(g_poly_call_counter)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #endif // STUB_LOGGING #ifdef CHAIN_LOOKUP - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\nchain lookup data\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\nchain lookup data\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #ifdef STUB_LOGGING - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "chained_lookup_call_counter", g_chained_lookup_call_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "chained_lookup_call_counter", g_chained_lookup_call_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "chained_lookup_miss_counter", g_chained_lookup_miss_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "chained_lookup_miss_counter", g_chained_lookup_miss_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_PCT, "miss percent", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_PCT, "miss percent", 100.0 * double(g_chained_lookup_miss_counter)/double(g_chained_lookup_call_counter)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "chained_lookup_external_call_counter", g_chained_lookup_external_call_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "chained_lookup_external_call_counter", g_chained_lookup_external_call_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "chained_lookup_external_miss_counter", g_chained_lookup_external_miss_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "chained_lookup_external_miss_counter", g_chained_lookup_external_miss_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_PCT, "miss percent", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_PCT, "miss percent", 100.0 * double(g_chained_lookup_external_miss_counter)/double(g_chained_lookup_external_call_counter)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #endif // STUB_LOGGING - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "chained_entry_promoted", g_chained_entry_promoted); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "chained_entry_promoted", g_chained_entry_promoted); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #endif // CHAIN_LOOKUP #ifdef STUB_LOGGING - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\n%-30s %#5.2f%%\r\n", "worker (slow resolver) data", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\n%-30s %#5.2f%%\r\n", "worker (slow resolver) data", 100.0 * double(g_worker_call)/double(total_calls)); #else // !STUB_LOGGING - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\nworker (slow resolver) data\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\nworker (slow resolver) data\r\n"); #endif // !STUB_LOGGING WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "worker_call", g_worker_call); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "worker_call", g_worker_call); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "worker_call_no_patch", g_worker_call_no_patch); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "worker_call_no_patch", g_worker_call_no_patch); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "external_call", g_external_call); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "external_call", g_external_call); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "external_call_no_patch", g_external_call_no_patch); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "external_call_no_patch", g_external_call_no_patch); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "worker_collide_to_mono", g_worker_collide_to_mono); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "worker_collide_to_mono", g_worker_collide_to_mono); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); UINT32 total_inserts = g_insert_cache_external @@ -330,74 +330,74 @@ void VirtualCallStubManager::LoggingDump() + g_insert_cache_dispatch + g_insert_cache_resolve; - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\n%-30s %d\r\n", "insert cache data", total_inserts); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\n%-30s %d\r\n", "insert cache data", total_inserts); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_external", g_insert_cache_external, + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_external", g_insert_cache_external, 100.0 * double(g_insert_cache_external)/double(total_inserts)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_shared", g_insert_cache_shared, + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_shared", g_insert_cache_shared, 100.0 * double(g_insert_cache_shared)/double(total_inserts)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_dispatch", g_insert_cache_dispatch, + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_dispatch", g_insert_cache_dispatch, 100.0 * double(g_insert_cache_dispatch)/double(total_inserts)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_resolve", g_insert_cache_resolve, + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_resolve", g_insert_cache_resolve, 100.0 * double(g_insert_cache_resolve)/double(total_inserts)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_hit", g_insert_cache_hit, + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_hit", g_insert_cache_hit, 100.0 * double(g_insert_cache_hit)/double(total_inserts)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_miss", g_insert_cache_miss, + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_miss", g_insert_cache_miss, 100.0 * double(g_insert_cache_miss)/double(total_inserts)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_collide", g_insert_cache_collide, + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_collide", g_insert_cache_collide, 100.0 * double(g_insert_cache_collide)/double(total_inserts)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_write", g_insert_cache_write, + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT_PCT, "insert_cache_write", g_insert_cache_write, 100.0 * double(g_insert_cache_write)/double(total_inserts)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\ncache data\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\ncache data\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); size_t total, used; g_resolveCache->GetLoadFactor(&total, &used); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_SIZE, "cache_entry_used", used); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_SIZE, "cache_entry_used", used); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "cache_entry_counter", g_cache_entry_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "cache_entry_counter", g_cache_entry_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "cache_entry_space", g_cache_entry_space); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "cache_entry_space", g_cache_entry_space); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\nstub hash table data\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\nstub hash table data\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "bucket_space", g_bucket_space); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "bucket_space", g_bucket_space); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "bucket_space_dead", g_bucket_space_dead); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "bucket_space_dead", g_bucket_space_dead); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\ncache_load:\t%zu used, %zu total, utilization %#5.2f%%\r\n", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\ncache_load:\t%zu used, %zu total, utilization %#5.2f%%\r\n", used, total, 100.0 * double(used) / double(total)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #ifdef STUB_LOGGING - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\ncache entry write counts\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\ncache entry write counts\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); DispatchCache::CacheEntryData *rgCacheData = g_resolveCache->cacheData; for (UINT16 i = 0; i < CALL_STUB_CACHE_SIZE; i++) { - sprintf_s(szPrintStr, COUNTOF(szPrintStr), " %4d", rgCacheData[i]); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), " %4d", rgCacheData[i]); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); if (i % 16 == 15) { - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); } } - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #endif // STUB_LOGGING @@ -406,7 +406,7 @@ void VirtualCallStubManager::LoggingDump() { if (ContractImplMap::deltasDescs[i] != 0) { - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "deltasDescs[%d]\t%d\r\n", i, ContractImplMap::deltasDescs[i]); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "deltasDescs[%d]\t%d\r\n", i, ContractImplMap::deltasDescs[i]); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); } } @@ -414,19 +414,19 @@ void VirtualCallStubManager::LoggingDump() { if (ContractImplMap::deltasSlots[i] != 0) { - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "deltasSlots[%d]\t%d\r\n", i, ContractImplMap::deltasSlots[i]); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "deltasSlots[%d]\t%d\r\n", i, ContractImplMap::deltasSlots[i]); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); } } - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "cout of maps:\t%d\r\n", ContractImplMap::countMaps); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "cout of maps:\t%d\r\n", ContractImplMap::countMaps); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "count of interfaces:\t%d\r\n", ContractImplMap::countInterfaces); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "count of interfaces:\t%d\r\n", ContractImplMap::countInterfaces); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "count of deltas:\t%d\r\n", ContractImplMap::countDelta); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "count of deltas:\t%d\r\n", ContractImplMap::countDelta); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "total delta for descs:\t%d\r\n", ContractImplMap::totalDeltaDescs); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "total delta for descs:\t%d\r\n", ContractImplMap::totalDeltaDescs); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "total delta for slots:\t%d\r\n", ContractImplMap::totalDeltaSlots); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "total delta for slots:\t%d\r\n", ContractImplMap::totalDeltaSlots); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); #endif // 0 @@ -2972,38 +2972,38 @@ void VirtualCallStubManager::LogStats() if (g_hStubLogFile && (stats.site_write != 0)) { //output counters - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "site_counter", stats.site_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "site_counter", stats.site_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "site_write", stats.site_write); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "site_write", stats.site_write); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "site_write_mono", stats.site_write_mono); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "site_write_mono", stats.site_write_mono); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "site_write_poly", stats.site_write_poly); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "site_write_poly", stats.site_write_poly); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\nstub data\r\n"); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\nstub data\r\n"); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_lookup_counter", stats.stub_lookup_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_lookup_counter", stats.stub_lookup_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_mono_counter", stats.stub_mono_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_mono_counter", stats.stub_mono_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_poly_counter", stats.stub_poly_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_poly_counter", stats.stub_poly_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "stub_space", stats.stub_space); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "stub_space", stats.stub_space); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); size_t total, used; g_resolveCache->GetLoadFactor(&total, &used); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_SIZE, "cache_entry_used", used); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_SIZE, "cache_entry_used", used); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "cache_entry_counter", stats.cache_entry_counter); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "cache_entry_counter", stats.cache_entry_counter); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), OUTPUT_FORMAT_INT, "cache_entry_space", stats.cache_entry_space); + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), OUTPUT_FORMAT_INT, "cache_entry_space", stats.cache_entry_space); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); - sprintf_s(szPrintStr, COUNTOF(szPrintStr), "\r\ncache_load:\t%zu used, %zu total, utilization %#5.2f%%\r\n", + sprintf_s(szPrintStr, ARRAY_SIZE(szPrintStr), "\r\ncache_load:\t%zu used, %zu total, utilization %#5.2f%%\r\n", used, total, 100.0 * double(used) / double(total)); WriteFile (g_hStubLogFile, szPrintStr, (DWORD) strlen(szPrintStr), &dwWriteByte, NULL); } diff --git a/src/coreclr/vm/wks/CMakeLists.txt b/src/coreclr/vm/wks/CMakeLists.txt index cb7ba8ca2cc99..b0113575c1e05 100644 --- a/src/coreclr/vm/wks/CMakeLists.txt +++ b/src/coreclr/vm/wks/CMakeLists.txt @@ -26,7 +26,6 @@ add_dependencies(cee_wks_obj eventing_headers) add_dependencies(cee_wks_mergeable_obj eventing_headers) if (CLR_CMAKE_TARGET_WIN32) - if(NOT CLR_CMAKE_HOST_ARCH_ARM AND NOT CLR_CMAKE_HOST_ARCH_ARM64) if (CLR_CMAKE_HOST_ARCH_I386) @@ -34,33 +33,16 @@ if (CLR_CMAKE_TARGET_WIN32) endif (CLR_CMAKE_HOST_ARCH_I386) # Convert AsmConstants.h into AsmConstants.inc - find_program(POWERSHELL powershell) - if (POWERSHELL STREQUAL "POWERSHELL-NOTFOUND") - message(FATAL_ERROR "POWERSHELL not found") - endif() - - # Get the current list of definitions - get_compile_definitions(DEFINITIONS) - add_custom_command( - OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.inc" - DEPENDS ${VM_DIR}/${ARCH_SOURCES_DIR}/asmconstants.h - COMMAND ${POWERSHELL} -NoProfile -ExecutionPolicy Bypass -NonInteractive \"& \"\"${VM_DIR}/h2inc.ps1\"\"\" \"\"\"${VM_DIR}/${ARCH_SOURCES_DIR}/asmconstants.h\"\"\" >"${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.tmp" - COMMAND ${CMAKE_CXX_COMPILER} ${DEFINITIONS} /EP "${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.tmp" >"${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.inc" - ) + h2inc("${VM_DIR}/${ARCH_SOURCES_DIR}/asmconstants.h" "${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.tmp") + preprocess_file("${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.tmp" "${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.inc") - set_source_files_properties(${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.inc PROPERTIES GENERATED TRUE) - - add_custom_target( - asmconstants_inc - DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.inc - ) + add_custom_target(asmconstants_inc DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/AsmConstants.inc) add_dependencies(cee_wks_core asmconstants_inc) add_dependencies(cee_wks_obj asmconstants_inc) add_dependencies(cee_wks_mergeable_obj asmconstants_inc) endif(NOT CLR_CMAKE_HOST_ARCH_ARM AND NOT CLR_CMAKE_HOST_ARCH_ARM64) - endif (CLR_CMAKE_TARGET_WIN32) add_custom_target(precompiled_asm DEPENDS ${VM_WKS_ARCH_ASM_OBJECTS}) diff --git a/src/libraries/Common/src/Interop/Android/System.Security.Cryptography.Native.Android/Interop.Ssl.cs b/src/libraries/Common/src/Interop/Android/System.Security.Cryptography.Native.Android/Interop.Ssl.cs index f1200eabdd2a7..9ae88238278c1 100644 --- a/src/libraries/Common/src/Interop/Android/System.Security.Cryptography.Native.Android/Interop.Ssl.cs +++ b/src/libraries/Common/src/Interop/Android/System.Security.Cryptography.Native.Android/Interop.Ssl.cs @@ -233,8 +233,7 @@ private static partial void SSLStreamGetPeerCertificates( internal static IntPtr[]? SSLStreamGetPeerCertificates(SafeSslHandle ssl) { IntPtr[]? ptrs; - int count; - Interop.AndroidCrypto.SSLStreamGetPeerCertificates(ssl, out ptrs, out count); + Interop.AndroidCrypto.SSLStreamGetPeerCertificates(ssl, out ptrs, out _); return ptrs; } diff --git a/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Ssl.cs b/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Ssl.cs index 2e6e72c9418b4..af6596efd51da 100644 --- a/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Ssl.cs +++ b/src/libraries/Common/src/Interop/OSX/System.Security.Cryptography.Native.Apple/Interop.Ssl.cs @@ -46,6 +46,7 @@ internal enum PAL_TlsHandshakeState WouldBlock, ServerAuthCompleted, ClientAuthCompleted, + ClientCertRequested, } internal enum PAL_TlsIo @@ -99,6 +100,12 @@ private static partial int AppleCryptoNative_SslSetBreakOnClientAuth( int setBreak, out int pOSStatus); + [GeneratedDllImport(Interop.Libraries.AppleCryptoNative)] + private static partial int AppleCryptoNative_SslSetBreakOnCertRequested( + SafeSslHandle sslHandle, + int setBreak, + out int pOSStatus); + [GeneratedDllImport(Interop.Libraries.AppleCryptoNative)] private static partial int AppleCryptoNative_SslSetCertificate( SafeSslHandle sslHandle, @@ -266,6 +273,25 @@ internal static void SslBreakOnClientAuth(SafeSslHandle sslHandle, bool setBreak throw new SslException(); } + internal static void SslBreakOnCertRequested(SafeSslHandle sslHandle, bool setBreak) + { + int osStatus; + int result = AppleCryptoNative_SslSetBreakOnCertRequested(sslHandle, setBreak ? 1 : 0, out osStatus); + + if (result == 1) + { + return; + } + + if (result == 0) + { + throw CreateExceptionForOSStatus(osStatus); + } + + Debug.Fail($"AppleCryptoNative_SslSetBreakOnCertRequested returned {result}"); + throw new SslException(); + } + internal static void SslSetCertificate(SafeSslHandle sslHandle, IntPtr[] certChainPtrs) { using (SafeCreateHandle cfCertRefs = CoreFoundation.CFArrayCreate(certChainPtrs, (UIntPtr)certChainPtrs.Length)) diff --git a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.LChflags.cs b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.LChflags.cs index 1353fbc3acec6..a5bc36dfa3d2f 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Native/Interop.LChflags.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Native/Interop.LChflags.cs @@ -22,5 +22,11 @@ internal enum UserFlags : uint [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LChflagsCanSetHiddenFlag")] [SuppressGCTransition] private static partial int LChflagsCanSetHiddenFlag(); + + internal static readonly bool SupportsHiddenFlag = (CanGetHiddenFlag() != 0); + + [GeneratedDllImport(Libraries.SystemNative, EntryPoint = "SystemNative_CanGetHiddenFlag")] + [SuppressGCTransition] + private static partial int CanGetHiddenFlag(); } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs index 593c6f4e593f6..95e9ab89fc505 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.EvpPkey.cs @@ -105,18 +105,28 @@ internal static unsafe SafeEvpPKeyHandle DecodePkcs8PrivateKey( } [GeneratedDllImport(Libraries.CryptoNative)] - private static partial int CryptoNative_GetPkcs8PrivateKeySize(IntPtr pkey); + private static partial int CryptoNative_GetPkcs8PrivateKeySize(IntPtr pkey, out int p8size); private static int GetPkcs8PrivateKeySize(IntPtr pkey) { - int ret = CryptoNative_GetPkcs8PrivateKeySize(pkey); + const int Success = 1; + const int Error = -1; + const int MissingPrivateKey = -2; - if (ret < 0) + int ret = CryptoNative_GetPkcs8PrivateKeySize(pkey, out int p8size); + + switch (ret) { - throw CreateOpenSslCryptographicException(); + case Success: + return p8size; + case Error: + throw CreateOpenSslCryptographicException(); + case MissingPrivateKey: + throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey); + default: + Debug.Fail($"Unexpected return '{ret}' value from {nameof(CryptoNative_GetPkcs8PrivateKeySize)}."); + throw new CryptographicException(); } - - return ret; } [GeneratedDllImport(Libraries.CryptoNative)] diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs index 6e7701f57ae57..d403daac342ad 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs @@ -219,6 +219,45 @@ internal static SafeSslContextHandle AllocateSslContext(SafeFreeSslCredentials c return sslCtx; } + internal static void UpdateClientCertiticate(SafeSslHandle ssl, SslAuthenticationOptions sslAuthenticationOptions) + { + // Disable certificate selection callback. We either got certificate or we will try to proceed without it. + Interop.Ssl.SslSetClientCertCallback(ssl, 0); + + if (sslAuthenticationOptions.CertificateContext == null) + { + return; + } + + var credential = new SafeFreeSslCredentials(sslAuthenticationOptions.CertificateContext, sslAuthenticationOptions.EnabledSslProtocols, sslAuthenticationOptions.EncryptionPolicy, sslAuthenticationOptions.IsServer); + SafeX509Handle? certHandle = credential.CertHandle; + SafeEvpPKeyHandle? certKeyHandle = credential.CertKeyHandle; + + Debug.Assert(certHandle != null); + Debug.Assert(certKeyHandle != null); + + int retVal = Ssl.SslUseCertificate(ssl, certHandle); + if (1 != retVal) + { + throw CreateSslException(SR.net_ssl_use_cert_failed); + } + + retVal = Ssl.SslUsePrivateKey(ssl, certKeyHandle); + if (1 != retVal) + { + throw CreateSslException(SR.net_ssl_use_private_key_failed); + } + + if (sslAuthenticationOptions.CertificateContext.IntermediateCertificates.Length > 0) + { + if (!Ssl.AddExtraChainCertificates(ssl, sslAuthenticationOptions.CertificateContext.IntermediateCertificates)) + { + throw CreateSslException(SR.net_ssl_use_cert_failed); + } + } + + } + // This essentially wraps SSL* SSL_new() internal static SafeSslHandle AllocateSslHandle(SafeFreeSslCredentials credential, SslAuthenticationOptions sslAuthenticationOptions) { @@ -287,6 +326,13 @@ internal static SafeSslHandle AllocateSslHandle(SafeFreeSslCredentials credentia { Crypto.ErrClearError(); } + + if (sslAuthenticationOptions.CertSelectionDelegate != null && sslAuthenticationOptions.CertificateContext == null) + { + // We don't have certificate but we have callback. We should wait for remote certificate and + // possible trusted issuer list. + Interop.Ssl.SslSetClientCertCallback(sslHandle, 1); + } } if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired) @@ -324,7 +370,7 @@ internal static SecurityStatusPal SslRenegotiate(SafeSslHandle sslContext, out b return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } - internal static bool DoSslHandshake(SafeSslHandle context, ReadOnlySpan input, out byte[]? sendBuf, out int sendCount) + internal static SecurityStatusPalErrorCode DoSslHandshake(SafeSslHandle context, ReadOnlySpan input, out byte[]? sendBuf, out int sendCount) { sendBuf = null; sendCount = 0; @@ -345,6 +391,11 @@ internal static bool DoSslHandshake(SafeSslHandle context, ReadOnlySpan in Exception? innerError; Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError); + if (error == Ssl.SslErrorCode.SSL_ERROR_WANT_X509_LOOKUP) + { + return SecurityStatusPalErrorCode.CredentialsNeeded; + } + if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ)) { // Handshake failed, but even if the handshake does not need to read, there may be an Alert going out. @@ -389,7 +440,8 @@ internal static bool DoSslHandshake(SafeSslHandle context, ReadOnlySpan in { context.MarkHandshakeCompleted(); } - return stateOk; + + return stateOk ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.ContinueNeeded; } internal static int Encrypt(SafeSslHandle context, ReadOnlySpan input, ref byte[] output, out Ssl.SslErrorCode errorCode) diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs index 8d1cad3d480fd..379ab7586ed38 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs @@ -6,6 +6,8 @@ using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; @@ -46,7 +48,7 @@ internal static partial class Ssl internal static partial void SslSetAcceptState(SafeSslHandle ssl); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAlpnProtos")] - internal static partial int SslSetAlpnProtos(SafeSslHandle ssl, IntPtr protos, int len); + internal static unsafe partial int SslSetAlpnProtos(SafeSslHandle ssl, byte* protos, int len); [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")] internal static partial IntPtr SslGetVersion(SafeSslHandle ssl); @@ -149,6 +151,15 @@ internal static partial class Ssl [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetData")] internal static partial int SslSetData(IntPtr ssl, IntPtr data); + [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslUseCertificate")] + internal static extern int SslUseCertificate(SafeSslHandle ssl, SafeX509Handle certPtr); + + [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslUsePrivateKey")] + internal static extern int SslUsePrivateKey(SafeSslHandle ssl, SafeEvpPKeyHandle keyPtr); + + [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetClientCertCallback")] + internal static extern unsafe void SslSetClientCertCallback(SafeSslHandle ssl, int set); + [GeneratedDllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_Tls13Supported")] private static partial int Tls13SupportedImpl(); @@ -158,16 +169,7 @@ internal static class Capabilities internal static readonly bool Tls13Supported = Tls13SupportedImpl() != 0; } - internal static unsafe int SslSetAlpnProtos(SafeSslHandle ssl, List protocols) - { - byte[] buffer = ConvertAlpnProtocolListToByteArray(protocols); - fixed (byte* b = buffer) - { - return SslSetAlpnProtos(ssl, (IntPtr)b, buffer.Length); - } - } - - internal static byte[] ConvertAlpnProtocolListToByteArray(List applicationProtocols) + internal static int GetAlpnProtocolListSerializedLength(List applicationProtocols) { int protocolSize = 0; foreach (SslApplicationProtocol protocol in applicationProtocols) @@ -180,16 +182,59 @@ internal static byte[] ConvertAlpnProtocolListToByteArray(List applicationProtocols, Span buffer) + { + Debug.Assert(GetAlpnProtocolListSerializedLength(applicationProtocols) == buffer.Length, + "GetAlpnProtocolListSerializedSize(applicationProtocols) == buffer.Length"); + + int offset = 0; foreach (SslApplicationProtocol protocol in applicationProtocols) { - buffer[offset++] = (byte)(protocol.Protocol.Length); - protocol.Protocol.Span.CopyTo(buffer.AsSpan(offset)); + buffer[offset++] = (byte)protocol.Protocol.Length; + protocol.Protocol.Span.CopyTo(buffer.Slice(offset)); offset += protocol.Protocol.Length; } + } - return buffer; + internal static unsafe int SslSetAlpnProtos(SafeSslHandle ssl, List applicationProtocols) + { + int length = GetAlpnProtocolListSerializedLength(applicationProtocols); + Span buffer = length <= 256 ? stackalloc byte[256].Slice(0, length) : new byte[length]; + SerializeAlpnProtocolList(applicationProtocols, buffer); + return SslSetAlpnProtos(ssl, buffer); + } + + internal static unsafe int SslSetAlpnProtos(SafeSslHandle ssl, Span serializedProtocols) + { + fixed (byte* pBuffer = &MemoryMarshal.GetReference(serializedProtocols)) + { + return SslSetAlpnProtos(ssl, pBuffer, serializedProtocols.Length); + } + } + + [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")] + internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509); + + internal static bool AddExtraChainCertificates(SafeSslHandle ssl, X509Certificate2[] chain) + { + // send pre-computed list of intermediates. + for (int i = 0; i < chain.Length; i++) + { + SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain[i].Handle); + Crypto.CheckValidOpenSslHandle(dupCertHandle); + if (!SslAddExtraChainCert(ssl, dupCertHandle)) + { + Crypto.ErrClearError(); + dupCertHandle.Dispose(); // we still own the safe handle; clean it up + return false; + } + dupCertHandle.SetHandleAsInvalid(); // ownership has been transferred to sslHandle; do not free via this safe handle + } + + return true; } internal static string? GetOpenSslCipherSuiteName(SafeSslHandle ssl, TlsCipherSuite cipherSuite, out bool isTls12OrLower) @@ -224,6 +269,7 @@ internal enum SslErrorCode SSL_ERROR_SSL = 1, SSL_ERROR_WANT_READ = 2, SSL_ERROR_WANT_WRITE = 3, + SSL_ERROR_WANT_X509_LOOKUP = 4, SSL_ERROR_SYSCALL = 5, SSL_ERROR_ZERO_RETURN = 6, diff --git a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetConsoleMode.cs b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetConsoleMode.cs index 6eb46b1f4b6d9..8275904b8286b 100644 --- a/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetConsoleMode.cs +++ b/src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetConsoleMode.cs @@ -13,8 +13,7 @@ internal static partial class Kernel32 internal static bool IsGetConsoleModeCallSuccessful(IntPtr handle) { - int mode; - return GetConsoleMode(handle, out mode); + return GetConsoleMode(handle, out _); } [GeneratedDllImport(Libraries.Kernel32, SetLastError = true)] diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs index 43b718524d1ca..8c3b6d815c169 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs @@ -49,9 +49,7 @@ internal void Set(IntPtr value) internal static int EnumeratePackages(out int pkgnum, out SafeFreeContextBuffer pkgArray) { - int res = -1; - SafeFreeContextBuffer_SECURITY? pkgArray_SECURITY = null; - res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out pkgArray_SECURITY); + int res = Interop.SspiCli.EnumerateSecurityPackagesW(out pkgnum, out SafeFreeContextBuffer_SECURITY? pkgArray_SECURITY); pkgArray = pkgArray_SECURITY; if (res != 0) @@ -230,11 +228,8 @@ public static unsafe int AcquireCredentialsHandle( ref SafeSspiAuthDataHandle authdata, out SafeFreeCredentials outCredential) { - int errorCode = -1; - long timeStamp; - outCredential = new SafeFreeCredential_SECURITY(); - errorCode = Interop.SspiCli.AcquireCredentialsHandleW( + int errorCode = Interop.SspiCli.AcquireCredentialsHandleW( null, package, (int)intent, @@ -243,7 +238,7 @@ public static unsafe int AcquireCredentialsHandle( null, null, ref outCredential._handle, - out timeStamp); + out _); if (errorCode != 0) { @@ -260,7 +255,6 @@ public static unsafe int AcquireCredentialsHandle( out SafeFreeCredentials outCredential) { int errorCode = -1; - long timeStamp; outCredential = new SafeFreeCredential_SECURITY(); @@ -273,7 +267,7 @@ public static unsafe int AcquireCredentialsHandle( null, null, ref outCredential._handle, - out timeStamp); + out _); if (NetEventSource.Log.IsEnabled()) NetEventSource.Verbose(null, $"{nameof(Interop.SspiCli.AcquireCredentialsHandleW)} returns 0x{errorCode:x}, handle = {outCredential}"); diff --git a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs index 2ab6998096704..253e0548dea9d 100644 --- a/src/libraries/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs +++ b/src/libraries/Common/src/Microsoft/Win32/SafeHandles/GssSafeHandles.cs @@ -54,8 +54,7 @@ public override bool IsInvalid protected override bool ReleaseHandle() { - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.ReleaseName(out minorStatus, ref handle); + Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.ReleaseName(out _, ref handle); SetHandle(IntPtr.Zero); return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE; } @@ -75,7 +74,7 @@ internal sealed class SafeGssCredHandle : SafeHandle public static SafeGssCredHandle CreateAcceptor() { - SafeGssCredHandle? retHandle = null; + SafeGssCredHandle? retHandle; Interop.NetSecurityNative.Status status; Interop.NetSecurityNative.Status minorStatus; @@ -143,8 +142,7 @@ public override bool IsInvalid protected override bool ReleaseHandle() { - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.ReleaseCred(out minorStatus, ref handle); + Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.ReleaseCred(out _, ref handle); SetHandle(IntPtr.Zero); return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE; } @@ -169,8 +167,7 @@ public override bool IsInvalid protected override unsafe bool ReleaseHandle() { - Interop.NetSecurityNative.Status minorStatus; - Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.DeleteSecContext(out minorStatus, ref handle); + Interop.NetSecurityNative.Status status = Interop.NetSecurityNative.DeleteSecContext(out _, ref handle); SetHandle(IntPtr.Zero); return status == Interop.NetSecurityNative.Status.GSS_S_COMPLETE; } diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs index 5418b4ff8bba7..d329db38dd031 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionFactory.cs @@ -386,23 +386,13 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo // if two threads happen to hit this at the same time. One will be GC'd if (metaDataFactory == null) { - bool allowCache = false; - metaDataFactory = CreateMetaDataFactory(internalConnection, out allowCache); - if (allowCache) - { - connectionPoolGroup.MetaDataFactory = metaDataFactory; - } + metaDataFactory = CreateMetaDataFactory(internalConnection); + connectionPoolGroup.MetaDataFactory = metaDataFactory; } return metaDataFactory; } - protected virtual DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory) - { - // providers that support GetSchema must override this with a method that creates a meta data - // factory appropriate for them. - cacheMetaDataFactory = false; - throw ADP.NotSupported(); - } + protected abstract DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection); protected abstract DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool? pool, DbConnection? owningConnection); diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs index 5c1c4c0034cd9..1103b6488733b 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbConnectionInternal.cs @@ -319,7 +319,7 @@ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnect // ?->Connecting: prevent set_ConnectionString during Open if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) { - DbConnectionInternal? openConnection = null; + DbConnectionInternal? openConnection; try { connectionFactory.PermissionDemand(outerConnection); diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs index e2727c92b6bdf..61f4cfcb9ce08 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -109,8 +109,8 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName]!; DataTable? resultTable = null; - DbCommand? command = null; - DataTable? schemaTable = null; + DbCommand? command; + DataTable? schemaTable; Debug.Assert(requestedCollectionRow != null); string sqlCommand = (requestedCollectionRow[populationStringColumn, DataRowVersion.Current] as string)!; @@ -185,7 +185,6 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest if (reader != null) { reader.Dispose(); - reader = null; } } return resultTable; @@ -341,8 +340,8 @@ private void FixUpVersion(DataTable dataSourceInfoTable) private string GetParameterName(string neededCollectionName, int neededRestrictionNumber) { - DataTable? restrictionsTable = null; - DataColumnCollection? restrictionColumns = null; + DataTable? restrictionsTable; + DataColumnCollection? restrictionColumns; DataColumn? collectionName = null; DataColumn? parameterName = null; DataColumn? restrictionName = null; @@ -396,10 +395,10 @@ public virtual DataTable GetSchema(DbConnection connection, string collectionNam DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism]!; DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]!; - DataRow? requestedCollectionRow = null; - DataTable? requestedSchema = null; + DataRow? requestedCollectionRow; + DataTable? requestedSchema; string[]? hiddenColumns; - string? exactCollectionName = null; + string? exactCollectionName; requestedCollectionRow = FindMetaDataCollectionRow(collectionName); exactCollectionName = (requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string)!; diff --git a/src/libraries/Common/src/System/Diagnostics/NetFrameworkUtils.cs b/src/libraries/Common/src/System/Diagnostics/NetFrameworkUtils.cs index 4bab9a4590c35..d8ec150103d9b 100644 --- a/src/libraries/Common/src/System/Diagnostics/NetFrameworkUtils.cs +++ b/src/libraries/Common/src/System/Diagnostics/NetFrameworkUtils.cs @@ -19,9 +19,7 @@ internal static void EnterMutex(string name, ref Mutex mutex) internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex) { - bool createdNew; - - Mutex tmpMutex = new Mutex(false, mutexName, out createdNew); + Mutex tmpMutex = new Mutex(false, mutexName, out _); SafeWaitForMutex(tmpMutex, ref mutex); } diff --git a/src/libraries/Common/src/System/IO/FileSystem.Attributes.Windows.cs b/src/libraries/Common/src/System/IO/FileSystem.Attributes.Windows.cs index 7e7afcec97a72..dab4cf7a8f6c5 100644 --- a/src/libraries/Common/src/System/IO/FileSystem.Attributes.Windows.cs +++ b/src/libraries/Common/src/System/IO/FileSystem.Attributes.Windows.cs @@ -15,7 +15,7 @@ internal static partial class FileSystem { public static bool DirectoryExists(string? fullPath) { - return DirectoryExists(fullPath, out int lastError); + return DirectoryExists(fullPath, out _); } private static bool DirectoryExists(string? path, out int lastError) diff --git a/src/libraries/Common/src/System/IO/TempFileCollection.cs b/src/libraries/Common/src/System/IO/TempFileCollection.cs index 4c29dc0e70c38..95ca600bf2fab 100644 --- a/src/libraries/Common/src/System/IO/TempFileCollection.cs +++ b/src/libraries/Common/src/System/IO/TempFileCollection.cs @@ -116,8 +116,8 @@ private void EnsureTempNameCreated() { if (_basePath == null) { - string tempFileName = null; - bool uniqueFile = false; + string tempFileName; + bool uniqueFile; int retryCount = 5000; do { diff --git a/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs b/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs index 148d1dc9a0700..a46e7314c9f50 100644 --- a/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs +++ b/src/libraries/Common/src/System/Net/NTAuthentication.Common.cs @@ -179,8 +179,7 @@ internal int MakeSignature(byte[] buffer, int offset, int count, [AllowNull] ref } else { - SecurityStatusPal statusCode; - decodedOutgoingBlob = GetOutgoingBlob(decodedIncomingBlob, true, out statusCode); + decodedOutgoingBlob = GetOutgoingBlob(decodedIncomingBlob, true); } string? outgoingBlob = null; @@ -199,8 +198,7 @@ internal int MakeSignature(byte[] buffer, int offset, int count, [AllowNull] ref internal byte[]? GetOutgoingBlob(byte[]? incomingBlob, bool thrownOnError) { - SecurityStatusPal statusCode; - return GetOutgoingBlob(incomingBlob, thrownOnError, out statusCode); + return GetOutgoingBlob(incomingBlob, thrownOnError, out _); } // Accepts an incoming binary security blob and returns an outgoing binary security blob. diff --git a/src/libraries/Common/src/System/Net/SocketProtocolSupportPal.Unix.cs b/src/libraries/Common/src/System/Net/SocketProtocolSupportPal.Unix.cs index 8de1e2a0f4ce3..c755c16517c77 100644 --- a/src/libraries/Common/src/System/Net/SocketProtocolSupportPal.Unix.cs +++ b/src/libraries/Common/src/System/Net/SocketProtocolSupportPal.Unix.cs @@ -15,7 +15,9 @@ private static unsafe bool IsSupported(AddressFamily af) IntPtr socket = invalid; try { - return Interop.Sys.Socket(af, SocketType.Dgram, 0, &socket) != Interop.Error.EAFNOSUPPORT; + Interop.Error result = Interop.Sys.Socket(af, SocketType.Dgram, 0, &socket); + // we get EAFNOSUPPORT when family is not supported by Kernel, EPROTONOSUPPORT may come from policy enforcement like FreeBSD jail() + return result != Interop.Error.EAFNOSUPPORT && result != Interop.Error.EPROTONOSUPPORT; } finally { diff --git a/src/libraries/Common/src/System/Resources/ResourceWriter.cs b/src/libraries/Common/src/System/Resources/ResourceWriter.cs index 71697a29e04bb..b9184070fbc8b 100644 --- a/src/libraries/Common/src/System/Resources/ResourceWriter.cs +++ b/src/libraries/Common/src/System/Resources/ResourceWriter.cs @@ -595,7 +595,7 @@ private void WriteValue(ResourceTypeCode typeCode, object? value, BinaryWriter w s.Position = 0; writer.Write((int)s.Length); byte[] buffer = new byte[4096]; - int read = 0; + int read; while ((read = s.Read(buffer, 0, buffer.Length)) != 0) { writer.Write(buffer, 0, read); diff --git a/src/libraries/Common/src/System/Security/Cryptography/EccSecurityTransforms.macOS.cs b/src/libraries/Common/src/System/Security/Cryptography/EccSecurityTransforms.macOS.cs index af0bdd21d7dc9..8e9c3f8790acd 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/EccSecurityTransforms.macOS.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/EccSecurityTransforms.macOS.cs @@ -29,7 +29,7 @@ private static ECParameters ExportParametersFromLegacyKey(SecKeyPair keys, bool { EccKeyFormatHelper.ReadSubjectPublicKeyInfo( keyBlob, - out int localRead, + out _, out ECParameters key); return key; } @@ -38,7 +38,7 @@ private static ECParameters ExportParametersFromLegacyKey(SecKeyPair keys, bool EccKeyFormatHelper.ReadEncryptedPkcs8( keyBlob, ExportPassword, - out int localRead, + out _, out ECParameters key); return key; } diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs b/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs index fcd2d846a265c..c78de73548035 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSAAndroid.cs @@ -690,7 +690,7 @@ public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RS Span.Empty, hashAlgorithm, padding, true, - out int bytesWritten, + out _, out byte[]? signature)) { Debug.Fail("TrySignHash should not return false in allocation mode"); diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs b/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs index f80a641a98f01..149e240893039 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSAOpenSsl.cs @@ -762,7 +762,7 @@ public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RS Span.Empty, hashAlgorithm, padding, true, - out int bytesWritten, + out _, out byte[]? signature)) { Debug.Fail("TrySignHash should not return false in allocation mode"); diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs index 29ce858255e76..7bce2648d443a 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.cs @@ -564,7 +564,7 @@ public override bool VerifyHash(ReadOnlySpan hash, ReadOnlySpan sign if (padding == RSASignaturePadding.Pkcs1) { Interop.AppleCrypto.PAL_HashAlgorithm palAlgId = - PalAlgorithmFromAlgorithmName(hashAlgorithm, out int expectedSize); + PalAlgorithmFromAlgorithmName(hashAlgorithm, out _); return Interop.AppleCrypto.VerifySignature( GetKeys().PublicKey, hash, diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.macOS.cs b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.macOS.cs index 8496d3ab2fc0e..2a99e40a129df 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.macOS.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSASecurityTransforms.macOS.cs @@ -62,7 +62,7 @@ private static RSAParameters ExportParametersFromLegacyKey(SecKeyPair keys, bool RSAKeyFormatHelper.ReadEncryptedPkcs8( keyBlob, ExportPassword, - out int localRead, + out _, out RSAParameters key); return key; } diff --git a/src/libraries/Common/tests/System/Collections/DebugView.Tests.cs b/src/libraries/Common/tests/System/Collections/DebugView.Tests.cs index 35e6b16b65415..d363af3479c3b 100644 --- a/src/libraries/Common/tests/System/Collections/DebugView.Tests.cs +++ b/src/libraries/Common/tests/System/Collections/DebugView.Tests.cs @@ -60,7 +60,7 @@ public static IEnumerable TestDebuggerAttributes_Inputs() yield return new object[] { new SortedList{{1f, 1L}, {2f, 2L}}.Values }; } - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsDebuggerTypeProxyAttributeSupported))] [MemberData(nameof(TestDebuggerAttributes_Inputs))] public static void TestDebuggerAttributes(object obj) { @@ -71,7 +71,7 @@ public static void TestDebuggerAttributes(object obj) Assert.Equal((obj as IEnumerable).Cast().ToArray(), items.Cast()); } - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsDebuggerTypeProxyAttributeSupported))] [MemberData(nameof(TestDebuggerAttributes_Inputs))] public static void TestDebuggerAttributes_Null(object obj) { diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index 7ee8b9c6ee40e..13425342d094c 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -7,6 +7,7 @@ using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; +using System.Text; namespace System.IO { @@ -133,6 +134,33 @@ protected string GetTestFileName(int? index = null, [CallerMemberName] string me return testFileName; } + protected static string GetNamedPipeServerStreamName() + { + if (PlatformDetection.IsInAppContainer) + { + return @"LOCAL\" + Guid.NewGuid().ToString("N"); + } + + if (PlatformDetection.IsWindows) + { + return Guid.NewGuid().ToString("N"); + } + + const int MinUdsPathLength = 104; // required min is 92, but every platform we currently target is at least 104 + const int MinAvailableForSufficientRandomness = 5; // we want enough randomness in the name to avoid conflicts between concurrent tests + string prefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_"); + int availableLength = MinUdsPathLength - prefix.Length - 1; // 1 - for possible null terminator + Assert.True(availableLength >= MinAvailableForSufficientRandomness, $"UDS prefix {prefix} length {prefix.Length} is too long"); + + StringBuilder sb = new(availableLength); + Random random = new Random(); + for (int i = 0; i < availableLength; i++) + { + sb.Append((char)('a' + random.Next(0, 26))); + } + return sb.ToString(); + } + private string GenerateTestFileName(int? index, string memberName, int lineNumber) => string.Format( index.HasValue ? "{0}_{1}_{2}_{3}" : "{0}_{1}_{3}", diff --git a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs index ac167ec7cecaf..207cd17f3b538 100644 --- a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs +++ b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.Unix.cs @@ -57,6 +57,11 @@ public static partial class PlatformDetection GetOpenSslVersion() : throw new PlatformNotSupportedException(); + private static readonly Version s_openssl3Version = new Version(3, 0, 0); + public static bool IsOpenSsl3 => !IsOSXLike && !IsWindows && !IsAndroid && !IsBrowser ? + GetOpenSslVersion() >= s_openssl3Version : + false; + /// /// If gnulibc is available, returns the release, such as "stable". /// Otherwise returns "glibc_not_found". diff --git a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs index 8ff457f1deed8..a2a2e9634489b 100644 --- a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs +++ b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs @@ -28,6 +28,7 @@ public static partial class PlatformDetection public static bool IsMonoInterpreter => GetIsRunningOnMonoInterpreter(); public static bool IsMonoAOT => Environment.GetEnvironmentVariable("MONO_AOT_MODE") == "aot"; public static bool IsNotMonoAOT => Environment.GetEnvironmentVariable("MONO_AOT_MODE") != "aot"; + public static bool IsNativeAot => IsNotMonoRuntime && !IsReflectionEmitSupported; public static bool IsFreeBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD")); public static bool IsNetBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")); public static bool IsAndroid => RuntimeInformation.IsOSPlatform(OSPlatform.Create("ANDROID")); @@ -52,7 +53,7 @@ public static partial class PlatformDetection public static bool IsNotArmNorArm64Process => !IsArmOrArm64Process; public static bool IsX86Process => RuntimeInformation.ProcessArchitecture == Architecture.X86; public static bool IsNotX86Process => !IsX86Process; - public static bool IsArgIteratorSupported => IsMonoRuntime || (IsWindows && IsNotArmProcess); + public static bool IsArgIteratorSupported => IsMonoRuntime || (IsWindows && IsNotArmProcess && !IsNativeAot); public static bool IsArgIteratorNotSupported => !IsArgIteratorSupported; public static bool Is32BitProcess => IntPtr.Size == 4; public static bool Is64BitProcess => IntPtr.Size == 8; @@ -62,7 +63,7 @@ public static partial class PlatformDetection public static bool IsCaseSensitiveOS => !IsCaseInsensitiveOS; public static bool IsThreadingSupported => !IsBrowser; - public static bool IsBinaryFormatterSupported => IsNotMobile; + public static bool IsBinaryFormatterSupported => IsNotMobile && !IsNativeAot; public static bool IsSymLinkSupported => !IsiOS && !IstvOS; public static bool IsSpeedOptimized => !IsSizeOptimized; @@ -118,10 +119,10 @@ public static bool IsDrawingSupported public static bool IsAsyncFileIOSupported => !IsBrowser && !(IsWindows && IsMonoRuntime); // https://github.com/dotnet/runtime/issues/34582 - public static bool IsLineNumbersSupported => true; + public static bool IsLineNumbersSupported => !IsNativeAot; public static bool IsInContainer => GetIsInContainer(); - public static bool SupportsComInterop => IsWindows && IsNotMonoRuntime; // matches definitions in clr.featuredefines.props + public static bool SupportsComInterop => IsWindows && IsNotMonoRuntime && !IsNativeAot; // matches definitions in clr.featuredefines.props public static bool SupportsSsl3 => GetSsl3Support(); public static bool SupportsSsl2 => IsWindows && !PlatformDetection.IsWindows10Version1607OrGreater; @@ -132,7 +133,9 @@ public static bool IsDrawingSupported public static bool IsReflectionEmitSupported => true; #endif - public static bool IsInvokingStaticConstructorsSupported => true; + public static bool IsInvokingStaticConstructorsSupported => !IsNativeAot; + + public static bool IsMetadataUpdateSupported => !IsNativeAot; // System.Security.Cryptography.Xml.XmlDsigXsltTransform.GetOutput() relies on XslCompiledTransform which relies // heavily on Reflection.Emit @@ -142,6 +145,10 @@ public static bool IsDrawingSupported public static bool IsNotIntMaxValueArrayIndexSupported => s_largeArrayIsNotSupported.Value; + public static bool IsAssemblyLoadingSupported => !IsNativeAot; + public static bool IsMethodBodySupported => !IsNativeAot; + public static bool IsDebuggerTypeProxyAttributeSupported => !IsNativeAot; + private static volatile Tuple s_lazyNonZeroLowerBoundArraySupported; public static bool IsNonZeroLowerBoundArraySupported { @@ -164,6 +171,28 @@ public static bool IsNonZeroLowerBoundArraySupported } } + private static volatile Tuple s_lazyMetadataTokensSupported; + public static bool IsMetadataTokenSupported + { + get + { + if (s_lazyMetadataTokensSupported == null) + { + bool metadataTokensSupported = false; + try + { + _ = typeof(PlatformDetection).MetadataToken; + metadataTokensSupported = true; + } + catch (InvalidOperationException) + { + } + s_lazyMetadataTokensSupported = Tuple.Create(metadataTokensSupported); + } + return s_lazyMetadataTokensSupported.Item1; + } + } + public static bool IsDomainJoinedMachine => !Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.OrdinalIgnoreCase); public static bool IsNotDomainJoinedMachine => !IsDomainJoinedMachine; @@ -189,7 +218,12 @@ private static bool GetAlpnSupport() if (IsOpenSslSupported) { - return OpenSslVersion.Major >= 1 && (OpenSslVersion.Minor >= 1 || OpenSslVersion.Build >= 2); + if (OpenSslVersion.Major >= 3) + { + return true; + } + + return OpenSslVersion.Major == 1 && (OpenSslVersion.Minor >= 1 || OpenSslVersion.Build >= 2); } if (IsAndroid) diff --git a/src/libraries/Common/tests/Tests/System/StringTests.cs b/src/libraries/Common/tests/Tests/System/StringTests.cs index c9c617ca640db..6e863d253a474 100644 --- a/src/libraries/Common/tests/Tests/System/StringTests.cs +++ b/src/libraries/Common/tests/Tests/System/StringTests.cs @@ -7320,6 +7320,7 @@ public static unsafe void CopyTest() } [Fact] + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/155", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] public static unsafe void InternTest() { AssertExtensions.Throws("str", () => string.Intern(null)); diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/DynamicDebuggerProxy.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/DynamicDebuggerProxy.cs index c04fa1735478e..dafa11e908b9f 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/DynamicDebuggerProxy.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/DynamicDebuggerProxy.cs @@ -238,8 +238,8 @@ public static object TryEvalMethodVarArgs( Type accessibilityContext, Type[] typeArguments) { - Type[] delegateSignatureTypes = null; - CSharpArgumentInfo[] argInfos = null; + Type[] delegateSignatureTypes; + CSharpArgumentInfo[] argInfos; CreateDelegateSignatureAndArgumentInfos( methodArgs, @@ -315,8 +315,8 @@ public static object TryGetMemberValueVarArgs( CSharpArgumentInfoFlags[] argFlags, Type accessibilityContext) { - Type[] delegateSignatureTypes = null; - CSharpArgumentInfo[] argInfos = null; + Type[] delegateSignatureTypes; + CSharpArgumentInfo[] argInfos; CreateDelegateSignatureAndArgumentInfos( propArgs, @@ -381,8 +381,8 @@ public static object TrySetMemberValueVarArgs( CSharpArgumentInfoFlags[] argFlags, Type accessibilityContext) { - Type[] delegateSignatureTypes = null; - CSharpArgumentInfo[] argInfos = null; + Type[] delegateSignatureTypes; + CSharpArgumentInfo[] argInfos; CreateDelegateSignatureAndArgumentInfos( propArgs, diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs index cb2dd20c9bce0..a29175fe6c431 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs @@ -1092,8 +1092,7 @@ private static void MarkAsIntermediateConversion(Expr pExpr) [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr BindUDConversionCore(Expr pFrom, CType pTypeFrom, CType pTypeTo, CType pTypeDestination, MethWithInst mwiBest) { - Expr ppTransformedArgument; - return BindUDConversionCore(pFrom, pTypeFrom, pTypeTo, pTypeDestination, mwiBest, out ppTransformedArgument); + return BindUDConversionCore(pFrom, pTypeFrom, pTypeTo, pTypeDestination, mwiBest, out _); } [RequiresUnreferencedCode(Binder.TrimmerWarning)] @@ -1237,7 +1236,6 @@ private ConstCastResult bindConstantCast(Expr exprSrc, CType typeDest, bool need case FUNDTYPE.FT_U8: if (!srcIntegral) { - valueInt = (long)(ulong)valueFlt; const double two63 = 2147483648.0 * 4294967296.0; if (valueFlt < two63) { diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs index b5775612b2c1a..271c136fd2ce3 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryCache.cs @@ -140,7 +140,7 @@ internal void SetEntry(CacheEntry entry) bool exceedsCapacity = UpdateCacheSizeExceedsCapacity(entry, coherentState); if (!exceedsCapacity) { - bool entryAdded = false; + bool entryAdded; if (priorEntry == null) { @@ -329,11 +329,10 @@ private bool UpdateCacheSizeExceedsCapacity(CacheEntry entry, CoherentState cohe return false; } - long newSize = 0L; for (int i = 0; i < 100; i++) { long sizeRead = coherentState.Size; - newSize = sizeRead + entry.Size.Value; + long newSize = sizeRead + entry.Size.Value; if (newSize < 0 || newSize > _options.SizeLimit) { diff --git a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs index e867c7ecec0fd..ec8d34cb35851 100644 --- a/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs +++ b/src/libraries/Microsoft.Extensions.Caching.Memory/src/MemoryDistributedCache.cs @@ -107,7 +107,7 @@ public void Refresh(string key) throw new ArgumentNullException(nameof(key)); } - _memCache.TryGetValue(key, out object value); + _memCache.TryGetValue(key, out _); } public Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)) diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/ref/Microsoft.Extensions.Configuration.FileExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/ref/Microsoft.Extensions.Configuration.FileExtensions.cs index 9314e23ef311e..57e46ec6dcac2 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/ref/Microsoft.Extensions.Configuration.FileExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/ref/Microsoft.Extensions.Configuration.FileExtensions.cs @@ -8,7 +8,7 @@ namespace Microsoft.Extensions.Configuration { public static partial class FileConfigurationExtensions { - public static System.Action GetFileLoadExceptionHandler(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder) { throw null; } + public static System.Action? GetFileLoadExceptionHandler(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder) { throw null; } public static Microsoft.Extensions.FileProviders.IFileProvider GetFileProvider(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder SetBasePath(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, string basePath) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder SetFileLoadExceptionHandler(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, System.Action handler) { throw null; } @@ -27,10 +27,11 @@ public override void Load() { } public abstract partial class FileConfigurationSource : Microsoft.Extensions.Configuration.IConfigurationSource { protected FileConfigurationSource() { } - public Microsoft.Extensions.FileProviders.IFileProvider FileProvider { get { throw null; } set { } } - public System.Action OnLoadException { get { throw null; } set { } } + public Microsoft.Extensions.FileProviders.IFileProvider? FileProvider { get { throw null; } set { } } + public System.Action? OnLoadException { get { throw null; } set { } } public bool Optional { get { throw null; } set { } } - public string Path { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.DisallowNull] + public string? Path { get { throw null; } set { } } public int ReloadDelay { get { throw null; } set { } } public bool ReloadOnChange { get { throw null; } set { } } public abstract Microsoft.Extensions.Configuration.IConfigurationProvider Build(Microsoft.Extensions.Configuration.IConfigurationBuilder builder); diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/ref/Microsoft.Extensions.Configuration.FileExtensions.csproj b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/ref/Microsoft.Extensions.Configuration.FileExtensions.csproj index f7a69d4e76c85..2e8aa6b1a125f 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/ref/Microsoft.Extensions.Configuration.FileExtensions.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/ref/Microsoft.Extensions.Configuration.FileExtensions.csproj @@ -1,6 +1,8 @@ + $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) + enable diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs index 4ce12bd020caf..815905130036a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationExtensions.cs @@ -43,9 +43,9 @@ public static IFileProvider GetFileProvider(this IConfigurationBuilder builder) throw new ArgumentNullException(nameof(builder)); } - if (builder.Properties.TryGetValue(FileProviderKey, out object provider)) + if (builder.Properties.TryGetValue(FileProviderKey, out object? provider)) { - return provider as IFileProvider; + return (IFileProvider)provider; } return new PhysicalFileProvider(AppContext.BaseDirectory ?? string.Empty); @@ -94,14 +94,14 @@ public static IConfigurationBuilder SetFileLoadExceptionHandler(this IConfigurat /// /// The . /// The . - public static Action GetFileLoadExceptionHandler(this IConfigurationBuilder builder) + public static Action? GetFileLoadExceptionHandler(this IConfigurationBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } - if (builder.Properties.TryGetValue(FileLoadExceptionHandlerKey, out object handler)) + if (builder.Properties.TryGetValue(FileLoadExceptionHandlerKey, out object? handler)) { return handler as Action; } diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs index aef7acc13e5e9..60811023f6b38 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationProvider.cs @@ -17,7 +17,7 @@ namespace Microsoft.Extensions.Configuration /// public abstract class FileConfigurationProvider : ConfigurationProvider, IDisposable { - private readonly IDisposable _changeTokenRegistration; + private readonly IDisposable? _changeTokenRegistration; /// /// Initializes a new instance with the specified source. @@ -30,7 +30,7 @@ public FileConfigurationProvider(FileConfigurationSource source) if (Source.ReloadOnChange && Source.FileProvider != null) { _changeTokenRegistration = ChangeToken.OnChange( - () => Source.FileProvider.Watch(Source.Path), + () => Source.FileProvider.Watch(Source.Path!), () => { Thread.Sleep(Source.ReloadDelay); @@ -53,12 +53,12 @@ public override string ToString() private void Load(bool reload) { - IFileInfo file = Source.FileProvider?.GetFileInfo(Source.Path); + IFileInfo? file = Source.FileProvider?.GetFileInfo(Source.Path ?? string.Empty); if (file == null || !file.Exists) { if (Source.Optional || reload) // Always optional on reload { - Data = new Dictionary(StringComparer.OrdinalIgnoreCase); + Data = new Dictionary(StringComparer.OrdinalIgnoreCase); } else { @@ -100,7 +100,7 @@ static Stream OpenRead(IFileInfo fileInfo) { if (reload) { - Data = new Dictionary(StringComparer.OrdinalIgnoreCase); + Data = new Dictionary(StringComparer.OrdinalIgnoreCase); } var exception = new InvalidDataException(SR.Format(SR.Error_FailedToLoad, file.PhysicalPath), ex); HandleException(ExceptionDispatchInfo.Capture(exception)); diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationSource.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationSource.cs index 1122e6f171553..d58c265f406a9 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationSource.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileConfigurationSource.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.Extensions.FileProviders; @@ -15,12 +16,13 @@ public abstract class FileConfigurationSource : IConfigurationSource /// /// Used to access the contents of the file. /// - public IFileProvider FileProvider { get; set; } + public IFileProvider? FileProvider { get; set; } /// /// The path to the file. /// - public string Path { get; set; } + [DisallowNull] + public string? Path { get; set; } /// /// Determines if loading the file is optional. @@ -41,7 +43,7 @@ public abstract class FileConfigurationSource : IConfigurationSource /// /// Will be called if an uncaught exception occurs in FileConfigurationProvider.Load. /// - public Action OnLoadException { get; set; } + public Action? OnLoadException { get; set; } /// /// Builds the for this source. @@ -56,8 +58,8 @@ public abstract class FileConfigurationSource : IConfigurationSource /// The . public void EnsureDefaults(IConfigurationBuilder builder) { - FileProvider = FileProvider ?? builder.GetFileProvider(); - OnLoadException = OnLoadException ?? builder.GetFileLoadExceptionHandler(); + FileProvider ??= builder.GetFileProvider(); + OnLoadException ??= builder.GetFileLoadExceptionHandler(); } /// @@ -70,8 +72,8 @@ public void ResolveFileProvider() !string.IsNullOrEmpty(Path) && System.IO.Path.IsPathRooted(Path)) { - string directory = System.IO.Path.GetDirectoryName(Path); - string pathToFile = System.IO.Path.GetFileName(Path); + string? directory = System.IO.Path.GetDirectoryName(Path); + string? pathToFile = System.IO.Path.GetFileName(Path); while (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) { pathToFile = System.IO.Path.Combine(System.IO.Path.GetFileName(directory), pathToFile); @@ -84,6 +86,5 @@ public void ResolveFileProvider() } } } - } } diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileLoadExceptionContext.cs b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileLoadExceptionContext.cs index a87c82339f58c..1d619335d5e88 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileLoadExceptionContext.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/FileLoadExceptionContext.cs @@ -13,12 +13,12 @@ public class FileLoadExceptionContext /// /// The that caused the exception. /// - public FileConfigurationProvider Provider { get; set; } + public FileConfigurationProvider Provider { get; set; } = null!; /// /// The exception that occurred in Load. /// - public Exception Exception { get; set; } + public Exception Exception { get; set; } = null!; /// /// If true, the exception will not be rethrown. diff --git a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj index c256903f01cc2..e2c041ade1833 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.FileExtensions/src/Microsoft.Extensions.Configuration.FileExtensions.csproj @@ -2,6 +2,7 @@ $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) + enable true false diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.cs b/src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.cs index 9a73882b9e3a7..e23fd718f00d7 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.cs @@ -8,8 +8,8 @@ namespace Microsoft.Extensions.Configuration { public static partial class IniConfigurationExtensions { - public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddIniFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, Microsoft.Extensions.FileProviders.IFileProvider provider, string path, bool optional, bool reloadOnChange) { throw null; } - public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddIniFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, System.Action configureSource) { throw null; } + public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddIniFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, Microsoft.Extensions.FileProviders.IFileProvider? provider, string path, bool optional, bool reloadOnChange) { throw null; } + public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddIniFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, System.Action? configureSource) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddIniFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, string path) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddIniFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, string path, bool optional) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddIniFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) { throw null; } @@ -32,7 +32,7 @@ public partial class IniStreamConfigurationProvider : Microsoft.Extensions.Confi { public IniStreamConfigurationProvider(Microsoft.Extensions.Configuration.Ini.IniStreamConfigurationSource source) : base (default(Microsoft.Extensions.Configuration.StreamConfigurationSource)) { } public override void Load(System.IO.Stream stream) { } - public static System.Collections.Generic.IDictionary Read(System.IO.Stream stream) { throw null; } + public static System.Collections.Generic.IDictionary Read(System.IO.Stream stream) { throw null; } } public partial class IniStreamConfigurationSource : Microsoft.Extensions.Configuration.StreamConfigurationSource { diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.csproj b/src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.csproj index 7d73ff499998a..a4ee6a2df9438 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/ref/Microsoft.Extensions.Configuration.Ini.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) + enable diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs index 259417495a1d1..ab5442a919575 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniConfigurationExtensions.cs @@ -62,7 +62,7 @@ public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builde /// Whether the file is optional. /// Whether the configuration should be reloaded if the file changes. /// The . - public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) + public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { if (builder == null) { @@ -89,7 +89,7 @@ public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builde /// The to add to. /// Configures the source. /// The . - public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builder, Action configureSource) + public static IConfigurationBuilder AddIniFile(this IConfigurationBuilder builder, Action? configureSource) => builder.Add(configureSource); /// diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniStreamConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniStreamConfigurationProvider.cs index a0c1d7b59bd02..9b010dc476267 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniStreamConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/IniStreamConfigurationProvider.cs @@ -23,16 +23,16 @@ public IniStreamConfigurationProvider(IniStreamConfigurationSource source) : bas /// /// The stream of INI data. /// The which was read from the stream. - public static IDictionary Read(Stream stream) + public static IDictionary Read(Stream stream) { - var data = new Dictionary(StringComparer.OrdinalIgnoreCase); + var data = new Dictionary(StringComparer.OrdinalIgnoreCase); using (var reader = new StreamReader(stream)) { string sectionPrefix = string.Empty; while (reader.Peek() != -1) { - string rawLine = reader.ReadLine(); + string rawLine = reader.ReadLine()!; // Since Peak didn't return -1, stream hasn't ended. string line = rawLine.Trim(); // Ignore blank lines @@ -41,7 +41,7 @@ public static IDictionary Read(Stream stream) continue; } // Ignore comments - if (line[0] == ';' || line[0] == '#' || line[0] == '/') + if (line[0] is ';' or '#' or '/') { continue; } @@ -50,9 +50,9 @@ public static IDictionary Read(Stream stream) { // remove the brackets #if NET - sectionPrefix = string.Concat(line.AsSpan(1, line.Length - 2), ConfigurationPath.KeyDelimiter); + sectionPrefix = string.Concat(line.AsSpan(1, line.Length - 2).Trim(), ConfigurationPath.KeyDelimiter); #else - sectionPrefix = line.Substring(1, line.Length - 2) + ConfigurationPath.KeyDelimiter; + sectionPrefix = line.Substring(1, line.Length - 2).Trim() + ConfigurationPath.KeyDelimiter; #endif continue; } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj index 7b0a14abec59c..a212999573c80 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/src/Microsoft.Extensions.Configuration.Ini.csproj @@ -2,6 +2,7 @@ $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) + enable true false diff --git a/src/libraries/Microsoft.Extensions.Configuration.Ini/tests/IniConfigurationTest.cs b/src/libraries/Microsoft.Extensions.Configuration.Ini/tests/IniConfigurationTest.cs index 18e4903c318b5..f7c91fc4c3bfa 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Ini/tests/IniConfigurationTest.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Ini/tests/IniConfigurationTest.cs @@ -160,6 +160,28 @@ public void SupportAndIgnoreComments() Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:Provider")); } + [Fact] + public void ShouldRemoveLeadingAndTrailingWhiteSpacesFromKeyAndValue() + { + var ini = "[section]\n" + + " \t key \t = \t value\t "; + var iniConfigSrc = new IniConfigurationProvider(new IniConfigurationSource()); + iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini)); + + Assert.Equal("value", iniConfigSrc.Get("section:key")); + } + + [Fact] + public void ShouldRemoveLeadingAndTrailingWhiteSpacesFromSectionName() + { + var ini = "[ \t section \t ]\n" + + "key=value"; + var iniConfigSrc = new IniConfigurationProvider(new IniConfigurationSource()); + iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini)); + + Assert.Equal("value", iniConfigSrc.Get("section:key")); + } + [Fact] public void ThrowExceptionWhenFoundInvalidLine() { diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/ref/Microsoft.Extensions.Configuration.Json.cs b/src/libraries/Microsoft.Extensions.Configuration.Json/ref/Microsoft.Extensions.Configuration.Json.cs index b844fec6f2f7a..556870c199dcf 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/ref/Microsoft.Extensions.Configuration.Json.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/ref/Microsoft.Extensions.Configuration.Json.cs @@ -8,8 +8,8 @@ namespace Microsoft.Extensions.Configuration { public static partial class JsonConfigurationExtensions { - public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddJsonFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, Microsoft.Extensions.FileProviders.IFileProvider provider, string path, bool optional, bool reloadOnChange) { throw null; } - public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddJsonFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, System.Action configureSource) { throw null; } + public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddJsonFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, Microsoft.Extensions.FileProviders.IFileProvider? provider, string path, bool optional, bool reloadOnChange) { throw null; } + public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddJsonFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, System.Action? configureSource) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddJsonFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, string path) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddJsonFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, string path, bool optional) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddJsonFile(this Microsoft.Extensions.Configuration.IConfigurationBuilder builder, string path, bool optional, bool reloadOnChange) { throw null; } diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/ref/Microsoft.Extensions.Configuration.Json.csproj b/src/libraries/Microsoft.Extensions.Configuration.Json/ref/Microsoft.Extensions.Configuration.Json.csproj index 195538be004ea..d6c79dcac206b 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/ref/Microsoft.Extensions.Configuration.Json.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/ref/Microsoft.Extensions.Configuration.Json.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) + enable diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs index e5cc31af1289e..bf3a83cbad455 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationExtensions.cs @@ -62,7 +62,7 @@ public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder build /// Whether the file is optional. /// Whether the configuration should be reloaded if the file changes. /// The . - public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) + public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange) { if (builder == null) { @@ -89,7 +89,7 @@ public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder build /// The to add to. /// Configures the source. /// The . - public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, Action configureSource) + public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, Action? configureSource) => builder.Add(configureSource); /// diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationFileParser.cs b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationFileParser.cs index 2104b66ea66c4..077ead2b51108 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationFileParser.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/JsonConfigurationFileParser.cs @@ -13,13 +13,13 @@ internal sealed class JsonConfigurationFileParser { private JsonConfigurationFileParser() { } - private readonly Dictionary _data = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _data = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly Stack _paths = new Stack(); - public static IDictionary Parse(Stream input) + public static IDictionary Parse(Stream input) => new JsonConfigurationFileParser().ParseStream(input); - private IDictionary ParseStream(Stream input) + private IDictionary ParseStream(Stream input) { var jsonDocumentOptions = new JsonDocumentOptions { diff --git a/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj b/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj index ad2b4ea3c1f82..61be4beedfb22 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj +++ b/src/libraries/Microsoft.Extensions.Configuration.Json/src/Microsoft.Extensions.Configuration.Json.csproj @@ -2,6 +2,7 @@ $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum) + enable true true diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs index 6fe4c1a004663..1fb575e0c0c0d 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ConfigurationManager.cs @@ -14,15 +14,20 @@ namespace Microsoft.Extensions.Configuration { /// /// ConfigurationManager is a mutable configuration object. It is both an and an . - /// As sources are added, it updates its current view of configuration. Once Build is called, configuration is frozen. + /// As sources are added, it updates its current view of configuration. /// public sealed class ConfigurationManager : IConfigurationBuilder, IConfigurationRoot, IDisposable { + // Concurrently modifying config sources or properties is not thread-safe. However, it is thread-safe to read config while modifying sources or properties. private readonly ConfigurationSources _sources; private readonly ConfigurationBuilderProperties _properties; - private readonly object _providerLock = new(); - private readonly List _providers = new(); + // ReferenceCountedProviderManager manages copy-on-write references to support concurrently reading config while modifying sources. + // It waits for readers to unreference the providers before disposing them without blocking on any concurrent operations. + private readonly ReferenceCountedProviderManager _providerManager = new(); + + // _changeTokenRegistrations is only modified when config sources are modified. It is not referenced by any read operations. + // Because modify config sources is not thread-safe, modifying _changeTokenRegistrations does not need to be thread-safe either. private readonly List _changeTokenRegistrations = new(); private ConfigurationReloadToken _changeToken = new(); @@ -43,17 +48,13 @@ public string? this[string key] { get { - lock (_providerLock) - { - return ConfigurationRoot.GetConfiguration(_providers, key); - } + using ReferenceCountedProviders reference = _providerManager.GetReference(); + return ConfigurationRoot.GetConfiguration(reference.Providers, key); } set { - lock (_providerLock) - { - ConfigurationRoot.SetConfiguration(_providers, key, value); - } + using ReferenceCountedProviders reference = _providerManager.GetReference(); + ConfigurationRoot.SetConfiguration(reference.Providers, key, value); } } @@ -61,37 +62,22 @@ public string? this[string key] public IConfigurationSection GetSection(string key) => new ConfigurationSection(this, key); /// - public IEnumerable GetChildren() - { - lock (_providerLock) - { - // ToList() to eagerly evaluate inside lock. - return this.GetChildrenImplementation(null).ToList(); - } - } + public IEnumerable GetChildren() => this.GetChildrenImplementation(null); IDictionary IConfigurationBuilder.Properties => _properties; IList IConfigurationBuilder.Sources => _sources; - IEnumerable IConfigurationRoot.Providers - { - get - { - lock (_providerLock) - { - return new List(_providers); - } - } - } + // We cannot track the duration of the reference to the providers if this property is used. + // If a configuration source is removed after this is accessed but before it's completely enumerated, + // this may allow access to a disposed provider. + IEnumerable IConfigurationRoot.Providers => _providerManager.NonReferenceCountedProviders; /// public void Dispose() { - lock (_providerLock) - { - DisposeRegistrationsAndProvidersUnsynchronized(); - } + DisposeRegistrations(); + _providerManager.Dispose(); } IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source) @@ -106,9 +92,9 @@ IConfigurationBuilder IConfigurationBuilder.Add(IConfigurationSource source) void IConfigurationRoot.Reload() { - lock (_providerLock) + using (ReferenceCountedProviders reference = _providerManager.GetReference()) { - foreach (var provider in _providers) + foreach (IConfigurationProvider provider in reference.Providers) { provider.Load(); } @@ -117,6 +103,8 @@ void IConfigurationRoot.Reload() RaiseChanged(); } + internal ReferenceCountedProviders GetProvidersReference() => _providerManager.GetReference(); + private void RaiseChanged() { var previousToken = Interlocked.Exchange(ref _changeToken, new ConfigurationReloadToken()); @@ -126,59 +114,49 @@ private void RaiseChanged() // Don't rebuild and reload all providers in the common case when a source is simply added to the IList. private void AddSource(IConfigurationSource source) { - lock (_providerLock) - { - var provider = source.Build(this); - _providers.Add(provider); + IConfigurationProvider provider = source.Build(this); - provider.Load(); - _changeTokenRegistrations.Add(ChangeToken.OnChange(() => provider.GetReloadToken(), () => RaiseChanged())); - } + provider.Load(); + _changeTokenRegistrations.Add(ChangeToken.OnChange(() => provider.GetReloadToken(), () => RaiseChanged())); + _providerManager.AddProvider(provider); RaiseChanged(); } // Something other than Add was called on IConfigurationBuilder.Sources or IConfigurationBuilder.Properties has changed. private void ReloadSources() { - lock (_providerLock) - { - DisposeRegistrationsAndProvidersUnsynchronized(); + DisposeRegistrations(); - _changeTokenRegistrations.Clear(); - _providers.Clear(); + _changeTokenRegistrations.Clear(); - foreach (var source in _sources) - { - _providers.Add(source.Build(this)); - } + var newProvidersList = new List(); - foreach (var p in _providers) - { - p.Load(); - _changeTokenRegistrations.Add(ChangeToken.OnChange(() => p.GetReloadToken(), () => RaiseChanged())); - } + foreach (IConfigurationSource source in _sources) + { + newProvidersList.Add(source.Build(this)); + } + + foreach (IConfigurationProvider p in newProvidersList) + { + p.Load(); + _changeTokenRegistrations.Add(ChangeToken.OnChange(() => p.GetReloadToken(), () => RaiseChanged())); } + _providerManager.ReplaceProviders(newProvidersList); RaiseChanged(); } - private void DisposeRegistrationsAndProvidersUnsynchronized() + private void DisposeRegistrations() { // dispose change token registrations - foreach (var registration in _changeTokenRegistrations) + foreach (IDisposable registration in _changeTokenRegistrations) { registration.Dispose(); } - - // dispose providers - foreach (var provider in _providers) - { - (provider as IDisposable)?.Dispose(); - } } - private class ConfigurationSources : IList + private sealed class ConfigurationSources : IList { private readonly List _sources = new(); private readonly ConfigurationManager _config; @@ -259,7 +237,7 @@ IEnumerator IEnumerable.GetEnumerator() } } - private class ConfigurationBuilderProperties : IDictionary + private sealed class ConfigurationBuilderProperties : IDictionary { private readonly Dictionary _properties = new(); private readonly ConfigurationManager _config; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/InternalConfigurationRootExtensions.cs b/src/libraries/Microsoft.Extensions.Configuration/src/InternalConfigurationRootExtensions.cs index 7fd17a98acf47..8951697d8d68a 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/InternalConfigurationRootExtensions.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/InternalConfigurationRootExtensions.cs @@ -20,11 +20,24 @@ internal static class InternalConfigurationRootExtensions /// Immediate children sub-sections of section specified by key. internal static IEnumerable GetChildrenImplementation(this IConfigurationRoot root, string? path) { - return root.Providers + using ReferenceCountedProviders? reference = (root as ConfigurationManager)?.GetProvidersReference(); + IEnumerable providers = reference?.Providers ?? root.Providers; + + IEnumerable children = providers .Aggregate(Enumerable.Empty(), (seed, source) => source.GetChildKeys(seed, path)) .Distinct(StringComparer.OrdinalIgnoreCase) .Select(key => root.GetSection(path == null ? key : ConfigurationPath.Combine(path, key))); + + if (reference is null) + { + return children; + } + else + { + // Eagerly evaluate the IEnumerable before releasing the reference so we don't allow iteration over disposed providers. + return children.ToList(); + } } } } diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ReferenceCountedProviders.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ReferenceCountedProviders.cs new file mode 100644 index 0000000000000..2c2e32fc7e47d --- /dev/null +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ReferenceCountedProviders.cs @@ -0,0 +1,93 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +namespace Microsoft.Extensions.Configuration +{ + // ReferenceCountedProviders is used by ConfigurationManager to wait until all readers unreference it before disposing any providers. + internal abstract class ReferenceCountedProviders : IDisposable + { + public static ReferenceCountedProviders Create(List providers) => new ActiveReferenceCountedProviders(providers); + + // If anything references DisposedReferenceCountedProviders, it indicates something is using the ConfigurationManager after it's been disposed. + // We could preemptively throw an ODE from ReferenceCountedProviderManager.GetReference() instead of returning this type, but this might + // break existing apps that are previously able to continue to read configuration after disposing an ConfigurationManager. + public static ReferenceCountedProviders CreateDisposed(List providers) => new DisposedReferenceCountedProviders(providers); + + public abstract List Providers { get; set; } + + // NonReferenceCountedProviders is only used to: + // 1. Support IConfigurationRoot.Providers because we cannot track the lifetime of that reference. + // 2. Construct DisposedReferenceCountedProviders because the providers are disposed anyway and no longer reference counted. + public abstract List NonReferenceCountedProviders { get; } + + public abstract void AddReference(); + // This is Dispose() rather than RemoveReference() so we can conveniently release a reference at the end of a using block. + public abstract void Dispose(); + + private sealed class ActiveReferenceCountedProviders : ReferenceCountedProviders + { + private long _refCount = 1; + // volatile is not strictly necessary because the runtime adds a barrier either way, but volatile indicates that this field has + // unsynchronized readers meaning the all writes initializing the list must be published before updating the _providers reference. + private volatile List _providers; + + public ActiveReferenceCountedProviders(List providers) + { + _providers = providers; + } + + public override List Providers + { + get + { + Debug.Assert(_refCount > 0); + return _providers; + } + set + { + Debug.Assert(_refCount > 0); + _providers = value; + } + } + + public override List NonReferenceCountedProviders => _providers; + + public override void AddReference() + { + // AddReference() is always called with a lock to ensure _refCount hasn't already decremented to zero. + Debug.Assert(_refCount > 0); + Interlocked.Increment(ref _refCount); + } + + public override void Dispose() + { + if (Interlocked.Decrement(ref _refCount) == 0) + { + foreach (IConfigurationProvider provider in _providers) + { + (provider as IDisposable)?.Dispose(); + } + } + } + } + + private sealed class DisposedReferenceCountedProviders : ReferenceCountedProviders + { + public DisposedReferenceCountedProviders(List providers) + { + Providers = providers; + } + + public override List Providers { get; set; } + public override List NonReferenceCountedProviders => Providers; + + public override void AddReference() { } + public override void Dispose() { } + } + } +} diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ReferenceCountedProvidersManager.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ReferenceCountedProvidersManager.cs new file mode 100644 index 0000000000000..210e41f665a47 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ReferenceCountedProvidersManager.cs @@ -0,0 +1,93 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; + +namespace Microsoft.Extensions.Configuration +{ + // ReferenceCountedProviderManager is used by ConfigurationManager to provide copy-on-write references that support concurrently + // reading config while modifying sources. It waits for readers to unreference the providers before disposing them + // without blocking on any concurrent operations. + internal sealed class ReferenceCountedProviderManager : IDisposable + { + private readonly object _replaceProvidersLock = new object(); + private ReferenceCountedProviders _refCountedProviders = ReferenceCountedProviders.Create(new List()); + private bool _disposed; + + // This is only used to support IConfigurationRoot.Providers because we cannot track the lifetime of that reference. + public IEnumerable NonReferenceCountedProviders => _refCountedProviders.NonReferenceCountedProviders; + + public ReferenceCountedProviders GetReference() + { + // Lock to ensure oldRefCountedProviders.Dispose() in ReplaceProviders() or Dispose() doesn't decrement ref count to zero + // before calling _refCountedProviders.AddReference(). + lock (_replaceProvidersLock) + { + if (_disposed) + { + // Return a non-reference-counting ReferenceCountedProviders instance now that the ConfigurationManager is disposed. + // We could preemptively throw an ODE instead, but this might break existing apps that were previously able to + // continue to read configuration after disposing an ConfigurationManager. + return ReferenceCountedProviders.CreateDisposed(_refCountedProviders.NonReferenceCountedProviders); + } + + _refCountedProviders.AddReference(); + return _refCountedProviders; + } + } + + // Providers should never be concurrently modified. Reading during modification is allowed. + public void ReplaceProviders(List providers) + { + ReferenceCountedProviders oldRefCountedProviders = _refCountedProviders; + + lock (_replaceProvidersLock) + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(ConfigurationManager)); + } + + _refCountedProviders = ReferenceCountedProviders.Create(providers); + } + + // Decrement the reference count to the old providers. If they are being concurrently read from + // the actual disposal of the old providers will be delayed until the final reference is released. + // Never dispose ReferenceCountedProviders with a lock because this may call into user code. + oldRefCountedProviders.Dispose(); + } + + public void AddProvider(IConfigurationProvider provider) + { + lock (_replaceProvidersLock) + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(ConfigurationManager)); + } + + // Maintain existing references, but replace list with copy containing new item. + _refCountedProviders.Providers = new List(_refCountedProviders.Providers) + { + provider + }; + } + } + + public void Dispose() + { + ReferenceCountedProviders oldRefCountedProviders = _refCountedProviders; + + // This lock ensures that we cannot reduce the ref count to zero before GetReference() calls AddReference(). + // Once _disposed is set, GetReference() stops reference counting. + lock (_replaceProvidersLock) + { + _disposed = true; + } + + // Never dispose ReferenceCountedProviders with a lock because this may call into user code. + oldRefCountedProviders.Dispose(); + } + } +} diff --git a/src/libraries/Microsoft.Extensions.Configuration/tests/ConfigurationManagerTest.cs b/src/libraries/Microsoft.Extensions.Configuration/tests/ConfigurationManagerTest.cs index 256d15a16c625..1a61a47394f2b 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/tests/ConfigurationManagerTest.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/tests/ConfigurationManagerTest.cs @@ -4,6 +4,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Microsoft.Extensions.Configuration.Memory; using Microsoft.Extensions.Primitives; using Moq; @@ -171,6 +173,91 @@ public void DisposesProvidersOnRemoval() Assert.True(provider5.IsDisposed); } + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] + public async Task ProviderCanBlockLoadWaitingOnConcurrentRead() + { + using var mre = new ManualResetEventSlim(false); + var provider = new BlockLoadOnMREProvider(mre, timeout: TimeSpan.FromSeconds(30)); + + var config = new ConfigurationManager(); + IConfigurationBuilder builder = config; + + // builder.Add(source) will block on provider.Load(). + var loadTask = Task.Run(() => builder.Add(new TestConfigurationSource(provider))); + await provider.LoadStartedTask; + + // Read configuration while provider.Load() is blocked waiting on us. + _ = config["key"]; + + // Unblock provider.Load() + mre.Set(); + + // This will throw if provider.Load() timed out instead of unblocking gracefully after the read. + await loadTask; + } + + public static TheoryData ConcurrentReadActions + { + get + { + return new TheoryData> + { + config => _ = config["key"], + config => config.GetChildren(), + config => config.GetSection("key").GetChildren(), + }; + } + } + + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] + [MemberData(nameof(ConcurrentReadActions))] + public async Task ProviderDisposeDelayedWaitingOnConcurrentRead(Action concurrentReadAction) + { + using var mre = new ManualResetEventSlim(false); + var provider = new BlockReadOnMREProvider(mre, timeout: TimeSpan.FromSeconds(30)); + + var config = new ConfigurationManager(); + IConfigurationBuilder builder = config; + + builder.Add(new TestConfigurationSource(provider)); + + // Reading configuration will block on provider.TryRead() or profvider.GetChildKeys(). + var readTask = Task.Run(() => concurrentReadAction(config)); + await provider.ReadStartedTask; + + // Removing the source normally disposes the provider except when there provider is in use as is the case here. + builder.Sources.Clear(); + + Assert.False(provider.IsDisposed); + + // Unblock TryRead() or GetChildKeys() + mre.Set(); + + // This will throw if TryRead() or GetChildKeys() timed out instead of unblocking gracefully after setting the MRE. + await readTask; + + // The provider should be disposed when the concurrentReadAction releases the last reference to the provider. + Assert.True(provider.IsDisposed); + } + + [Fact] + public void DisposingConfigurationManagerCausesOnlySourceChangesToThrow() + { + var config = new ConfigurationManager + { + ["TestKey"] = "TestValue", + }; + + config.Dispose(); + + Assert.Equal("TestValue", config["TestKey"]); + config["TestKey"] = "TestValue2"; + Assert.Equal("TestValue2", config["TestKey"]); + + Assert.Throws(() => config.AddInMemoryCollection()); + Assert.Throws(() => ((IConfigurationBuilder)config).Sources.Clear()); + } + // Moq heavily utilizes RefEmit, which does not work on most aot workloads [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] public void DisposesChangeTokenRegistrationsOnDispose() @@ -1130,6 +1217,62 @@ public TestConfigurationProvider(string key, string value) => Data.Add(key, value); } + private class BlockLoadOnMREProvider : ConfigurationProvider + { + private readonly ManualResetEventSlim _mre; + private readonly TimeSpan _timeout; + + private readonly TaskCompletionSource _loadStartedTcs = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public BlockLoadOnMREProvider(ManualResetEventSlim mre, TimeSpan timeout) + { + _mre = mre; + _timeout = timeout; + } + + public Task LoadStartedTask => _loadStartedTcs.Task; + + public override void Load() + { + _loadStartedTcs.SetResult(null); + Assert.True(_mre.Wait(_timeout), "BlockLoadOnMREProvider.Load() timed out."); + } + } + + private class BlockReadOnMREProvider : ConfigurationProvider, IDisposable + { + private readonly ManualResetEventSlim _mre; + private readonly TimeSpan _timeout; + + private readonly TaskCompletionSource _readStartedTcs = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public BlockReadOnMREProvider(ManualResetEventSlim mre, TimeSpan timeout) + { + _mre = mre; + _timeout = timeout; + } + + public Task ReadStartedTask => _readStartedTcs.Task; + + public bool IsDisposed { get; set; } + + public override bool TryGet(string key, out string? value) + { + _readStartedTcs.SetResult(null); + Assert.True(_mre.Wait(_timeout), "BlockReadOnMREProvider.TryGet() timed out."); + return base.TryGet(key, out value); + } + + public override IEnumerable GetChildKeys(IEnumerable earlierKeys, string? parentPath) + { + _readStartedTcs.SetResult(null); + Assert.True(_mre.Wait(_timeout), "BlockReadOnMREProvider.GetChildKeys() timed out."); + return base.GetChildKeys(earlierKeys, parentPath); + } + + public void Dispose() => IsDisposed = true; + } + private class DisposableTestConfigurationProvider : ConfigurationProvider, IDisposable { public bool IsDisposed { get; set; } diff --git a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs index 9f0ddf4c21757..312e600b05399 100644 --- a/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs +++ b/src/libraries/Microsoft.Extensions.FileProviders.Physical/src/PhysicalFilesWatcher.cs @@ -439,7 +439,7 @@ private void TryEnableFileSystemWatcher() } } - private static string NormalizePath(string filter) => filter = filter.Replace('\\', '/'); + private static string NormalizePath(string filter) => filter.Replace('\\', '/'); private static bool IsDirectoryPath(string path) { diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs index 5e736c11fb8a7..f7802124ea60e 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs @@ -29,6 +29,7 @@ public abstract class BackgroundService : IHostedService, IDisposable /// /// Triggered when is called. /// A that represents the long running operations. + /// See Worker Services in .NET for implementation guidelines. protected abstract Task ExecuteAsync(CancellationToken stoppingToken); /// diff --git a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/IHost.cs b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/IHost.cs index b0f2d86546d8e..339037f317a5e 100644 --- a/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/IHost.cs +++ b/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/IHost.cs @@ -13,12 +13,13 @@ namespace Microsoft.Extensions.Hosting public interface IHost : IDisposable { /// - /// The programs configured services. + /// Gets the services configured for the program (for example, using ). /// IServiceProvider Services { get; } /// - /// Start the program. + /// Starts the objects configured for the program. + /// The application will run until interrupted or until is called. /// /// Used to abort program start. /// A that will be completed when the starts. diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs b/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs index 3827761382a13..5f0ad5f68d524 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs @@ -121,6 +121,7 @@ public IHostBuilder ConfigureContainer(Action /// An initialized + /// Adds basic services to the host such as application lifetime, host environment, and logging. public IHost Build() { if (_hostBuilt) diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs index b2bee46b3a3d6..cca20cbca1a1e 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandler.cs @@ -90,10 +90,13 @@ public static class EventIds public static readonly EventId ResponseHeader = new EventId(103, "ResponseHeader"); } - private static readonly Action _requestStart = LoggerMessage.Define( + private static readonly LogDefineOptions _skipEnabledCheckLogDefineOptions = new LogDefineOptions() { SkipEnabledCheck = true }; + + private static readonly Action _requestStart = LoggerMessage.Define( LogLevel.Information, EventIds.RequestStart, - "Sending HTTP request {HttpMethod} {Uri}"); + "Sending HTTP request {HttpMethod} {Uri}", + _skipEnabledCheckLogDefineOptions); private static readonly Action _requestEnd = LoggerMessage.Define( LogLevel.Information, @@ -102,7 +105,11 @@ public static class EventIds public static void RequestStart(ILogger logger, HttpRequestMessage request, Func shouldRedactHeaderValue) { - _requestStart(logger, request.Method, request.RequestUri, null); + // We check here to avoid allocating in the GetUriString call unnecessarily + if (logger.IsEnabled(LogLevel.Information)) + { + _requestStart(logger, request.Method, GetUriString(request.RequestUri), null); + } if (logger.IsEnabled(LogLevel.Trace)) { @@ -129,6 +136,13 @@ public static void RequestEnd(ILogger logger, HttpResponseMessage response, Time (state, ex) => state.ToString()); } } + + private static string? GetUriString(Uri? requestUri) + { + return requestUri?.IsAbsoluteUri == true + ? requestUri.AbsoluteUri + : requestUri?.ToString(); + } } } } diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs index 8ac16482c5e1a..92fab8b7d06f3 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingScopeHttpMessageHandler.cs @@ -92,9 +92,9 @@ public static class EventIds public static readonly EventId ResponseHeader = new EventId(103, "RequestPipelineResponseHeader"); } - private static readonly Func _beginRequestPipelineScope = LoggerMessage.DefineScope("HTTP {HttpMethod} {Uri}"); + private static readonly Func _beginRequestPipelineScope = LoggerMessage.DefineScope("HTTP {HttpMethod} {Uri}"); - private static readonly Action _requestPipelineStart = LoggerMessage.Define( + private static readonly Action _requestPipelineStart = LoggerMessage.Define( LogLevel.Information, EventIds.PipelineStart, "Start processing HTTP request {HttpMethod} {Uri}"); @@ -106,12 +106,12 @@ public static class EventIds public static IDisposable BeginRequestPipelineScope(ILogger logger, HttpRequestMessage request) { - return _beginRequestPipelineScope(logger, request.Method, request.RequestUri); + return _beginRequestPipelineScope(logger, request.Method, GetUriString(request.RequestUri)); } public static void RequestPipelineStart(ILogger logger, HttpRequestMessage request, Func shouldRedactHeaderValue) { - _requestPipelineStart(logger, request.Method, request.RequestUri, null); + _requestPipelineStart(logger, request.Method, GetUriString(request.RequestUri), null); if (logger.IsEnabled(LogLevel.Trace)) { @@ -138,6 +138,13 @@ public static void RequestPipelineEnd(ILogger logger, HttpResponseMessage respon (state, ex) => state.ToString()); } } + + private static string? GetUriString(Uri? requestUri) + { + return requestUri?.IsAbsoluteUri == true + ? requestUri.AbsoluteUri + : requestUri?.ToString(); + } } } } diff --git a/src/libraries/Microsoft.Extensions.Http/tests/Microsoft.Extensions.Http.Tests/Logging/LoggingUriOutputTests.cs b/src/libraries/Microsoft.Extensions.Http/tests/Microsoft.Extensions.Http.Tests/Logging/LoggingUriOutputTests.cs new file mode 100644 index 0000000000000..9f5588a3f6105 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.Http/tests/Microsoft.Extensions.Http.Tests/Logging/LoggingUriOutputTests.cs @@ -0,0 +1,103 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Http.Logging; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Testing; +using Xunit; + +namespace Microsoft.Extensions.Http.Tests.Logging +{ + public class LoggingUriOutputTests + { + [Fact] + public async Task LoggingHttpMessageHandler_LogsAbsoluteUri() + { + // Arrange + var sink = new TestSink(); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddLogging(); + serviceCollection.AddSingleton(new TestLoggerFactory(sink, enabled: true)); + + serviceCollection + .AddHttpClient("test") + .ConfigurePrimaryHttpMessageHandler(() => new TestMessageHandler()); + + var services = serviceCollection.BuildServiceProvider(); + + var client = services.GetRequiredService().CreateClient("test"); + + + // Act + var request = new HttpRequestMessage(HttpMethod.Get, "http://api.example.com/search?term=Western%20Australia"); + + await client.SendAsync(request); + + // Assert + var messages = sink.Writes.ToArray(); + + var message = Assert.Single(messages.Where(m => + { + return + m.EventId == LoggingHttpMessageHandler.Log.EventIds.RequestStart && + m.LoggerName == "System.Net.Http.HttpClient.test.ClientHandler"; + })); + + Assert.Equal("Sending HTTP request GET http://api.example.com/search?term=Western%20Australia", message.Message); + } + + [Fact] + public async Task LoggingScopeHttpMessageHandler_LogsAbsoluteUri() + { + // Arrange + var sink = new TestSink(); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddLogging(); + serviceCollection.AddSingleton(new TestLoggerFactory(sink, enabled: true)); + + serviceCollection + .AddHttpClient("test") + .ConfigurePrimaryHttpMessageHandler(() => new TestMessageHandler()); + + var services = serviceCollection.BuildServiceProvider(); + + var client = services.GetRequiredService().CreateClient("test"); + + + // Act + var request = new HttpRequestMessage(HttpMethod.Get, "http://api.example.com/search?term=Western%20Australia"); + + await client.SendAsync(request); + + // Assert + var messages = sink.Writes.ToArray(); + + var message = Assert.Single(messages.Where(m => + { + return + m.EventId == LoggingScopeHttpMessageHandler.Log.EventIds.PipelineStart && + m.LoggerName == "System.Net.Http.HttpClient.test.LogicalHandler"; + })); + + Assert.Equal("Start processing HTTP request GET http://api.example.com/search?term=Western%20Australia", message.Message); + Assert.Equal("HTTP GET http://api.example.com/search?term=Western%20Australia", message.Scope.ToString()); + } + + private class TestMessageHandler : HttpClientHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var response = new HttpResponseMessage(); + + return Task.FromResult(response); + } + } + } +} diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/gen/LoggerMessageGenerator.Emitter.cs b/src/libraries/Microsoft.Extensions.Logging.Abstractions/gen/LoggerMessageGenerator.Emitter.cs index 53dd062b5d4b4..69f87fdcd48f6 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/gen/LoggerMessageGenerator.Emitter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/gen/LoggerMessageGenerator.Emitter.cs @@ -16,10 +16,18 @@ internal class Emitter private const int MaxLoggerMessageDefineArguments = 6; private const int DefaultStringBuilderCapacity = 1024; + private static readonly string s_generatedTypeSummary = + " " + + "This API supports the logging infrastructure and is not intended to be used directly from your code. " + + "It is subject to change in the future. " + + ""; private static readonly string s_generatedCodeAttribute = $"global::System.CodeDom.Compiler.GeneratedCodeAttribute(" + $"\"{typeof(Emitter).Assembly.GetName().Name}\", " + $"\"{typeof(Emitter).Assembly.GetName().Version}\")"; + private static readonly string s_editorBrowsableAttribute = + "global::System.ComponentModel.EditorBrowsableAttribute(" + + "global::System.ComponentModel.EditorBrowsableState.Never)"; private readonly StringBuilder _builder = new StringBuilder(DefaultStringBuilderCapacity); private bool _needEnumerationHelper; @@ -127,7 +135,9 @@ namespace {lc.Namespace} private void GenStruct(LoggerMethod lm, string nestedIndentation) { _builder.AppendLine($@" + {nestedIndentation}/// {s_generatedTypeSummary} {nestedIndentation}[{s_generatedCodeAttribute}] + {nestedIndentation}[{s_editorBrowsableAttribute}] {nestedIndentation}private readonly struct __{lm.Name}Struct : global::System.Collections.Generic.IReadOnlyList> {nestedIndentation}{{"); GenFields(lm, nestedIndentation); @@ -156,7 +166,7 @@ private void GenStruct(LoggerMethod lm, string nestedIndentation) {nestedIndentation}}} "); _builder.Append($@" - {nestedIndentation}public static string Format(__{lm.Name}Struct state, global::System.Exception? ex) => state.ToString(); + {nestedIndentation}public static readonly global::System.Func<__{lm.Name}Struct, global::System.Exception?, string> Format = (state, ex) => state.ToString(); {nestedIndentation}public int Count => {lm.TemplateParameters.Count + 1}; @@ -489,7 +499,9 @@ private void GenEnumerationHelper() if (_needEnumerationHelper) { _builder.Append($@" +/// {s_generatedTypeSummary} [{s_generatedCodeAttribute}] +[{s_editorBrowsableAttribute}] internal static class __LoggerMessageGenerator {{ public static string Enumerate(global::System.Collections.IEnumerable? enumerable) diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/.editorconfig b/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/.editorconfig new file mode 100644 index 0000000000000..e9356fee5e6d2 --- /dev/null +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/.editorconfig @@ -0,0 +1,4 @@ +# editorconfig.org + +[*.generated.txt] +insert_final_newline = false diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithDefaultValues.generated.txt b/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithDefaultValues.generated.txt index f4747ef679f83..5292db82ac8c8 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithDefaultValues.generated.txt +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithDefaultValues.generated.txt @@ -5,7 +5,9 @@ namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses { partial class TestWithDefaultValues { + /// This API supports the logging infrastructure and is not intended to be used directly from your code. It is subject to change in the future. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Logging.Generators", "%VERSION%")] + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private readonly struct __M0Struct : global::System.Collections.Generic.IReadOnlyList> { @@ -15,7 +17,7 @@ namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses return $""; } - public static string Format(__M0Struct state, global::System.Exception? ex) => state.ToString(); + public static readonly global::System.Func<__M0Struct, global::System.Exception?, string> Format = (state, ex) => state.ToString(); public int Count => 1; diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithDynamicLogLevel.generated.txt b/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithDynamicLogLevel.generated.txt index 1d1af4719fe40..6326923544aa9 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithDynamicLogLevel.generated.txt +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithDynamicLogLevel.generated.txt @@ -5,7 +5,9 @@ namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses { partial class TestWithDynamicLogLevel { + /// This API supports the logging infrastructure and is not intended to be used directly from your code. It is subject to change in the future. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Logging.Generators", "%VERSION%")] + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private readonly struct __M9Struct : global::System.Collections.Generic.IReadOnlyList> { @@ -15,7 +17,7 @@ namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses return $"M9"; } - public static string Format(__M9Struct state, global::System.Exception? ex) => state.ToString(); + public static readonly global::System.Func<__M9Struct, global::System.Exception?, string> Format = (state, ex) => state.ToString(); public int Count => 1; diff --git a/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithMoreThan6Params.generated.txt b/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithMoreThan6Params.generated.txt index 3387ec2da1a32..84611c6766f72 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithMoreThan6Params.generated.txt +++ b/src/libraries/Microsoft.Extensions.Logging.Abstractions/tests/Microsoft.Extensions.Logging.Generators.Tests/Baselines/TestWithMoreThan6Params.generated.txt @@ -5,7 +5,9 @@ namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses { partial class TestWithMoreThan6Params { + /// This API supports the logging infrastructure and is not intended to be used directly from your code. It is subject to change in the future. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Logging.Generators", "%VERSION%")] + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] private readonly struct __Method9Struct : global::System.Collections.Generic.IReadOnlyList> { private readonly global::System.Int32 _p1; @@ -41,7 +43,7 @@ namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses return $"M9 {p1} {p2} {p3} {p4} {p5} {p6} {p7}"; } - public static string Format(__Method9Struct state, global::System.Exception? ex) => state.ToString(); + public static readonly global::System.Func<__Method9Struct, global::System.Exception?, string> Format = (state, ex) => state.ToString(); public int Count => 8; @@ -88,7 +90,9 @@ namespace Microsoft.Extensions.Logging.Generators.Tests.TestClasses } } } +/// This API supports the logging infrastructure and is not intended to be used directly from your code. It is subject to change in the future. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Extensions.Logging.Generators", "%VERSION%")] +[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never)] internal static class __LoggerMessageGenerator { public static string Enumerate(global::System.Collections.IEnumerable? enumerable) diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/AssemblyResolver.cs b/src/libraries/Microsoft.NETCore.Platforms/src/AssemblyResolver.cs index 9427028aa5fe3..81cbce457a734 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/AssemblyResolver.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/src/AssemblyResolver.cs @@ -36,9 +36,9 @@ private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEven AssemblyName referenceName = new AssemblyName(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); string fileName = referenceName.Name + ".dll"; - string assemblyPath = null; - string probingPath = null; - Assembly assm = null; + string assemblyPath; + string probingPath; + Assembly assm; // look next to requesting assembly assemblyPath = args.RequestingAssembly?.Location; diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/Extensions.cs b/src/libraries/Microsoft.NETCore.Platforms/src/Extensions.cs index 128b56082e1fe..2456407d682e7 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/Extensions.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/src/Extensions.cs @@ -17,7 +17,7 @@ public static string GetString(this ITaskItem taskItem, string metadataName) public static bool GetBoolean(this ITaskItem taskItem, string metadataName, bool defaultValue = false) { - bool result = false; + bool result; var metadataValue = taskItem.GetMetadata(metadataName); if (!bool.TryParse(metadataValue, out result)) { diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs b/src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs index 1421200ead56a..f60a4f26ff83c 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs @@ -405,8 +405,6 @@ private static void WriteRuntimeGraph(RuntimeGraph graph, string dependencyGraph doc.Root.Add(nodesElement); doc.Root.Add(linksElement); - var nodeIds = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var runtimeDescription in graph.Runtimes.Values) { nodesElement.Add(new XElement(s_dgmlns + "Node", diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/RID.cs b/src/libraries/Microsoft.NETCore.Platforms/src/RID.cs index 6f08d1a510e56..6457fd29cadf0 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/RID.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/src/RID.cs @@ -62,7 +62,7 @@ public static RID Parse(string runtimeIdentifier) bool omitVersionDelimiter = true; RIDPart parseState = RIDPart.Base; - int partStart = 0, partLength = 0; + int partStart = 0, partLength; // qualifier is indistinguishable from arch so we cannot distinguish it for parsing purposes Debug.Assert(ArchitectureDelimiter == QualifierDelimiter); diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/runtime.compatibility.json b/src/libraries/Microsoft.NETCore.Platforms/src/runtime.compatibility.json index cbc3d322a87a9..25a7780058844 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/runtime.compatibility.json +++ b/src/libraries/Microsoft.NETCore.Platforms/src/runtime.compatibility.json @@ -4328,6 +4328,26 @@ "any", "base" ], + "manjaro": [ + "manjaro", + "arch", + "linux", + "unix", + "any", + "base" + ], + "manjaro-x64": [ + "manjaro-x64", + "manjaro", + "arch-x64", + "arch", + "linux-x64", + "linux", + "unix-x64", + "unix", + "any", + "base" + ], "ol": [ "ol", "rhel", diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json b/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json index b2070efde5b7c..f8c398707e0bb 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json +++ b/src/libraries/Microsoft.NETCore.Platforms/src/runtime.json @@ -1758,6 +1758,17 @@ "maccatalyst.14-x64" ] }, + "manjaro": { + "#import": [ + "arch" + ] + }, + "manjaro-x64": { + "#import": [ + "manjaro", + "arch-x64" + ] + }, "ol": { "#import": [ "rhel" diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/runtimeGroups.props b/src/libraries/Microsoft.NETCore.Platforms/src/runtimeGroups.props index b66931b24edf8..d1613c4345b31 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/runtimeGroups.props +++ b/src/libraries/Microsoft.NETCore.Platforms/src/runtimeGroups.props @@ -31,6 +31,11 @@ x64 + + arch + x64 + + any wasm diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs index 7e9998e9516cf..20dcbb887140b 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs @@ -588,7 +588,7 @@ private unsafe string[] GetValueNamesCore(int values) case Interop.Advapi32.RegistryValues.REG_BINARY: { byte[] blob = new byte[datasize]; - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); data = blob; } break; @@ -602,7 +602,7 @@ private unsafe string[] GetValueNamesCore(int values) long blob = 0; Debug.Assert(datasize == 8, "datasize==8"); // Here, datasize must be 8 when calling this - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); data = blob; } @@ -617,7 +617,7 @@ private unsafe string[] GetValueNamesCore(int values) int blob = 0; Debug.Assert(datasize == 4, "datasize==4"); // Here, datasize must be four when calling this - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); data = blob; } @@ -639,7 +639,7 @@ private unsafe string[] GetValueNamesCore(int values) } char[] blob = new char[datasize / 2]; - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { data = new string(blob, 0, blob.Length - 1); @@ -669,7 +669,7 @@ private unsafe string[] GetValueNamesCore(int values) } char[] blob = new char[datasize / 2]; - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) { diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs index ea5a83315216d..c82feafee9f0c 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs @@ -728,16 +728,16 @@ private static void ValidateKeyName(string name) throw new ArgumentNullException(nameof(name)); } - int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase); + int nextSlash = name.IndexOf('\\'); int current = 0; - while (nextSlash != -1) + while (nextSlash >= 0) { if ((nextSlash - current) > MaxKeyLength) { throw new ArgumentException(SR.Arg_RegKeyStrLenBug, nameof(name)); } current = nextSlash + 1; - nextSlash = name.IndexOf("\\", current, StringComparison.OrdinalIgnoreCase); + nextSlash = name.IndexOf('\\', current); } if ((name.Length - current) > MaxKeyLength) diff --git a/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs b/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs index 2192c517f81ba..0f659249417e5 100644 --- a/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs +++ b/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs @@ -905,7 +905,7 @@ private void OnSessionEnded(IntPtr wParam, IntPtr lParam) /// private int OnSessionEnding(IntPtr lParam) { - int endOk = 1; + int endOk; SessionEndReasons reason = SessionEndReasons.SystemShutdown; diff --git a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs index 5d126cfc9c715..e62a31e4d28c6 100644 --- a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs +++ b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs @@ -444,7 +444,7 @@ private bool ShortNameArgumentMatch(string arg, string shortName) private void ImportType(Type type, string defaultNamespace, List mappings, List importedTypes, bool verbose, XmlReflectionImporter importer, bool parsableerrors) { - XmlTypeMapping xmlTypeMapping = null; + XmlTypeMapping xmlTypeMapping; var localImporter = new XmlReflectionImporter(defaultNamespace); try { @@ -475,7 +475,7 @@ private void ImportType(Type type, string defaultNamespace, List map private static Assembly LoadAssembly(string assemblyName, bool throwOnFail) { - Assembly assembly = null; + Assembly assembly; string path = Path.IsPathRooted(assemblyName) ? assemblyName : Path.GetFullPath(assemblyName); assembly = Assembly.LoadFile(path); if (assembly == null) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs index cbd5b6e30c107..9e24a113117c8 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs @@ -253,7 +253,6 @@ protected virtual CompilerResults FromSourceBatch(CompilerParameters options, st var filenames = new string[sources.Length]; - CompilerResults results = null; for (int i = 0; i < sources.Length; i++) { string name = options.TempFiles.AddExtension(i + FileExtension); @@ -265,7 +264,7 @@ protected virtual CompilerResults FromSourceBatch(CompilerParameters options, st } filenames[i] = name; } - return results = FromFileBatch(options, filenames); + return FromFileBatch(options, filenames); } protected static string JoinStringArray(string[] sa, string separator) diff --git a/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs b/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs index 2899e28bdb2b7..58473bdcd9225 100644 --- a/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs +++ b/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs @@ -75,7 +75,7 @@ private static bool Contains(string[] array, string value, bool ignoreCase) // Do a binary search on the character array at the specific position and constrict the ranges appropriately. private static bool FindCharacter(string[] array, char value, int pos, ref int min, ref int max) { - int index = min; + int index; while (min < max) { index = (min + max) / 2; diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs index f08db43239b18..0fb3c5dba3cc3 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableDictionary_2.cs @@ -876,8 +876,7 @@ private static bool ContainsKey(TKey key, MutationInput origin) HashBucket bucket; if (origin.Root.TryGetValue(hashCode, out bucket)) { - TValue value; - return bucket.TryGetValue(key, origin.Comparers, out value!); + return bucket.TryGetValue(key, origin.Comparers, out _); } return false; @@ -1000,15 +999,13 @@ private static MutationResult Remove(TKey key, MutationInput origin) /// private static SortedInt32KeyNode UpdateRoot(SortedInt32KeyNode root, int hashCode, HashBucket newBucket, IEqualityComparer hashBucketComparer) { - bool mutated; if (newBucket.IsEmpty) { - return root.Remove(hashCode, out mutated); + return root.Remove(hashCode, out _); } else { - bool replacedExistingValue; - return root.SetItem(hashCode, newBucket, hashBucketComparer, out replacedExistingValue, out mutated); + return root.SetItem(hashCode, newBucket, hashBucketComparer, out _, out _); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs index 93efe0f90f172..90ac49138da80 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableExtensions.Minimal.cs @@ -103,7 +103,7 @@ internal static bool TryCopyTo(this IEnumerable sequence, T[] array, int a Debug.Assert(arrayIndex >= 0 && arrayIndex <= array.Length); // IList is the GCD of what the following types implement. - if (sequence is IList listInterface) + if (sequence is IList) { if (sequence is List list) { diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs index bfcae53cf8083..c29ccc50cb47d 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableHashSet_1.cs @@ -747,14 +747,13 @@ private static bool SetEquals(IEnumerable other, MutationInput origin) /// private static SortedInt32KeyNode UpdateRoot(SortedInt32KeyNode root, int hashCode, IEqualityComparer hashBucketEqualityComparer, HashBucket newBucket) { - bool mutated; if (newBucket.IsEmpty) { - return root.Remove(hashCode, out mutated); + return root.Remove(hashCode, out _); } else { - return root.SetItem(hashCode, newBucket, hashBucketEqualityComparer, out bool replacedExistingValue, out mutated); + return root.SetItem(hashCode, newBucket, hashBucketEqualityComparer, out _, out _); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs index 78480e7d044f2..061e5cd06fbdb 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Node.cs @@ -384,7 +384,7 @@ internal Node RemoveAt(int index) Requires.Range(index >= 0 && index < this.Count, nameof(index)); Debug.Assert(_left != null && _right != null); - Node result = this; + Node result; if (index == _left._count) { // We have a match. If this is a leaf, just remove it @@ -484,7 +484,7 @@ internal Node ReplaceAt(int index, T value) Requires.Range(index >= 0 && index < this.Count, nameof(index)); Debug.Assert(!this.IsEmpty); - Node result = this; + Node result; if (index == _left!._count) { // We have a match. diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Node.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Node.cs index 26daa6ef73ffd..06d52aa52f32b 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Node.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Node.cs @@ -290,8 +290,7 @@ internal Node Add(TKey key, TValue value, IComparer keyComparer, IEquality Requires.NotNull(keyComparer, nameof(keyComparer)); Requires.NotNull(valueComparer, nameof(valueComparer)); - bool dummy; - return this.SetOrAdd(key, value, keyComparer, valueComparer, false, out dummy, out mutated); + return this.SetOrAdd(key, value, keyComparer, valueComparer, false, out _, out mutated); } /// @@ -761,8 +760,7 @@ private Node RemoveRecursive(TKey key, IComparer keyComparer, out bool mut successor = successor._left; } - bool dummyMutated; - var newRight = _right.Remove(successor._key, keyComparer, out dummyMutated); + var newRight = _right.Remove(successor._key, keyComparer, out _); result = successor.Mutate(left: _left, right: newRight); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs index c720eb275e538..2648014f16236 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.cs @@ -253,8 +253,7 @@ public Builder ToBuilder() public ImmutableSortedDictionary Add(TKey key, TValue value) { Requires.NotNullAllowStructs(key, nameof(key)); - bool mutated; - var result = _root.Add(key, value, _keyComparer, _valueComparer, out mutated); + var result = _root.Add(key, value, _keyComparer, _valueComparer, out _); return this.Wrap(result, _count + 1); } @@ -264,8 +263,8 @@ public ImmutableSortedDictionary Add(TKey key, TValue value) public ImmutableSortedDictionary SetItem(TKey key, TValue value) { Requires.NotNullAllowStructs(key, nameof(key)); - bool replacedExistingValue, mutated; - var result = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated); + bool replacedExistingValue; + var result = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out _); return this.Wrap(result, replacedExistingValue ? _count : _count + 1); } @@ -297,8 +296,7 @@ public ImmutableSortedDictionary AddRange(IEnumerable Remove(TKey value) { Requires.NotNullAllowStructs(value, nameof(value)); - bool mutated; - var result = _root.Remove(value, _keyComparer, out mutated); + var result = _root.Remove(value, _keyComparer, out _); return this.Wrap(result, _count - 1); } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs index 4290f5c2ddeed..7b868bbabdef3 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs @@ -226,8 +226,7 @@ public void ExceptWith(IEnumerable other) foreach (T item in other) { - bool mutated; - this.Root = this.Root.Remove(item, _comparer, out mutated); + this.Root = this.Root.Remove(item, _comparer, out _); } } @@ -331,8 +330,7 @@ public void UnionWith(IEnumerable other) foreach (T item in other) { - bool mutated; - this.Root = this.Root.Add(item, _comparer, out mutated); + this.Root = this.Root.Add(item, _comparer, out _); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Node.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Node.cs index c1c53978e4b8c..e72c7cd019d45 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Node.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Node.cs @@ -458,8 +458,7 @@ internal Node Remove(T key, IComparer comparer, out bool mutated) successor = successor._left; } - bool dummyMutated; - var newRight = _right.Remove(successor._key, comparer, out dummyMutated); + var newRight = _right.Remove(successor._key, comparer, out _); result = successor.Mutate(left: _left, right: newRight); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs index c0e69a79ec782..8e635472f43d4 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.cs @@ -189,8 +189,7 @@ public Builder ToBuilder() /// public ImmutableSortedSet Add(T value) { - bool mutated; - return this.Wrap(_root.Add(value, _comparer, out mutated)); + return this.Wrap(_root.Add(value, _comparer, out _)); } /// @@ -198,8 +197,7 @@ public ImmutableSortedSet Add(T value) /// public ImmutableSortedSet Remove(T value) { - bool mutated; - return this.Wrap(_root.Remove(value, _comparer, out mutated)); + return this.Wrap(_root.Remove(value, _comparer, out _)); } /// diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.cs index 25cc0638f62f6..4231e04e78dee 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.cs @@ -518,8 +518,7 @@ private SortedInt32KeyNode RemoveRecursive(int key, out bool mutated) successor = successor._left; } - bool dummyMutated; - var newRight = _right.Remove(successor._key, out dummyMutated); + var newRight = _right.Remove(successor._key, out _); result = successor.Mutate(left: _left, right: newRight); } } diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs index 6829f94dec62e..a0de9bd1dc8f0 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/SortedSet.cs @@ -466,7 +466,6 @@ internal virtual bool DoRemove(T item) { parentOfMatch = newGrandParent; } - grandParent = newGrandParent; } } } @@ -823,7 +822,7 @@ internal static bool SortedSetEquals(SortedSet? set1, SortedSet? set2, ICo return set1.Count == set2.Count && set1.SetEquals(set2); } - bool found = false; + bool found; foreach (T item1 in set1) { found = false; @@ -1923,7 +1922,7 @@ private void Initialize() { _current = null; Node? node = _tree.root; - Node? next = null, other = null; + Node? next, other; while (node != null) { next = (_reverse ? node.Right : node.Left); @@ -1962,7 +1961,7 @@ public bool MoveNext() _current = _stack.Pop(); Node? node = (_reverse ? _current.Left : _current.Right); - Node? next = null, other = null; + Node? next, other; while (node != null) { next = (_reverse ? node.Right : node.Left); diff --git a/src/libraries/System.Collections/tests/Generic/Comparers/Comparer.Tests.cs b/src/libraries/System.Collections/tests/Generic/Comparers/Comparer.Tests.cs index bcc8df1755944..4b95f488db1c9 100644 --- a/src/libraries/System.Collections/tests/Generic/Comparers/Comparer.Tests.cs +++ b/src/libraries/System.Collections/tests/Generic/Comparers/Comparer.Tests.cs @@ -235,7 +235,7 @@ public void ComparerDefaultShouldAttemptToUseTheGenericIComparableInterfaceFirst [Theory] [MemberData(nameof(NullableOfInt32ComparisonsData))] [MemberData(nameof(NullableOfInt32EnumComparisonsData))] - [ActiveIssue("https://github.com/dotnet/runtime/issues/58933", TestPlatforms.iOS | TestPlatforms.tvOS)] + [ActiveIssue("https://github.com/dotnet/runtime/issues/58933", TestPlatforms.iOS | TestPlatforms.tvOS)] public void NullableComparisons(T leftValue, bool leftHasValue, T rightValue, bool rightHasValue, int expected) where T : struct { // Comparer is specialized (for perf reasons) when T : U? where U : IComparable diff --git a/src/libraries/System.Collections/tests/System.Collections.Tests.csproj b/src/libraries/System.Collections/tests/System.Collections.Tests.csproj index 66f5dee8d5ba6..d681aafe746bd 100644 --- a/src/libraries/System.Collections/tests/System.Collections.Tests.csproj +++ b/src/libraries/System.Collections/tests/System.Collections.Tests.csproj @@ -4,6 +4,9 @@ true true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs index f7a26800f39fc..650a114e5af50 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs @@ -106,8 +106,7 @@ internal bool IsPropertyContext(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); - PropertyStoreItem? item; - return typeItem.TryGetPropertyStoreItem(validationContext.MemberName!, out item); + return typeItem.TryGetPropertyStoreItem(validationContext.MemberName!, out _); } /// diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs index c7296f9543e59..2d9b046570ecb 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilder.cs @@ -219,7 +219,7 @@ private static bool MemberHasExportMetadata(MemberInfo member) { foreach (Attribute attr in member.GetCustomAttributes(typeof(Attribute), false)) { - if (attr is ExportMetadataAttribute provider) + if (attr is ExportMetadataAttribute) { return true; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs index 5f49441b566af..8c81e19816946 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/CatalogExportProvider.ScopeFactoryExport.cs @@ -78,7 +78,7 @@ public override ExportDefinition Definition public void Dispose() { CompositionContainer? childContainer = null; - Export? export = null; + Export? export; if (_export != null) { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs index 6ee624abab6ec..e89a4e9eac7a3 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Hosting/DirectoryCatalog.cs @@ -671,7 +671,7 @@ public override string ToString() private AssemblyCatalog? CreateAssemblyCatalogGuarded(string assemblyFilePath) { - Exception? exception = null; + Exception? exception; try { diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs index 3154a585f0db9..2b0ce5d8e7182 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/Primitives/PrimitivesServices.cs @@ -53,7 +53,7 @@ internal static bool IsImportDependentOnPart(this ImportDefinition import, Compo import = import.GetProductImportDefinition(); if (expandGenerics) { - return part.TryGetExports(import, out Tuple? singleMatch, out IEnumerable>? multipleMatches); + return part.TryGetExports(import, out _, out _); } else { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs index fdfc8a3c3eea6..945a723d1b6e7 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs @@ -94,7 +94,7 @@ public virtual void ApplyResources(object value, string objectName, CultureInfo? if (_resourceSets == null) { _resourceSets = new Hashtable(); - resources = FillResources(culture, out ResourceSet? dummy); + resources = FillResources(culture, out _); _resourceSets[culture] = resources; } else @@ -102,7 +102,7 @@ public virtual void ApplyResources(object value, string objectName, CultureInfo? resources = (SortedList?)_resourceSets[culture]; if (resources == null || (resources.Comparer.Equals(StringComparer.OrdinalIgnoreCase) != IgnoreCase)) { - resources = FillResources(culture, out ResourceSet? dummy); + resources = FillResources(culture, out _); _resourceSets[culture] = resources; } } @@ -165,7 +165,7 @@ public virtual void ApplyResources(object value, string objectName, CultureInfo? } else { - PropertyInfo? prop = null; + PropertyInfo? prop; try { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs index 37d2a6f635c0f..5aa11c3004c5f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/DateTimeOffsetConverter.cs @@ -94,7 +94,7 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina culture = CultureInfo.CurrentCulture; } - DateTimeFormatInfo? formatInfo = null; + DateTimeFormatInfo? formatInfo; formatInfo = (DateTimeFormatInfo?)culture.GetFormat(typeof(DateTimeFormatInfo)); string format; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/PropertyTabAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/PropertyTabAttribute.cs index 92ee6a87a46d4..c4dc526139e4c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/PropertyTabAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/PropertyTabAttribute.cs @@ -104,7 +104,7 @@ private void InitializeTabClasses() for (int i = 0; i < _tabClassNames.Length; i++) { int commaIndex = _tabClassNames[i].IndexOf(','); - string? className = null; + string? className; string? assemblyName = null; if (commaIndex != -1) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs index 31556e2ce55a5..54beae053cebd 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/LicenseManager.cs @@ -207,11 +207,7 @@ public static bool IsLicensed(Type type) { Debug.Assert(type != null, "IsValid Type cannot ever be null"); bool value = ValidateInternal(type, null, false, out License? license); - if (license != null) - { - license.Dispose(); - license = null; - } + license?.Dispose(); return value; } @@ -222,11 +218,7 @@ public static bool IsValid(Type type) { Debug.Assert(type != null, "IsValid Type cannot ever be null"); bool value = ValidateInternal(type, null, false, out License? license); - if (license != null) - { - license.Dispose(); - license = null; - } + license?.Dispose(); return value; } @@ -273,7 +265,7 @@ private static bool ValidateInternal(Type type, object? instance, bool allowExce instance, allowExceptions, out license, - out string? licenseKey); + out _); } @@ -329,10 +321,11 @@ private static bool ValidateInternalRecursive(LicenseContext context, Type type, if (license != null) { license.Dispose(); +#pragma warning disable IDE0059 // ValidateInternalRecursive does not null licence all the time (https://github.com/dotnet/roslyn/issues/42761) license = null; +#pragma warning restore IDE0059 } - string? temp; - isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out temp); + isValid = ValidateInternalRecursive(context, baseType, null, allowExceptions, out license, out _); if (license != null) { license.Dispose(); @@ -355,11 +348,7 @@ public static void Validate(Type type) throw new LicenseException(type); } - if (lic != null) - { - lic.Dispose(); - lic = null; - } + lic?.Dispose(); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs index 77a965c66482b..16ebdaf6ab300 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs @@ -826,9 +826,7 @@ public char this[int index] /// public bool Add(char input) { - int dummyVar; - MaskedTextResultHint dummyVar2; - return Add(input, out dummyVar, out dummyVar2); + return Add(input, out _, out _); } /// @@ -876,9 +874,7 @@ public bool Add(char input, out int testPosition, out MaskedTextResultHint resul /// public bool Add(string input) { - int dummyVar; - MaskedTextResultHint dummyVar2; - return Add(input, out dummyVar, out dummyVar2); + return Add(input, out _, out _); } /// @@ -913,8 +909,7 @@ public bool Add(string input, out int testPosition, out MaskedTextResultHint res /// public void Clear() { - MaskedTextResultHint dummyHint; - Clear(out dummyHint); + Clear(out _); } /// @@ -1255,9 +1250,7 @@ public bool InsertAt(char input, int position, out int testPosition, out MaskedT /// public bool InsertAt(string input, int position) { - int dummyVar; - MaskedTextResultHint dummyVar2; - return InsertAt(input, position, out dummyVar, out dummyVar2); + return InsertAt(input, position, out _, out _); } /// @@ -1516,9 +1509,7 @@ public static bool IsValidPasswordChar(char c) /// public bool Remove() { - int dummyVar; - MaskedTextResultHint dummyVar2; - return Remove(out dummyVar, out dummyVar2); + return Remove(out _, out _); } /// @@ -1564,9 +1555,7 @@ public bool RemoveAt(int position) /// public bool RemoveAt(int startPosition, int endPosition) { - int dummyVar; - MaskedTextResultHint dummyVar2; - return RemoveAt(startPosition, endPosition, out dummyVar, out dummyVar2); + return RemoveAt(startPosition, endPosition, out _, out _); } /// @@ -1730,9 +1719,7 @@ private bool RemoveAtInt(int startPosition, int endPosition, out int testPositio /// public bool Replace(char input, int position) { - int dummyVar; - MaskedTextResultHint dummyVar2; - return Replace(input, position, out dummyVar, out dummyVar2); + return Replace(input, position, out _, out _); } /// @@ -1823,9 +1810,7 @@ public bool Replace(char input, int startPosition, int endPosition, out int test /// public bool Replace(string input, int position) { - int dummyVar; - MaskedTextResultHint dummyVar2; - return Replace(input, position, out dummyVar, out dummyVar2); + return Replace(input, position, out _, out _); } /// @@ -2051,10 +2036,7 @@ private void ResetString(int startPosition, int endPosition) /// public bool Set(string input) { - int dummyVar; - MaskedTextResultHint dummyVar2; - - return Set(input, out dummyVar, out dummyVar2); + return Set(input, out _, out _); } /// @@ -2072,7 +2054,6 @@ public bool Set(string input, out int testPosition, out MaskedTextResultHint res throw new ArgumentNullException(nameof(input)); } - resultHint = MaskedTextResultHint.Unknown; testPosition = 0; if (input.Length == 0) // Clearing the input text. @@ -2511,7 +2492,7 @@ private bool TestString(string input, int position, out int testPosition, out Ma // If any char is actually accepted, then the hint is success, otherwise whatever the last character result is. // Need a temp variable for - MaskedTextResultHint tempHint = resultHint; + MaskedTextResultHint tempHint; foreach (char ch in input) { @@ -2753,8 +2734,6 @@ public string ToString(bool ignorePasswordChar, bool includePrompt, bool include /// public bool VerifyChar(char input, int position, out MaskedTextResultHint hint) { - hint = MaskedTextResultHint.NoEffect; - if (position < 0 || position >= _testString.Length) { hint = MaskedTextResultHint.PositionOutOfRange; @@ -2782,9 +2761,7 @@ public bool VerifyEscapeChar(char input, int position) /// public bool VerifyString(string input) { - int dummyVar; - MaskedTextResultHint dummyVar2; - return VerifyString(input, out dummyVar, out dummyVar2); + return VerifyString(input, out _, out _); } /// diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs index 615f8d70157b5..3d419bf44a7ac 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MemberDescriptor.cs @@ -358,7 +358,7 @@ private void FilterAttributesIfNeeded() for (int i = 0; i < list.Count;) { - int savedIndex = -1; + int savedIndex; object? typeId = list[i]?.TypeId; if (typeId == null) { @@ -417,7 +417,7 @@ private void FilterAttributesIfNeeded() throw new ArgumentNullException(nameof(componentClass)); } - MethodInfo? result = null; + MethodInfo? result; if (publicOnly) { result = componentClass.GetMethod(name, args); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs index 096fef344ad07..ec1987b77bb45 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs @@ -791,7 +791,7 @@ protected override void FillAttributes(IList attributes) while (currentReflectType != null && currentReflectType != typeof(object)) { - MemberInfo? memberInfo = null; + MemberInfo? memberInfo; BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly; // Fill in our member info so we can get at the custom attributes. diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs index dacc0ea3aba45..2e694467f8465 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs @@ -262,7 +262,7 @@ internal static void AddEditorTable(Type editorBaseType, Hashtable table) { Debug.Assert(objectType != null, "Should have arg-checked before coming in here"); - object? obj = null; + object? obj; if (argTypes != null) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs index f1b36ef296ab9..ded2068999cc5 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs @@ -511,7 +511,7 @@ public static PropertyDescriptor CreateProperty( oldPropertyDescriptor.Attributes[ typeof(ExtenderProvidedPropertyAttribute)]!; - if (attr.ExtenderProperty is ReflectPropertyDescriptor reflectDesc) + if (attr.ExtenderProperty is ReflectPropertyDescriptor) { return new ExtendedPropertyDescriptor(oldPropertyDescriptor, attributes); } @@ -2824,7 +2824,7 @@ internal AttributeTypeDescriptor(Attribute[] attrs, ICustomTypeDescriptor? paren /// public override AttributeCollection GetAttributes() { - Attribute[]? finalAttr = null; + Attribute[]? finalAttr; AttributeCollection existing = base.GetAttributes(); Attribute[] newAttrs = _attributeArray; Attribute[] newArray = new Attribute[existing.Count + newAttrs.Length]; @@ -3922,7 +3922,7 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? at // custom type descriptor TypeDescriptionProvider p = _node.Provider; object? owner; - if (p is ReflectTypeDescriptionProvider rp) + if (p is ReflectTypeDescriptionProvider) { owner = ReflectTypeDescriptionProvider.GetPropertyOwner(_objectType, _instance!, pd); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs index 6324f57626ceb..b11bf810aafd5 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/UriTypeConverter.cs @@ -95,7 +95,7 @@ public override bool IsValid(ITypeDescriptorContext? context, object? value) { if (value is string text) { - return Uri.TryCreate(text, UriKind.RelativeOrAbsolute, out Uri? uri); + return Uri.TryCreate(text, UriKind.RelativeOrAbsolute, out _); } return value is Uri; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs index 1c5629e4643a1..c3c83605400e0 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/Drawing/ColorConverter.cs @@ -101,7 +101,7 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina } else if (destinationType == typeof(InstanceDescriptor)) { - MemberInfo? member = null; + MemberInfo? member; object[]? args = null; if (c.IsEmpty) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs index d798088fe9d41..545880685ccbe 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs @@ -748,7 +748,6 @@ private void RefreshFactoryRecord(string configKey) private object GetSection(string configKey, bool getLkg, bool checkPermission) { - object result; object resultRuntimeObject; // Note that GetSectionRecursive may invalidate this record, @@ -759,7 +758,7 @@ private object GetSection(string configKey, bool getLkg, bool checkPermission) checkPermission, getRuntimeObject: true, requestIsHere: true, - result: out result, + result: out _, resultRuntimeObject: out resultRuntimeObject); return resultRuntimeObject; @@ -1688,8 +1687,7 @@ internal FactoryRecord FindFactoryRecord(string configKey, bool permitErrors, internal FactoryRecord FindFactoryRecord(string configKey, bool permitErrors) { - BaseConfigurationRecord dummy; - return FindFactoryRecord(configKey, permitErrors, out dummy); + return FindFactoryRecord(configKey, permitErrors, out _); } // - Find the nearest factory record @@ -2287,8 +2285,7 @@ private OverrideMode ResolveOverrideModeFromParent(string configKey, out Overrid protected OverrideMode GetSectionLockedMode(string configKey) { - OverrideMode dummy; - return GetSectionLockedMode(configKey, out dummy); + return GetSectionLockedMode(configKey, out _); } // Return the current lock mode for a section diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs index c9203656dea95..0cc7649687c80 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs @@ -192,7 +192,7 @@ protected internal virtual ConfigurationPropertyCollection Properties { get { - ConfigurationPropertyCollection result = null; + ConfigurationPropertyCollection result; if (PropertiesFromType(GetType(), out result)) ApplyValidatorsRecursive(this); @@ -789,8 +789,7 @@ private static ConfigurationProperty CreateConfigurationPropertyFromAttributes(P // Handle some special cases of property types if ((result != null) && typeof(ConfigurationElement).IsAssignableFrom(result.Type)) { - ConfigurationPropertyCollection unused; - PropertiesFromType(result.Type, out unused); + PropertiesFromType(result.Type, out _); } return result; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs index ae5f976f1de93..f0da80518597a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationManager.cs @@ -224,7 +224,7 @@ private static void PreloadConfiguration(Configuration configuration) if (null == configuration) return; // Preload root-level sections. - foreach (ConfigurationSection section in configuration.Sections) { } + foreach (ConfigurationSection _ in configuration.Sections) { } // Recursively preload all section groups and sections. foreach (ConfigurationSectionGroup sectionGroup in configuration.SectionGroups) @@ -236,7 +236,7 @@ private static void PreloadConfigurationSectionGroup(ConfigurationSectionGroup s if (null == sectionGroup) return; // Preload sections just by iterating. - foreach (ConfigurationSection section in sectionGroup.Sections) { } + foreach (ConfigurationSection _ in sectionGroup.Sections) { } // Load child section groups. foreach (ConfigurationSectionGroup childSectionGroup in sectionGroup.SectionGroups) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs index 90b743d395698..85031c95e5fc1 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs @@ -237,8 +237,7 @@ internal ConfigurationSectionGroup GetSectionGroup(string configKey) ConfigurationSectionGroup configSectionGroup = LookupSectionGroup(configKey); if (configSectionGroup != null) return configSectionGroup; - BaseConfigurationRecord configRecord; - FactoryRecord factoryRecord = FindFactoryRecord(configKey, false, out configRecord); + FactoryRecord factoryRecord = FindFactoryRecord(configKey, false, out _); if (factoryRecord == null) return null; if (!factoryRecord.IsGroup) throw ExceptionUtil.ParameterInvalid("sectionGroupName"); @@ -359,9 +358,8 @@ internal ConfigurationSection FindImmediateParentSection(ConfigurationSection se FactoryRecord factoryRecord = GetFactoryRecord(configKey, false); object resultObject; - object resultRuntimeObject; CreateSectionDefault(configKey, false, factoryRecord, null, out resultObject, - out resultRuntimeObject); + out _); result = (ConfigurationSection)resultObject; } else diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueFileSectionHandler.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueFileSectionHandler.cs index d434bd577a2e7..11abcd0076ce7 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueFileSectionHandler.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/NameValueFileSectionHandler.cs @@ -28,7 +28,7 @@ public object Create(object parent, object configContext, XmlNode section) if (fileAttribute != null && fileAttribute.Value.Length != 0) { - string filename = null; + string filename; filename = fileAttribute.Value; IConfigErrorInfo configXmlNode = fileAttribute as IConfigErrorInfo; if (configXmlNode == null) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs index d56275b403756..d67be0bafaa62 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionUpdates.cs @@ -29,10 +29,10 @@ internal SectionUpdates(string name) // Find the SectionUpdates for a configKey, and create it if it does not exist. private SectionUpdates FindSectionUpdates(string configKey, bool isGroup) { - string group, dummy; + string group; if (isGroup) group = configKey; - else BaseConfigurationRecord.SplitConfigKey(configKey, out group, out dummy); + else BaseConfigurationRecord.SplitConfigKey(configKey, out group, out _); Debug.Assert(string.IsNullOrEmpty(_name), "FindSectionUpdates assumes search is from root record"); SectionUpdates sectionUpdates = this; diff --git a/src/libraries/System.Console/src/System/ConsolePal.Unix.cs b/src/libraries/System.Console/src/System/ConsolePal.Unix.cs index 2b55bf8c57838..4619429733669 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Unix.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Unix.cs @@ -342,7 +342,7 @@ public static int WindowWidth { get { - GetWindowSize(out int width, out int height); + GetWindowSize(out int width, out _); return width; } set { throw new PlatformNotSupportedException(); } @@ -352,7 +352,7 @@ public static int WindowHeight { get { - GetWindowSize(out int width, out int height); + GetWindowSize(out _, out int height); return height; } set { throw new PlatformNotSupportedException(); } diff --git a/src/libraries/System.Console/src/System/ConsolePal.Windows.cs b/src/libraries/System.Console/src/System/ConsolePal.Windows.cs index 9542a6ea15345..32cb7659d5193 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Windows.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Windows.cs @@ -93,9 +93,8 @@ private static unsafe bool ConsoleHandleIsWritable(IntPtr outErrHandle) // stdin, stdout and stderr, but they may not be readable or // writable. Verify this by calling WriteFile in the // appropriate modes. This must handle console-less Windows apps. - int bytesWritten; byte junkByte = 0x41; - int r = Interop.Kernel32.WriteFile(outErrHandle, &junkByte, 0, out bytesWritten, IntPtr.Zero); + int r = Interop.Kernel32.WriteFile(outErrHandle, &junkByte, 0, out _, IntPtr.Zero); return r != 0; // In Win32 apps w/ no console, bResult should be 0 for failure. } @@ -273,11 +272,9 @@ public static bool KeyAvailable if (_cachedInputRecord.eventType == Interop.KEY_EVENT) return true; - Interop.InputRecord ir = default; - int numEventsRead = 0; while (true) { - bool r = Interop.Kernel32.PeekConsoleInput(InputHandle, out ir, 1, out numEventsRead); + bool r = Interop.Kernel32.PeekConsoleInput(InputHandle, out Interop.InputRecord ir, 1, out int numEventsRead); if (!r) { int errorCode = Marshal.GetLastPInvokeError(); @@ -292,7 +289,7 @@ public static bool KeyAvailable // Skip non key-down && mod key events. if (!IsKeyDownEvent(ir) || IsModKey(ir)) { - r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead); + r = Interop.Kernel32.ReadConsoleInput(InputHandle, out _, 1, out _); if (!r) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError()); @@ -310,7 +307,6 @@ public static bool KeyAvailable public static ConsoleKeyInfo ReadKey(bool intercept) { Interop.InputRecord ir; - int numEventsRead = -1; bool r; lock (s_readKeySyncObject) @@ -334,7 +330,7 @@ public static ConsoleKeyInfo ReadKey(bool intercept) while (true) { - r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out numEventsRead); + r = Interop.Kernel32.ReadConsoleInput(InputHandle, out ir, 1, out int numEventsRead); if (!r || numEventsRead == 0) { // This will fail when stdin is redirected from a file or pipe. @@ -411,8 +407,7 @@ public static bool TreatControlCAsInput if (handle == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); - int mode = 0; - if (!Interop.Kernel32.GetConsoleMode(handle, out mode)) + if (!Interop.Kernel32.GetConsoleMode(handle, out int mode)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError()); return (mode & Interop.Kernel32.ENABLE_PROCESSED_INPUT) == 0; @@ -423,8 +418,7 @@ public static bool TreatControlCAsInput if (handle == InvalidHandleValue) throw new IOException(SR.IO_NoConsole); - int mode = 0; - if (!Interop.Kernel32.GetConsoleMode(handle, out mode)) + if (!Interop.Kernel32.GetConsoleMode(handle, out int mode)) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError()); if (value) @@ -767,17 +761,15 @@ public static void Clear() // fill the entire screen with blanks - int numCellsWritten = 0; success = Interop.Kernel32.FillConsoleOutputCharacter(hConsole, ' ', - conSize, coordScreen, out numCellsWritten); + conSize, coordScreen, out _); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError()); // now set the buffer's attributes accordingly - numCellsWritten = 0; success = Interop.Kernel32.FillConsoleOutputAttribute(hConsole, csbi.wAttributes, - conSize, coordScreen, out numCellsWritten); + conSize, coordScreen, out _); if (!success) throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError()); @@ -1042,8 +1034,7 @@ private static ConsoleColor ColorAttributeToConsoleColor(Interop.Kernel32.Color private static Interop.Kernel32.CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo() { - bool unused; - return GetBufferInfo(true, out unused); + return GetBufferInfo(true, out _); } // For apps that don't have a console (like Windows apps), they might diff --git a/src/libraries/System.Console/src/System/IO/StdInReader.cs b/src/libraries/System.Console/src/System/IO/StdInReader.cs index fe0ab79f4fb7b..c5ba73ff740b3 100644 --- a/src/libraries/System.Console/src/System/IO/StdInReader.cs +++ b/src/libraries/System.Console/src/System/IO/StdInReader.cs @@ -391,12 +391,11 @@ internal bool MapBufferToConsoleKey(out ConsoleKey key, out char ch, out bool is } // Check if we can match Esc + combination and guess if alt was pressed. - isAlt = isCtrl = isShift = false; if (_unprocessedBufferToBeRead[_startIndex] == (char)0x1B && // Alt is send as an escape character _endIndex - _startIndex >= 2) // We have at least two characters to read { _startIndex++; - if (MapBufferToConsoleKey(out key, out ch, out isShift, out isAlt, out isCtrl)) + if (MapBufferToConsoleKey(out key, out ch, out isShift, out _, out isCtrl)) { isAlt = true; return true; @@ -416,7 +415,7 @@ internal bool MapBufferToConsoleKey(out ConsoleKey key, out char ch, out bool is // Try reading the first char in the buffer and interpret it as a key. ch = _unprocessedBufferToBeRead[_startIndex++]; key = GetKeyFromCharValue(ch, out isShift, out isCtrl); - + isAlt = false; return key != default(ConsoleKey); } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs index ba0a44032fc69..046366210dc55 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataRecordInternal.cs @@ -104,7 +104,7 @@ public override byte GetByte(int i) public override long GetBytes(int i, long dataIndex, byte[]? buffer, int bufferIndex, int length) { - int cbytes = 0; + int cbytes; int ndataIndex; byte[] data = (byte[])_values[i]; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs index 13552bc01785e..c25c75a80c877 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs @@ -88,7 +88,7 @@ public virtual object this[string keyword] set { ADP.CheckArgumentNull(keyword, nameof(keyword)); - bool flag = false; + bool flag; if (null != value) { string keyvalue = DbConnectionStringBuilderUtil.ConvertToString(value); @@ -431,7 +431,7 @@ protected virtual void GetProperties(Hashtable propertyDescriptors) { // Below call is necessary to tell the trimmer that it should mark derived types appropriately. // We cannot use overload which takes type because the result might differ if derived class implements ICustomTypeDescriptor. - Type thisType = GetType(); + GetType(); // show all strongly typed properties (not already added) // except ConnectionString iff BrowsableConnectionString @@ -587,7 +587,7 @@ private PropertyDescriptorCollection GetProperties(Attribute[]? attributes) { // Below call is necessary to tell the trimmer that it should mark derived types appropriately. // We cannot use overload which takes type because the result might differ if derived class implements ICustomTypeDescriptor. - Type thisType = GetType(); + GetType(); return TypeDescriptor.GetClassName(this, true); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", @@ -596,7 +596,7 @@ private PropertyDescriptorCollection GetProperties(Attribute[]? attributes) { // Below call is necessary to tell the trimmer that it should mark derived types appropriately. // We cannot use overload which takes type because the result might differ if derived class implements ICustomTypeDescriptor. - Type thisType = GetType(); + GetType(); return TypeDescriptor.GetComponentName(this, true); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", @@ -641,7 +641,7 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { // Below call is necessary to tell the trimmer that it should mark derived types appropriately. // We cannot use overload which takes type because the result might differ if derived class implements ICustomTypeDescriptor. - Type thisType = GetType(); + GetType(); return TypeDescriptor.GetEvents(this, true); } [RequiresUnreferencedCode("The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")] diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs index 0dbff5981b22d..1c202420c6fa0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs @@ -1598,7 +1598,7 @@ private void UpdateRowExecute(RowUpdatedEventArgs rowUpdatedEvent, IDbCommand da private int UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, int commandCount) { Debug.Assert(null != rowUpdatedEvent, "null rowUpdatedEvent"); - int cumulativeDataRowsAffected = 0; + int cumulativeDataRowsAffected; switch (rowUpdatedEvent.Status) { case UpdateStatus.Continue: diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs index 7489652d9ba15..0aa98075f3764 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs @@ -351,7 +351,7 @@ public override object ConvertXmlToObject(string s) [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute? xmlAttrib) { - object? retValue = null; + object? retValue; bool isBaseCLRType = false; bool legacyUDT = false; // in 1.0 and 1.1 we used to call ToString on CDT obj. so if we have the same case // we need to handle the case when we have column type as object. diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs index a9d8ac3f1f021..275c652b3ee82 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs @@ -624,11 +624,10 @@ internal int InternalIndexOf(string? constraintName) if ((null != constraintName) && (0 < constraintName.Length)) { int constraintCount = List.Count; - int result = 0; for (int i = 0; i < constraintCount; i++) { Constraint constraint = (Constraint)List[i]!; - result = NamesEqual(constraint.ConstraintName, constraintName, false, _table.Locale); + int result = NamesEqual(constraint.ConstraintName, constraintName, false, _table.Locale); if (result == 1) return i; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs index cfe21932b0a1e..252b84fa2efaa 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs @@ -566,7 +566,7 @@ internal bool CanRemove(DataColumn? column, bool fThrowException) // while index events are suspended else the indexes won't be properly maintained. // However, all the above checks should catch those participating columns. // except when a column is in a DataView RowFilter or Sort clause - foreach (Index index in _table.LiveIndexes) { } + foreach (Index _ in _table.LiveIndexes) { } return true; } @@ -723,10 +723,9 @@ internal int IndexOfCaseInsensitive(string name) { int hashcode = _table.GetSpecialHashCode(name); int cachedI = -1; - DataColumn? column = null; for (int i = 0; i < Count; i++) { - column = (DataColumn)_list[i]!; + DataColumn column = (DataColumn)_list[i]!; if ((hashcode == 0 || column._hashCode == 0 || column._hashCode == hashcode) && NamesEqual(column.ColumnName, name, false, _table.Locale) != 0) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs index 1bec593c84971..7738305236ee7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs @@ -336,11 +336,10 @@ internal int InternalIndexOf(string? name) if ((null != name) && (0 < name.Length)) { int count = List.Count; - int result = 0; for (int i = 0; i < count; i++) { DataRelation relation = (DataRelation)List[i]!; - result = NamesEqual(relation.RelationName, name, false, GetDataSet().Locale); + int result = NamesEqual(relation.RelationName, name, false, GetDataSet().Locale); if (result == 1) { return i; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs index 19b725110bb14..b9f35e9a65189 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRow.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRow.cs @@ -1204,7 +1204,7 @@ public void RejectChanges() } foreach (DataColumn dc in _columns.ColumnsImplementingIChangeTracking) { - object? value = null; + object? value; if (RowState != DataRowState.Deleted) value = this[dc]; else @@ -1426,7 +1426,6 @@ internal int CopyValuesIntoStore(ArrayList storeList, ArrayList nullbitList, int _columns[i].CopyValueIntoStore(_tempRecord, storeList[i]!, (BitArray)nullbitList[i]!, storeIndex); } recordCount++; - storeIndex++; } return recordCount; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index b2a85e44b382e..7778e96c3b5a7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -357,15 +357,13 @@ private void SerializeDataSet(SerializationInfo info, StreamingContext context, // old behaviour string strSchema = GetXmlSchemaForRemoting(null); - string? strData = null; info.AddValue(KEY_XMLSCHEMA, strSchema); StringBuilder strBuilder = new StringBuilder(EstimatedXmlStringSize() * 2); StringWriter strWriter = new StringWriter(strBuilder, CultureInfo.InvariantCulture); XmlTextWriter w = new XmlTextWriter(strWriter); WriteXml(w, XmlWriteMode.DiffGram); - strData = strWriter.ToString(); - info.AddValue(KEY_XMLDIFFGRAM, strData); + info.AddValue(KEY_XMLDIFFGRAM, strWriter.ToString()); } } @@ -1978,7 +1976,7 @@ private void WriteXmlSchema(XmlWriter? writer, SchemaFormat schemaFormat, Conver // Generate SchemaTree and write it out if (writer != null) { - XmlTreeGen? treeGen = null; + XmlTreeGen treeGen; if (schemaFormat == SchemaFormat.WebService && SchemaSerializationMode == SchemaSerializationMode.ExcludeSchema && writer.WriteState == WriteState.Element) @@ -2804,7 +2802,7 @@ public XmlReadMode ReadXml(TextReader? reader, XmlReadMode mode) [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] public XmlReadMode ReadXml(string fileName, XmlReadMode mode) { - XmlTextReader? xr = null; + XmlTextReader xr; if (mode == XmlReadMode.Fragment) { FileStream stream = new FileStream(fileName, FileMode.Open); @@ -3262,8 +3260,8 @@ internal bool ValidateCaseConstraint() } } - ForeignKeyConstraint? constraint = null; - ConstraintCollection? constraints = null; + ForeignKeyConstraint? constraint; + ConstraintCollection? constraints; for (int i = 0; i < Tables.Count; i++) { constraints = Tables[i].Constraints; @@ -3302,8 +3300,8 @@ internal bool ValidateLocaleConstraint() } } - ForeignKeyConstraint? constraint = null; - ConstraintCollection? constraints = null; + ForeignKeyConstraint? constraint; + ConstraintCollection? constraints; for (int i = 0; i < Tables.Count; i++) { constraints = Tables[i].Constraints; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index 3759b0a04ddd0..be4c83ae79967 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -1622,7 +1622,7 @@ public DataColumn[] PrimaryKey set { UniqueConstraint? key = null; - UniqueConstraint? existingKey = null; + UniqueConstraint? existingKey; // Loading with persisted property if (fInitInProgress && value != null) @@ -2176,7 +2176,7 @@ internal DataRow MergeRow(DataRow row, DataRow? targetRow, bool preserveChanges, try { DataRowState saveRowState = targetRow.RowState; - int saveIdxRecord = (saveRowState == DataRowState.Added) ? targetRow._newRecord : saveIdxRecord = targetRow._oldRecord; + int saveIdxRecord = (saveRowState == DataRowState.Added) ? targetRow._newRecord : targetRow._oldRecord; int newRecord; int oldRecord; if (targetRow.RowState == DataRowState.Unchanged && row.RowState == DataRowState.Unchanged) @@ -2737,7 +2737,7 @@ internal DataRow AddRecords(int oldRecord, int newRecord) internal void InsertRow(DataRow row, long proposedID, int pos, bool fireEvent) { - Exception? deferredException = null; + Exception? deferredException; if (row == null) { @@ -3920,7 +3920,7 @@ internal void SilentlySetValue(DataRow dr, DataColumn dc, DataRowVersion version // get record for version int record = dr.GetRecordFromVersion(version); - bool equalValues = false; + bool equalValues; if (DataStorage.IsTypeCustomType(dc.DataType) && newValue != dc[record]) { // if UDT storage, need to check if reference changed. @@ -4245,7 +4245,7 @@ public DataRow[] Select(string? filterExpression, string? sort, DataViewRowState internal void SetNewRecord(DataRow row, int proposedRecord, DataRowAction action = DataRowAction.Change, bool isInMerge = false, bool fireEvent = true, bool suppressEnsurePropertyChanged = false) { - Exception? deferredException = null; + Exception? deferredException; SetNewRecordWorker(row, proposedRecord, action, isInMerge, suppressEnsurePropertyChanged, -1, fireEvent, out deferredException); // we are going to call below overload from insert if (deferredException != null) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs index e4dd696086956..0dc5aa0510d6d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs @@ -259,7 +259,7 @@ public event CollectionChangeEventHandler? CollectionChanging /// internal string AssignName() { - string? newName = null; + string newName; while (Contains(newName = MakeName(_defaultNameIndex))) { _defaultNameIndex++; @@ -631,7 +631,7 @@ internal int InternalIndexOf(string? tableName) if ((null != tableName) && (0 < tableName.Length)) { int count = _list.Count; - int result = 0; + int result; for (int i = 0; i < count; i++) { DataTable table = (DataTable)_list[i]!; @@ -668,7 +668,7 @@ internal int InternalIndexOf(string? tableName, string tableNamespace) if ((null != tableName) && (0 < tableName.Length)) { int count = _list.Count; - int result = 0; + int result; for (int i = 0; i < count; i++) { DataTable table = (DataTable)_list[i]!; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs index 03c7c20835208..0919dc0361394 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs @@ -1437,7 +1437,7 @@ internal StorageType ResultSqlType(StorageType left, StorageType right, bool lc, DataTypePrecedence higherPrec = (DataTypePrecedence)Math.Max(leftPrecedence, rightPrecedence); - StorageType result = GetPrecedenceType(higherPrec); + StorageType result; // if we have at least one Sql type, the intermediate result should be Sql type result = GetPrecedenceType((DataTypePrecedence)SqlResultType((int)higherPrec)); @@ -1598,7 +1598,7 @@ internal string AnalyzePattern(string pat) char[] patchars = new char[length + 1]; pat.CopyTo(0, patchars, 0, length); patchars[length] = (char)0; - string? substring = null; + string? substring; char[] constchars = new char[length + 1]; int newLength = 0; diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs index 83a5066a4261c..5972b3d3c4357 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs @@ -207,7 +207,7 @@ internal ExpressionNode Parse() case Tokens.StringConst: case Tokens.Date: ExpressionNode? node = null; - string? str = null; + string? str; /* Constants and identifiers: create leaf node */ @@ -264,7 +264,6 @@ internal ExpressionNode Parse() ScanToken(Tokens.Name); colname = NameNode.ParseName(_text, _start, _pos); - opInfo = _ops[_topOperator - 1]; node = new LookupNode(_table, colname, relname); break; @@ -272,7 +271,6 @@ internal ExpressionNode Parse() case Tokens.Name: /* Qualify name now for nice error checking */ - opInfo = _ops[_topOperator - 1]; /* Create tree element - */ // CONSIDER: Check for reserved proc names here @@ -655,7 +653,7 @@ private void NodePush(ExpressionNode node) private void BuildExpression(int pri) { - ExpressionNode? expr = null; + ExpressionNode? expr; Debug.Assert(pri > Operators.priStart && pri <= Operators.priMax, "Invalid priority value"); diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs index 5e0fcb3742447..a7a32ed98825b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/UnaryNode.cs @@ -47,7 +47,7 @@ internal override object Eval(int[] recordNos) private object EvalUnaryOp(int op, object vl) { - object value = DBNull.Value; + object value; if (DataExpression.IsUnknown(vl)) return DBNull.Value; diff --git a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs index 39d130e4ff0f4..1513b767d212b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs @@ -599,7 +599,7 @@ internal override void CheckConstraint(DataRow childRow, DataRowAction action) // could be self-join constraint if (_childKey.Table == _parentKey.Table && childRow._tempRecord != -1) { - int lo = 0; + int lo; for (lo = 0; lo < childValues.Length; lo++) { DataColumn column = _parentKey.ColumnsReference[lo]; @@ -761,12 +761,10 @@ internal override bool ContainsColumn(DataColumn column) => DataColumn[] columns = new DataColumn[keys]; DataColumn[] relatedColumns = new DataColumn[keys]; - int iDest = 0; - for (int i = 0; i < keys; i++) { DataColumn src = Columns[i]; - iDest = destination.Columns.IndexOf(src.ColumnName); + int iDest = destination.Columns.IndexOf(src.ColumnName); if (iDest < 0) { return null; diff --git a/src/libraries/System.Data.Common/src/System/Data/Merger.cs b/src/libraries/System.Data.Common/src/System/Data/Merger.cs index 616acba1372b0..109e2119790d8 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Merger.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Merger.cs @@ -285,7 +285,6 @@ internal void MergeRows(DataRow[] rows) if (null != ndxSearch) { ndxSearch.RemoveRef(); - ndxSearch = null; } ndxSearch = new Index(dst, dst._primaryKey!.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, null); ndxSearch.AddRef(); // need to addref twice, otherwise it will be collected @@ -314,7 +313,6 @@ internal void MergeRows(DataRow[] rows) if (null != ndxSearch) { ndxSearch.RemoveRef(); - ndxSearch = null; } _dataSet.EnforceConstraints = fEnforce; diff --git a/src/libraries/System.Data.Common/src/System/Data/RbTree.cs b/src/libraries/System.Data.Common/src/System/Data/RbTree.cs index a5f75b089899b..a7892bdf9816a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RbTree.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RbTree.cs @@ -342,7 +342,7 @@ public bool HasDuplicates private int GetNewNode(K? key) { // find page with free slots, if none, allocate a new page - TreePage? page = null; + TreePage? page; int freePageIndex = GetIndexOfPageWithFreeSlot(true); if (freePageIndex != -1) @@ -1479,7 +1479,7 @@ private int ComputeNodeByIndex(int index, out int satelliteRootId) satelliteRootId = NIL; int x_id = root; - int rank = -1; + int rank; while (x_id != NIL && !(((rank = SubTreeSize(Left(x_id)) + 1) == index) && Next(x_id) == NIL)) { if (index < rank) @@ -1972,8 +1972,8 @@ internal TreePage(int size) */ internal int AllocSlot(RBTree tree) { - int segmentPos = 0; // index into _SlotMap - int freeSlot = 0; // Uint, slot offset within the segment + int segmentPos; // index into _SlotMap + int freeSlot; // Uint, slot offset within the segment int freeSlotId = -1; // 0 based slot position if (_inUseCount < _slots.Length) @@ -1983,7 +1983,6 @@ internal int AllocSlot(RBTree tree) { if (unchecked((uint)_slotMap[segmentPos]) < 0xFFFFFFFF) { - freeSlotId = 0; freeSlot = (~(_slotMap[segmentPos])) & unchecked(_slotMap[segmentPos] + 1); // avoid string concat to allow debug code to run faster diff --git a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs index 94450f9c80d57..c768b3c5e8945 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RelationshipConverter.cs @@ -41,8 +41,8 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina throw new ArgumentNullException(nameof(destinationType)); } - System.Reflection.ConstructorInfo? ctor = null; - object[]? values = null; + System.Reflection.ConstructorInfo? ctor; + object[]? values; if (destinationType == typeof(InstanceDescriptor) && value is DataRelation) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs index b04d39205ba3d..9045b9a1c352d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs @@ -660,7 +660,7 @@ public override long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed(); - long lPosition = 0; + long lPosition; switch (origin) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs index dfb18b73ab652..7719da00f1b3d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs @@ -494,7 +494,7 @@ private void SetBuffer(char[] buffer) void IXmlSerializable.ReadXml(XmlReader r) { - char[]? value = null; + char[]? value; string? isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); @@ -615,7 +615,7 @@ public long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed(); - long lPosition = 0; + long lPosition; switch (origin) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs index 64e7815e2945c..784d50d2bb1cf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs @@ -703,7 +703,6 @@ public SqlDecimal(double dVal) : this(false) { dVal = Math.Floor(dInt / s_DUINT_BASE); _data4 = (uint)(dInt - dVal * s_DUINT_BASE); - dInt = dVal; _bLen++; } } @@ -1123,7 +1122,7 @@ public double ToDouble() if (IsNull) throw new SqlNullValueException(); - double dRet = 0.0; + double dRet; dRet = _data4; dRet = dRet * s_lInt32Base + _data3; @@ -2729,9 +2728,8 @@ out int ciulR // Out | # of digits in R // D8. Unnormalize: Divide D and R to get result if (D1 > 1) { - uint ret; - MpDiv1(rgulD, ref ciulD, D1, out ret); - MpDiv1(rgulR, ref ciulR, D1, out ret); + MpDiv1(rgulD, ref ciulD, D1, out _); + MpDiv1(rgulR, ref ciulR, D1, out _); } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs index 9cd3c54c86000..cac4122feba68 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs @@ -409,7 +409,7 @@ private static SqlBoolean Compare(SqlString x, SqlString y, EComparison ecExpect int iCmpResult = StringCompare(x, y); - bool fResult = false; + bool fResult; switch (ecExpectedResult) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Select.cs b/src/libraries/System.Data.Common/src/System/Data/Select.cs index 79c273c1d5dc9..06f22adc9765a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Select.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Select.cs @@ -691,7 +691,7 @@ private int Eval(BinaryNode expr, DataRow row, DataRowVersion version) // use InvariantCulture instead of DataTable.Locale because in the Danish related cultures // sorting a Guid as a string has different results than in Invariant and English related cultures. // This fix is restricted to DataTable.Select("GuidColumn = 'string literal'") types of queries - NameNode? namedNode = null; + NameNode? namedNode; System.Globalization.CompareInfo? comparer = ((isLConst && !isRConst && (leftType == StorageType.String) && (rightType == StorageType.Guid) && (null != (namedNode = expr._right as NameNode)) && (namedNode._column!.DataType == typeof(Guid))) || (isRConst && !isLConst && (rightType == StorageType.String) && (leftType == StorageType.Guid) && (null != (namedNode = expr._left as NameNode)) && (namedNode._column!.DataType == typeof(Guid)))) diff --git a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs index a025c3f7f2bea..37cd34e6f79e3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs @@ -383,7 +383,7 @@ internal void HandleColumn(XmlElement node, DataTable table) } else { - strName = instanceName = string.Empty; + instanceName = string.Empty; } // Now get the type @@ -443,8 +443,6 @@ internal void HandleColumn(XmlElement node, DataTable table) GetMinMax(node, isAttribute, ref minOccurs, ref maxOccurs); - strDefault = null; - // Does XDR has default? strDefault = node.GetAttribute(Keywords.DEFAULT); diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs index df87d51e94541..2ab54d821686e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs @@ -86,9 +86,7 @@ internal void ProcessDiffs(DataSet ds, XmlReader ssync) while (iSsyncDepth < ssync.Depth) { tableBefore = null; - string? diffId = null; - - oldRowRecord = -1; + string? diffId; // the diffgramm always contains sql:before and sql:after pairs @@ -141,7 +139,6 @@ internal void ProcessDiffs(ArrayList tableList, XmlReader ssync) tableBefore = null; string diffId; - oldRowRecord = -1; // the diffgramm always contains sql:before and sql:after pairs @@ -308,7 +305,7 @@ private int ReadOldRowData(DataSet? ds, ref DataTable? table, ref int pos, XmlRe } int iRowDepth = row.Depth; - string? value = null; + string? value; value = row.GetAttribute(Keywords.ROWORDER, Keywords.MSDNS); if (!string.IsNullOrEmpty(value)) diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs index f103604b74c9f..20e3c2140ba8a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -916,7 +916,7 @@ internal void HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList ta el.MaxOccurs = pt.MaxOccurs; - DataTable? child = null; + DataTable? child; // to decide if element is our table, we need to match both name and ns // 286043 - SQL BU Defect Tracking if (((el.Name == null) && (el.RefName.Name == table.EncodedTableName && el.RefName.Namespace == table.Namespace)) || @@ -1340,7 +1340,7 @@ internal void HandleKeyref(XmlSchemaKeyref keyref) if (fKey[0].Table!.DataSet!.Relations[iExisting].RelationName != relName) iExisting = -1; } - DataRelation? relation = null; + DataRelation? relation; if (iExisting < 0) { relation = new DataRelation(relName, pKey, fKey); @@ -1390,7 +1390,7 @@ internal void HandleKeyref(XmlSchemaKeyref keyref) [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal void HandleConstraint(XmlSchemaIdentityConstraint keyNode) { - string? name = null; + string? name; name = XmlConvert.DecodeName(keyNode.Name); if (name == null || name.Length == 0) @@ -1964,7 +1964,7 @@ internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, return; } - Type? type = null; + Type? type; SimpleType? xsdType = null; // if (typeNode.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType @@ -2101,7 +2101,7 @@ internal void HandleSimpleContentColumn(string strType, DataTable table, bool is if (FromInference && table.XmlText != null) // backward compatability for inference return; - Type? type = null; + Type? type; if (strType == null) { return; @@ -2196,12 +2196,12 @@ internal void HandleSimpleContentColumn(string strType, DataTable table, bool is [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, bool isBase) { - Type? type = null; + Type? type; XmlSchemaAttribute? attr = attrib.Name != null ? attrib : (XmlSchemaAttribute)_attributes![attrib.RefName]!; XmlSchemaAnnotated? typeNode = FindTypeNode(attr); - string? strType = null; + string? strType; SimpleType? xsdType = null; if (typeNode == null) @@ -2359,7 +2359,7 @@ internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool isBase) { - Type? type = null; + Type? type; XmlSchemaElement? el = elem.Name != null ? elem : (XmlSchemaElement?)_elementsTable![elem.RefName]; if (el == null) // it's possible due to some XSD compiler optimizations @@ -2773,7 +2773,7 @@ private void AddTablesToList(List tableList, DataTable dt) { string xpath = key.Selector!.XPath!; string[] split = xpath.Split('/'); - string prefix = string.Empty; + string prefix; string QualifiedTableName = split[split.Length - 1]; //get the last string after '/' and ':' diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs index 3f80ecdf1cbee..736b340ece89c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs @@ -150,7 +150,6 @@ private string GetValueForTextOnlyColums(XmlNode? n) { // don't use string builder if only one text node exists value = n.Value; - n = n.NextSibling; } else { @@ -702,7 +701,7 @@ private void LoadTopMostTable(DataTable table) // If table name we have matches dataset // name top node could be a DataSet OR a table. // It's a table overwise. - DataRow? row = null; // Data row we're going to add to this table + DataRow? row; // Data row we're going to add to this table bool matchFound = false; // Assume we found no matching elements @@ -880,7 +879,7 @@ private void LoadTable(DataTable table, bool isNested) Debug.Assert(table != null, "Table to be loaded is null on LoadTable() entry"); - DataRow? row = null; // Data row we're going to add to this table + DataRow? row; // Data row we're going to add to this table int entryDepth = _dataReader!.Depth; // Store current reader depth so we know when to stop reading int entryChild = _childRowsStack!.Count; // Memorize child stack level on entry diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs index 1c042b2102993..f27573c55b6d9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs @@ -457,7 +457,7 @@ private ArrayList GetSelfAndDescendants(DataTable dt) public object? GetColumnSchema(XmlNode node, bool fIgnoreNamespace) { Debug.Assert(node != null, "Argument validation"); - TableSchemaInfo? tableSchemaInfo = null; + TableSchemaInfo? tableSchemaInfo; XmlNode? nodeRegion = (node.NodeType == XmlNodeType.Attribute) ? ((XmlAttribute)node).OwnerElement : node.ParentNode; diff --git a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs index 49fbf274d2335..b79b96c418472 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -1074,7 +1074,7 @@ internal XmlElement FillDataSetElement(XmlDocument xd, DataSet? ds, DataTable? d internal void SetPath(XmlWriter xw) { - FileStream? fs = null; + FileStream? fs; DataTextWriter? sw = xw as DataTextWriter; fs = (sw != null) ? sw.BaseStream as FileStream : null; @@ -1725,7 +1725,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche Debug.Assert(_dsElement != null); XmlElement root = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); - bool fWriteOrdinals = false; + bool fWriteOrdinals; bool fUnqualified = false; if (((table.DataSet == null) || (_ds != null && table.Namespace != _ds.Namespace)) && (_schFormat == SchemaFormat.Remoting)) @@ -1855,7 +1855,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche root.SetAttribute(Keywords.TYPE, NewDiffgramGen.QualifiedName((string)_prefixes[table.TypeName.Namespace]!, table.TypeName.Name)); } - XmlElement? compositor = null; + XmlElement? compositor; DataColumn? colTxt = table.XmlText; @@ -1989,7 +1989,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche for (int i = 0; i < constraints.Count; i++) { - XmlElement? constraint = null; + XmlElement? constraint; DataColumn[] fields; if (constraints[i] is UniqueConstraint) @@ -2541,7 +2541,7 @@ private void GenerateRow(DataRow row) [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] private void GenerateColumn(DataRow row, DataColumn col, DataRowVersion version) { - string? value = null; + string? value; value = col.GetColumnValueAsString(row, version); // this is useless for CTD if (value == null) diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs index 3df260fa1abbc..c7e99046842f2 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs @@ -650,7 +650,7 @@ internal void RealFoliate() return; } - XmlNode? n = null; + XmlNode? n; if (_doc.IsTextOnly(_column!)) { diff --git a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs index 4e4c878b51c54..5d5f7b4d268d1 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs @@ -88,7 +88,7 @@ private XPathNodeType DecideXPNodeTypeForTextNodes(XmlNode node) private XPathNodeType ConvertNodeType(XmlNode node) { - int xnt = -1; + int xnt; if (XmlDataDocument.IsTextNode(node.NodeType)) return DecideXPNodeTypeForTextNodes(node); xnt = s_xmlNodeType_To_XpathNodeType_Map[(int)(node.NodeType)]; @@ -404,8 +404,8 @@ internal string XmlLang { RealFoliate(); XmlNode curNode = _node; - XmlBoundElement? curBoundElem = null; - object? colVal = null; + XmlBoundElement? curBoundElem; + object? colVal; while (curNode != null) { curBoundElem = curNode as XmlBoundElement; @@ -853,7 +853,7 @@ internal bool MoveToFirst() if (_node != null) { DataRow? curRow = null; - XmlNode? parent = null; + XmlNode? parent; if (_column != null) { curRow = Row; @@ -1006,7 +1006,7 @@ internal bool MoveToParent() } else { - XmlNode? n = null; + XmlNode? n; if (_node.NodeType == XmlNodeType.Attribute) n = ((XmlAttribute)_node).OwnerElement; else @@ -1099,7 +1099,7 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) if (IsSamePosition(other)) return XmlNodeOrder.Same; - XmlNode? curNode1 = null, curNode2 = null; + XmlNode? curNode1, curNode2; //deal with namespace node first if (NodeType == XPathNodeType.Namespace && other.NodeType == XPathNodeType.Namespace) @@ -1209,7 +1209,7 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) XmlNode? parent1 = GetParent(curNode1!); XmlNode? parent2 = GetParent(curNode2!); - XmlNode? nextNode = null; + XmlNode? nextNode; while (parent1 != null && parent2 != null) { if (parent1 == parent2) @@ -1291,7 +1291,7 @@ private void RealFoliate() Debug.Assert(_column != null); - XmlNode? n = null; + XmlNode? n; if (_doc.IsTextOnly(_column)) n = _node.FirstChild; @@ -1333,7 +1333,7 @@ private void RealFoliate() { if (be == null) return null; - XmlAttribute? attr = null; + XmlAttribute? attr; if (be.IsFoliated) { attr = be.GetAttributeNode(name, StrReservedXmlns); @@ -1374,8 +1374,8 @@ internal string GetNamespace(string name) name = "xmlns"; RealFoliate(); XmlNode? node = _node; - XmlNodeType nt = node.NodeType; - string? retVal = null; + XmlNodeType nt; + string? retVal; while (node != null) { //first identify an element node in the ancestor + itself @@ -1407,15 +1407,10 @@ internal bool MoveToNamespace(string name) //only need to check with _node, even if _column is not null and its mapping type is element, it can't have attributes if (_parentOfNS == null) return false; - string attrName = name; - if (attrName == "xmlns") - attrName = "xmlns:xmlns"; - if (attrName != null && attrName.Length == 0) - attrName = "xmlns"; RealFoliate(); XmlNode? node = _node; - XmlAttribute? attr = null; - XmlBoundElement? be = null; + XmlAttribute? attr; + XmlBoundElement? be; while (node != null) { //check current element node @@ -1524,7 +1519,7 @@ internal bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) if (_parentOfNS == null) return false; XmlNode? node = _node; - XmlBoundElement? be = null; + XmlBoundElement? be; while (node != null) { be = node as XmlBoundElement; @@ -1557,7 +1552,7 @@ private bool DuplicateNS(XmlBoundElement endElem, string lname) if (_parentOfNS == null || endElem == null) return false; XmlBoundElement? be = _parentOfNS; - XmlNode? node = null; + XmlNode? node; while (be != null && be != endElem) { if (GetNamespace(be, lname) != null) diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs index 97fcd22ba3412..92a6a510a9f36 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs @@ -158,7 +158,7 @@ public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) internal void RemoveAllChildren() { XmlNode? child = FirstChild; - XmlNode? sibling = null; + XmlNode? sibling; while (child != null) { diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs index 3eab2aeaf2e80..c75a7afa48321 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -148,7 +148,7 @@ internal void SyncRows(DataRow? parentRow, XmlNode node, bool fAddRowsToTable) [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] internal void SyncTree(XmlNode node) { - XmlBoundElement? be = null; + XmlBoundElement? be; _mapper.GetRegion(node, out be); DataRow? parentRow = null; bool fAddRowsToTable = IsConnected(node); @@ -765,7 +765,7 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) private XmlNode? GetColumnInsertAfterLocation(DataRow row, DataColumn col, XmlBoundElement rowElement) { XmlNode? prev = null; - XmlNode? node = null; + XmlNode? node; // text only columns appear first if (IsTextOnly(col)) @@ -866,7 +866,7 @@ private ArrayList GetNestedChildRelations(DataRow row) private XmlNode? GetRowInsertBeforeLocation(DataRow row, XmlElement rowElement, XmlNode parentElement) { DataRow refRow = row; - int i = 0; + int i; int pos; // Find position @@ -2327,7 +2327,7 @@ private void PromoteNonValueChildren(XmlNode parent) XmlNode prevSibling = parent; XmlNode? child = parent.FirstChild; bool bTextLikeNode = true; - XmlNode? nextSibling = null; + XmlNode? nextSibling; while (child != null) { nextSibling = child.NextSibling; @@ -2496,7 +2496,7 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis Debug.Assert(row != null); Hashtable foundColumns = new Hashtable(); - string xsi_attrVal = string.Empty; + string xsi_attrVal; RegionIterator iter = new RegionIterator(rowElement); bool fMore; diff --git a/src/libraries/System.Data.Common/tests/System/Data/DataTableTest.cs b/src/libraries/System.Data.Common/tests/System/Data/DataTableTest.cs index 7538f21eac709..8a38cfc60027c 100644 --- a/src/libraries/System.Data.Common/tests/System/Data/DataTableTest.cs +++ b/src/libraries/System.Data.Common/tests/System/Data/DataTableTest.cs @@ -3566,34 +3566,38 @@ public void Remote() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/62965", TestPlatforms.Browser)] // fails on NodeJS on windows public void Bug55978() { DataTable dt = new DataTable(); dt.Columns.Add("StartDate", typeof(DateTime)); DataRow dr; - DateTime date = DateTime.Now; + DateTime now = DateTime.Now; + + // In RowFilter we have a string containing only seconds, + // but in rows we have a DateTime which also contains milliseconds. + // The test would fail without this extra minute, when now.Millisecond is 0. + DateTime rowDate = now.AddMinutes(1); for (int i = 0; i < 10; i++) { dr = dt.NewRow(); - dr["StartDate"] = date.AddDays(i); + dr["StartDate"] = rowDate.AddDays(i); dt.Rows.Add(dr); } DataView dv = dt.DefaultView; dv.RowFilter = string.Format(CultureInfo.InvariantCulture, "StartDate >= #{0}# and StartDate <= #{1}#", - DateTime.Now.AddDays(2), - DateTime.Now.AddDays(4)); + now.AddDays(2), + now.AddDays(4)); Assert.Equal(10, dt.Rows.Count); int expectedRowCount = 2; if (dv.Count != expectedRowCount) { StringBuilder sb = new(); - sb.AppendLine($"DataView.Rows.Count: Expected: {expectedRowCount}, Actual: {dv.Count}. Debug data: RowFilter: {dv.RowFilter}, date: {date}"); + sb.AppendLine($"DataView.Rows.Count: Expected: {expectedRowCount}, Actual: {dv.Count}. Debug data: RowFilter: {dv.RowFilter}, date: {now}"); for (int i = 0; i < dv.Count; i++) { sb.Append($"row#{i}: "); diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs index dba3fdbbc37e4..1e6a0a019a62a 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs @@ -473,8 +473,8 @@ private static string[] NoDuplicateUnion(string[] a, string[] b) { int startPosition = nextStartPosition; - string? keyname, keyvalue; // since parsing restrictions ignores values, it doesn't matter if we use ODBC rules or OLEDB rules - nextStartPosition = DbConnectionOptions.GetKeyValuePair(restrictions, startPosition, buffer, false, out keyname, out keyvalue); + string? keyname; // since parsing restrictions ignores values, it doesn't matter if we use ODBC rules or OLEDB rules + nextStartPosition = DbConnectionOptions.GetKeyValuePair(restrictions, startPosition, buffer, false, out keyname, out _); if (!string.IsNullOrEmpty(keyname)) { string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144 diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs index d752d1233af8e..56abf205f6e3c 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs @@ -322,7 +322,7 @@ public bool ContainsKey(string keyword) internal string? ExpandDataDirectories(ref string? filename, ref int position) { - string? value = null; + string? value; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); string? datadir = null; diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs index ab2d89be6121a..d88cd4f443483 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs @@ -909,7 +909,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o private DbConnectionInternal? GetFromGeneralPool() { - DbConnectionInternal? obj = null; + DbConnectionInternal? obj; if (!_stackNew.TryPop(out obj)) { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs index 0eefd1d2cdb85..0d566e7c3276b 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/Odbc32.cs @@ -730,7 +730,7 @@ internal static void GetDiagErrors(OdbcErrorCollection errors, string? source, O { int NativeError; short iRec = 0; - short cchActual = 0; + short cchActual; StringBuilder message = new StringBuilder(1024); string sqlState; @@ -743,7 +743,7 @@ internal static void GetDiagErrors(OdbcErrorCollection errors, string? source, O if ((SQLRETURN.SUCCESS_WITH_INFO == retcode) && (message.Capacity - 1 < cchActual)) { message.Capacity = cchActual + 1; - retcode = hrHandle.GetDiagnosticRecord(iRec, out sqlState, message, out NativeError, out cchActual); + retcode = hrHandle.GetDiagnosticRecord(iRec, out sqlState, message, out NativeError, out _); } //Note: SUCCESS_WITH_INFO from SQLGetDiagRec would be because diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommandBuilder.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommandBuilder.cs index 0b5d0ea105012..edff9d02d1a90 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommandBuilder.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcCommandBuilder.cs @@ -242,7 +242,7 @@ private static OdbcParameter[] DeriveParametersFromStoredProcedure(OdbcConnectio rParams.Add(parameter); } } - retcode = hstmt.CloseCursor(); + hstmt.CloseCursor(); return rParams.ToArray(); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs index 5c5f3e3a2c059..5de32103c9e0c 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs @@ -380,7 +380,7 @@ private void DisposeMe(bool disposing) internal string GetConnectAttrString(ODBC32.SQL_ATTR attribute) { string value = ""; - int cbActual = 0; + int cbActual; byte[] buffer = new byte[100]; OdbcConnectionHandle? connectionHandle = ConnectionHandle; if (null != connectionHandle) @@ -413,12 +413,11 @@ internal string GetConnectAttrString(ODBC32.SQL_ATTR attribute) internal int GetConnectAttr(ODBC32.SQL_ATTR attribute, ODBC32.HANDLER handler) { int retval = -1; - int cbActual = 0; byte[] buffer = new byte[4]; OdbcConnectionHandle? connectionHandle = ConnectionHandle; if (null != connectionHandle) { - ODBC32.SQLRETURN retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out cbActual); + ODBC32.SQLRETURN retcode = connectionHandle.GetConnectionAttribute(attribute, buffer, out _); if ((ODBC32.SQLRETURN.SUCCESS == retcode) || (ODBC32.SQLRETURN.SUCCESS_WITH_INFO == retcode)) { @@ -483,7 +482,7 @@ private int GetInfoInt32Unhandled(ODBC32.SQL_INFO infotype) { //SQLGetInfo string? value = null; - short cbActual = 0; + short cbActual; byte[] buffer = new byte[100]; OdbcConnectionHandle? connectionHandle = ConnectionHandle; if (null != connectionHandle) diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs index d9d35950a2e61..8a978df0eb052 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionFactory.cs @@ -53,25 +53,17 @@ internal override DbConnectionPoolGroupProviderInfo CreateConnectionPoolGroupPro return new OdbcConnectionPoolGroupProviderInfo(); } - protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection, out bool cacheMetaDataFactory) + protected override DbMetaDataFactory CreateMetaDataFactory(DbConnectionInternal internalConnection) { Debug.Assert(internalConnection != null, "internalConnection may not be null."); - cacheMetaDataFactory = false; OdbcConnection odbcOuterConnection = ((OdbcConnectionOpen)internalConnection).OuterConnection; Debug.Assert(odbcOuterConnection != null, "outer connection may not be null."); // get the DBMS Name - object? driverName = null; - string? stringValue = odbcOuterConnection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME); - if (stringValue != null) - { - driverName = stringValue; - } + odbcOuterConnection.GetInfoStringUnhandled(ODBC32.SQL_INFO.DRIVER_NAME); Stream? XMLStream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("System.Data.Odbc.OdbcMetaData.xml"); - cacheMetaDataFactory = true; - Debug.Assert(XMLStream != null, "XMLstream may not be null."); diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHandle.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHandle.cs index c23159d34b0b7..b573da4b8ab6b 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHandle.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHandle.cs @@ -41,7 +41,7 @@ internal OdbcConnectionHandle(OdbcConnection connection, OdbcConnectionString co //a odbc 3.0 feature. The ConnectionTimeout on the managed providers represents //the login timeout, nothing more. int connectionTimeout = connection.ConnectionTimeout; - retcode = SetConnectionAttribute2(ODBC32.SQL_ATTR.LOGIN_TIMEOUT, (IntPtr)connectionTimeout, (int)ODBC32.SQL_IS.UINTEGER); + SetConnectionAttribute2(ODBC32.SQL_ATTR.LOGIN_TIMEOUT, (IntPtr)connectionTimeout, (int)ODBC32.SQL_IS.UINTEGER); string connectionString = constr.UsersConnectionString(false); @@ -195,8 +195,7 @@ private ODBC32.SQLRETURN Connect(string connectionString) try { } finally { - short cbActualSize; - retcode = Interop.Odbc.SQLDriverConnectW(this, ADP.PtrZero, connectionString, ODBC32.SQL_NTS, ADP.PtrZero, 0, out cbActualSize, (short)ODBC32.SQL_DRIVER.NOPROMPT); + retcode = Interop.Odbc.SQLDriverConnectW(this, ADP.PtrZero, connectionString, ODBC32.SQL_NTS, ADP.PtrZero, 0, out _, (short)ODBC32.SQL_DRIVER.NOPROMPT); switch (retcode) { case ODBC32.SQLRETURN.SUCCESS: @@ -212,14 +211,13 @@ private ODBC32.SQLRETURN Connect(string connectionString) protected override bool ReleaseHandle() { // NOTE: The SafeHandle class guarantees this will be called exactly once and is non-interrutible. - ODBC32.SQLRETURN retcode; // must call complete the transaction rollback, change handle state, and disconnect the connection - retcode = CompleteTransaction(ODBC32.SQL_ROLLBACK, handle); + CompleteTransaction(ODBC32.SQL_ROLLBACK, handle); if ((HandleState.Connected == _handleState) || (HandleState.TransactionInProgress == _handleState)) { - retcode = Interop.Odbc.SQLDisconnect(handle); + Interop.Odbc.SQLDisconnect(handle); _handleState = HandleState.Allocated; } Debug.Assert(HandleState.Allocated == _handleState, "not expected HandleState.Allocated"); diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs index 8e57c9e8f4233..fb9e8d88c4bea 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs @@ -174,8 +174,7 @@ public override int FieldCount } if (null == _dataCache) { - short cColsAffected; - ODBC32.SQLRETURN retcode = this.FieldCountNoThrow(out cColsAffected); + ODBC32.SQLRETURN retcode = this.FieldCountNoThrow(out _); if (retcode != ODBC32.SQLRETURN.SUCCESS) { Connection!.HandleError(StatementHandle, retcode); @@ -547,8 +546,7 @@ internal object GetValue(int i, TypeMap typemap) { if (_dataCache!.AccessIndex(i) == null) { - int dummy; - bool isNotDbNull = QueryFieldInfo(i, ODBC32.SQL_C.BINARY, out dummy); + bool isNotDbNull = QueryFieldInfo(i, ODBC32.SQL_C.BINARY, out _); // if the value is DBNull, QueryFieldInfo will cache it if (isNotDbNull) { @@ -672,8 +670,7 @@ public override bool IsDBNull(int i) // case 3 - the data has variable-length type, read zero-length data to query for null // QueryFieldInfo will return false only if the object cached as DbNull // QueryFieldInfo will put DbNull in cache only if the SQLGetData returns SQL_NULL_DATA, otherwise it does not change it - int dummy; - return !QueryFieldInfo(i, typeMap._sql_c, out dummy); + return !QueryFieldInfo(i, typeMap._sql_c, out _); } } @@ -1133,7 +1130,7 @@ private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsB // use the cache - preserve the original behavior to minimize regression risk // 4. sequential access, no cache: (fixed now) user reads the bytes/chars in sequential order (no cache) - object? cachedObj = null; // The cached object (if there is one) + object? cachedObj; // The cached object (if there is one) // Get cached object, ensure the correct type using explicit cast, to preserve same behavior as before if (isCharsBuffer) @@ -1335,8 +1332,7 @@ private long GetBytesOrChars(int i, long dataIndex, Array? buffer, bool isCharsB { // for GetChars, ensure data is not null // 2 bytes for '\0' termination, no data is actually read from the driver - int cbLengthOrIndicator; - bool isDbNull = !QueryFieldInfo(i, ODBC32.SQL_C.WCHAR, out cbLengthOrIndicator); + bool isDbNull = !QueryFieldInfo(i, ODBC32.SQL_C.WCHAR, out _); if (isDbNull) { throw ADP.InvalidCast(); @@ -1550,7 +1546,6 @@ private object internalGetBytes(int i) // private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId, ODBC32.HANDLER handler) { - short cchNameLength = 0; SQLLEN numericAttribute; ODBC32.SQLRETURN retcode; @@ -1564,11 +1559,11 @@ private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQ OdbcStatementHandle stmt = StatementHandle; if (Connection.IsV3Driver) { - retcode = stmt.ColumnAttribute(iColumn + 1, (short)v3FieldId, Buffer, out cchNameLength, out numericAttribute); + retcode = stmt.ColumnAttribute(iColumn + 1, (short)v3FieldId, Buffer, out _, out numericAttribute); } else if (v2FieldId != (ODBC32.SQL_COLUMN)(-1)) { - retcode = stmt.ColumnAttribute(iColumn + 1, (short)v2FieldId, Buffer, out cchNameLength, out numericAttribute); + retcode = stmt.ColumnAttribute(iColumn + 1, (short)v2FieldId, Buffer, out _, out numericAttribute); } else { @@ -1604,8 +1599,7 @@ private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQ private string? GetColAttributeStr(int i, ODBC32.SQL_DESC v3FieldId, ODBC32.SQL_COLUMN v2FieldId, ODBC32.HANDLER handler) { ODBC32.SQLRETURN retcode; - short cchNameLength = 0; - SQLLEN numericAttribute; + short cchNameLength; CNativeBuffer buffer = Buffer; buffer.WriteInt16(0, 0); @@ -1619,11 +1613,11 @@ private SQLLEN GetColAttribute(int iColumn, ODBC32.SQL_DESC v3FieldId, ODBC32.SQ if (Connection.IsV3Driver) { - retcode = stmt.ColumnAttribute(i + 1, (short)v3FieldId, buffer, out cchNameLength, out numericAttribute); + retcode = stmt.ColumnAttribute(i + 1, (short)v3FieldId, buffer, out cchNameLength, out _); } else if (v2FieldId != (ODBC32.SQL_COLUMN)(-1)) { - retcode = stmt.ColumnAttribute(i + 1, (short)v2FieldId, buffer, out cchNameLength, out numericAttribute); + retcode = stmt.ColumnAttribute(i + 1, (short)v2FieldId, buffer, out cchNameLength, out _); } else { @@ -1720,8 +1714,7 @@ private bool GetData(int i, ODBC32.SQL_C sqlctype) { // Never call GetData with anything larger than _buffer.Length-2. // We keep reallocating native buffers and it kills performance!!! - int dummy; - return GetData(i, sqlctype, Buffer.Length - 4, out dummy); + return GetData(i, sqlctype, Buffer.Length - 4, out _); } /// @@ -1739,7 +1732,7 @@ private bool GetData(int i, ODBC32.SQL_C sqlctype) /// false if value is DbNull, true otherwise private bool GetData(int i, ODBC32.SQL_C sqlctype, int cb, out int cbLengthOrIndicator) { - IntPtr cbActual = IntPtr.Zero; // Length or an indicator value + IntPtr cbActual; // Length or an indicator value if (IsCancelingCommand) { @@ -2334,7 +2327,7 @@ internal int RetrieveKeyInfo(bool needkeyinfo, QualifiedTableName qualifiedTable string columnname; int ordinal; int keyColumns = 0; - IntPtr cbActual = IntPtr.Zero; + IntPtr cbActual; if (IsClosed || (_cmdWrapper == null)) { @@ -2502,7 +2495,7 @@ private int RetrieveKeyInfoFromStatistics(QualifiedTableName qualifiedTableName, ODBC32.SQLRETURN retcode; string columnname = string.Empty; - string indexname = string.Empty; + string indexname; string currentindexname = string.Empty; int[] indexcolumnordinals = new int[16]; int[] pkcolumnordinals = new int[16]; @@ -2511,8 +2504,8 @@ private int RetrieveKeyInfoFromStatistics(QualifiedTableName qualifiedTableName, bool partialcolumnset = false; int ordinal; int indexordinal; - IntPtr cbIndexLen = IntPtr.Zero; - IntPtr cbColnameLen = IntPtr.Zero; + IntPtr cbIndexLen; + IntPtr cbColnameLen; int keyColumns = 0; // devnote: this test is already done by calling method ... @@ -2788,7 +2781,7 @@ internal int GetOrdinalFromBaseColName(string? columnname, string? tablename) ((localcmdtext[1] == 's') || (localcmdtext[1] == 'S'))) { // aliased table, skip the alias name - localcmdtext = tokenstmt.NextToken(); + tokenstmt.NextToken(); localcmdtext = tokenstmt.NextToken(); if ((localcmdtext.Length > 0) && (localcmdtext[0] == ',')) { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironmentHandle.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironmentHandle.cs index 07fa28c0884a8..3e4d63cccf386 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironmentHandle.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcEnvironmentHandle.cs @@ -14,7 +14,7 @@ public OdbcEnvironmentHandle() : base(ODBC32.SQL_HANDLE.ENV, null) //Set the expected driver manager version // - retcode = Interop.Odbc.SQLSetEnvAttr( + Interop.Odbc.SQLSetEnvAttr( this, ODBC32.SQL_ATTR.ODBC_VERSION, ODBC32.SQL_OV_ODBC3, diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs index 5c4cfbe5823b3..a15469babaf3d 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcHandle.cs @@ -171,14 +171,12 @@ protected override bool ReleaseHandle() if (null != parentHandle) { parentHandle.DangerousRelease(); - parentHandle = null; } return true; } internal ODBC32.SQLRETURN GetDiagnosticField(out string sqlState) { - short cbActual; // ODBC (MSDN) documents it expects a buffer large enough to hold 5(+L'\0') unicode characters StringBuilder sb = new StringBuilder(6); ODBC32.SQLRETURN retcode = Interop.Odbc.SQLGetDiagFieldW( @@ -188,7 +186,7 @@ internal ODBC32.SQLRETURN GetDiagnosticField(out string sqlState) ODBC32.SQL_DIAG_SQLSTATE, sb, checked((short)(2 * sb.Capacity)), // expects number of bytes, see \\kbinternal\kb\articles\294\1\69.HTM - out cbActual); + out _); ODBC.TraceODBC(3, "SQLGetDiagFieldW", retcode); if ((retcode == ODBC32.SQLRETURN.SUCCESS) || (retcode == ODBC32.SQLRETURN.SUCCESS_WITH_INFO)) { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs index f92e61e23acf0..8b4f0ae845e3d 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs @@ -181,7 +181,7 @@ private DataTable DataTableFromDataReader(IDataReader reader, string tableName) private void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcDataReader dataReader, OdbcConnection connection) { - DataTable? schemaTable = null; + DataTable? schemaTable; // // Build a DataTable from the reader diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs index 6df1b3c9ec9d5..f3c8d232268cb 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs @@ -445,7 +445,6 @@ internal string NextToken() break; } } - endtoken = true; break; } } diff --git a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs index afce7a7dbc3a3..88addb2db1156 100644 --- a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs +++ b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs @@ -391,7 +391,7 @@ protected internal virtual string Expand() internal string? ExpandDataDirectories(ref string? filename, ref int position) { - string? value = null; + string? value; StringBuilder builder = new StringBuilder(_usersConnectionString.Length); string? datadir = null; diff --git a/src/libraries/System.Data.OleDb/src/DbPropSet.cs b/src/libraries/System.Data.OleDb/src/DbPropSet.cs index 6d462d9970c24..7a79d06c492a0 100644 --- a/src/libraries/System.Data.OleDb/src/DbPropSet.cs +++ b/src/libraries/System.Data.OleDb/src/DbPropSet.cs @@ -99,10 +99,9 @@ internal DBPropSet(UnsafeNativeMethods.ICommandProperties properties, PropertyID private void SetLastErrorInfo(OleDbHResult lastErrorHr) { // note: OleDbHResult is actually a simple wrapper over HRESULT with OLEDB-specific codes - UnsafeNativeMethods.IErrorInfo? errorInfo = null; string message = string.Empty; - OleDbHResult errorInfoHr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo + OleDbHResult errorInfoHr = UnsafeNativeMethods.GetErrorInfo(0, out UnsafeNativeMethods.IErrorInfo? errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo if ((errorInfoHr == OleDbHResult.S_OK) && (errorInfo != null)) { try diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index 7e456b936fba7..1a605f9e2c4fa 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -70,7 +70,7 @@ public override int ConnectionTimeout { get { - object? value = null; + object? value; if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_TIMEOUT); @@ -583,8 +583,7 @@ internal bool SupportSchemaRowset(Guid schema) // ErrorInfo object is to be checked regardless the hresult returned by the function called Exception? e = null; - UnsafeNativeMethods.IErrorInfo? errorInfo = null; - OleDbHResult hr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo + OleDbHResult hr = UnsafeNativeMethods.GetErrorInfo(0, out UnsafeNativeMethods.IErrorInfo? errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo if ((OleDbHResult.S_OK == hr) && (null != errorInfo)) { try diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs index e31ff207c5709..51b15e9ef6d70 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs @@ -243,7 +243,7 @@ private static int UdlPoolSize private static string? LoadStringFromStorage(string udlfilename) { - string? udlConnectionString = null; + string? udlConnectionString; Dictionary? udlcache = UDL._Pool; if ((null == udlcache) || !udlcache.TryGetValue(udlfilename, out udlConnectionString)) diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs index 7972bb788617e..eeccb6f1caf43 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs @@ -250,9 +250,8 @@ record = (adodb as UnsafeNativeMethods.ADORecordConstruction); { value[0] = DBNull.Value; - object recordsAffected; object nextresult; - OleDbHResult hr = ((UnsafeNativeMethods.Recordset15)adodb).NextRecordset(out recordsAffected, out nextresult); + OleDbHResult hr = ((UnsafeNativeMethods.Recordset15)adodb).NextRecordset(out _, out nextresult); if (0 > hr) { @@ -310,7 +309,7 @@ private int FillFromRecordset(object data, UnsafeNativeMethods.ADORecordsetConst incrementResultCount = false; IntPtr chapter; /*ODB.DB_NULL_HCHAPTER*/ - object? result = null; + object? result; try { result = recordset.get_Rowset(); @@ -368,7 +367,7 @@ private int FillFromRecordset(object data, UnsafeNativeMethods.ADORecordsetConst private int FillFromRecord(object data, UnsafeNativeMethods.ADORecordConstruction record, string srcTable) { - object? result = null; + object? result; try { result = record.get_Row(); diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 51186f08e09e7..966ec039781eb 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -1261,7 +1261,6 @@ internal void HasRowsRead() List? exceptions = null; if (null != imultipleResults) { - object result; IntPtr affected; OleDbHResult hr; @@ -1273,7 +1272,7 @@ internal void HasRowsRead() { break; } - hr = imultipleResults.GetResult(ADP.PtrZero, ODB.DBRESULTFLAG_DEFAULT, ref ODB.IID_NULL, out affected, out result); + hr = imultipleResults.GetResult(ADP.PtrZero, ODB.DBRESULTFLAG_DEFAULT, ref ODB.IID_NULL, out affected, out _); // If a provider doesn't support IID_NULL and returns E_NOINTERFACE we want to break out // of the loop without throwing an exception. Our behavior will match ADODB in that scenario @@ -1355,7 +1354,7 @@ public override bool NextResult() Debug.Assert(null == _irow, "NextResult: row loop check"); Debug.Assert(null == _irowset, "NextResult: rowset loop check"); - object? result = null; + object? result; OleDbHResult hr; IntPtr affected; diff --git a/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs b/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs index 03ddf25741551..d06d83e8d0bf0 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbEnumerator.cs @@ -34,7 +34,7 @@ internal static OleDbDataReader GetEnumeratorFromType(Type type) private static OleDbDataReader GetEnumeratorReader(object? value) { - NativeMethods.ISourcesRowset? srcrowset = null; + NativeMethods.ISourcesRowset? srcrowset; try { @@ -48,7 +48,6 @@ private static OleDbDataReader GetEnumeratorReader(object? value) { throw ODB.ISourcesRowsetNotSupported(); } - value = null; // still held by ISourcesRowset, reused for IRowset int propCount = 0; IntPtr propSets = ADP.PtrZero; diff --git a/src/libraries/System.Data.OleDb/src/OleDbError.cs b/src/libraries/System.Data.OleDb/src/OleDbError.cs index 9fa39bc0472e1..fe07229e52925 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbError.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbError.cs @@ -61,7 +61,7 @@ internal OleDbError(UnsafeNativeMethods.IErrorRecords errorRecords, int index) } UnsafeNativeMethods.ISQLErrorInfo sqlErrorInfo; - hr = errorRecords.GetCustomErrorObject(index, ref ODB.IID_ISQLErrorInfo, out sqlErrorInfo); + errorRecords.GetCustomErrorObject(index, ref ODB.IID_ISQLErrorInfo, out sqlErrorInfo); if (null != sqlErrorInfo) { diff --git a/src/libraries/System.Data.OleDb/src/OleDbException.cs b/src/libraries/System.Data.OleDb/src/OleDbException.cs index 31205aa04acd6..6bcead282f7f3 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbException.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbException.cs @@ -67,11 +67,8 @@ public OleDbErrorCollection Errors internal static OleDbException CreateException(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode, Exception? inner) { OleDbErrorCollection errors = new OleDbErrorCollection(errorInfo); - string? message = null; - string? source = null; - OleDbHResult hr = 0; - hr = errorInfo.GetDescription(out message); - hr = errorInfo.GetSource(out source); + errorInfo.GetDescription(out string? message); + errorInfo.GetSource(out string? source); int count = errors.Count; if (0 < errors.Count) diff --git a/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs b/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs index 4a169181f2b59..723e37ca1b65f 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbTransaction.cs @@ -27,13 +27,12 @@ private sealed class WrappedTransaction : WrappedIUnknown internal WrappedTransaction(UnsafeNativeMethods.ITransactionLocal transaction, int isolevel, out OleDbHResult hr) : base(transaction) { - int transactionLevel = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { - hr = transaction.StartTransaction(isolevel, 0, IntPtr.Zero, out transactionLevel); + hr = transaction.StartTransaction(isolevel, 0, IntPtr.Zero, out _); if (0 <= hr) { _mustComplete = true; diff --git a/src/libraries/System.Data.OleDb/src/RowBinding.cs b/src/libraries/System.Data.OleDb/src/RowBinding.cs index 80eb928349067..828900bc5778b 100644 --- a/src/libraries/System.Data.OleDb/src/RowBinding.cs +++ b/src/libraries/System.Data.OleDb/src/RowBinding.cs @@ -94,11 +94,10 @@ internal IntPtr DangerousGetDataPtr(int valueOffset) internal OleDbHResult CreateAccessor(UnsafeNativeMethods.IAccessor iaccessor, int flags, ColumnBinding[] bindings) { - OleDbHResult hr = 0; int[] rowBindStatus = new int[BindingCount()]; _iaccessor = iaccessor; - hr = iaccessor.CreateAccessor(flags, (IntPtr)rowBindStatus.Length, this, (IntPtr)_dataLength, out _accessorHandle, rowBindStatus); + OleDbHResult hr = iaccessor.CreateAccessor(flags, (IntPtr)rowBindStatus.Length, this, (IntPtr)_dataLength, out _accessorHandle, rowBindStatus); for (int k = 0; k < rowBindStatus.Length; ++k) { @@ -204,14 +203,13 @@ internal void SetVariantValue(int offset, object value) Debug.Assert(0 == offset % 8, "invalid alignment"); ValidateCheck(offset, 2 * ODB.SizeOf_Variant); - IntPtr buffer = ADP.PtrZero; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); - buffer = ADP.IntPtrOffset(DangerousGetHandle(), offset); + IntPtr buffer = ADP.IntPtrOffset(DangerousGetHandle(), offset); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -331,8 +329,7 @@ internal void CloseFromConnection() if ((ODB.DB_INVALID_HACCESSOR != accessorHandle) && (null != iaccessor)) { OleDbHResult hr; - int refcount; - hr = iaccessor.ReleaseAccessor(accessorHandle, out refcount); + hr = iaccessor.ReleaseAccessor(accessorHandle, out _); if (hr < 0) { // ignore any error msgs SafeNativeMethods.Wrapper.ClearErrorInfo(); diff --git a/src/libraries/System.Data.OleDb/src/SafeHandles.cs b/src/libraries/System.Data.OleDb/src/SafeHandles.cs index 1157f3e3a0580..534d865372aa1 100644 --- a/src/libraries/System.Data.OleDb/src/SafeHandles.cs +++ b/src/libraries/System.Data.OleDb/src/SafeHandles.cs @@ -665,9 +665,8 @@ internal static class NativeOledbWrapper { internal static unsafe OleDbHResult IChapteredRowsetReleaseChapter(System.IntPtr ptr, System.IntPtr chapter) { - OleDbHResult hr = OleDbHResult.E_UNEXPECTED; + OleDbHResult hr; IntPtr hchapter = chapter; - System.Data.Common.UnsafeNativeMethods.IChapteredRowset? chapteredRowset = null; RuntimeHelpers.PrepareConstrainedRegions(); try { } @@ -677,8 +676,8 @@ internal static unsafe OleDbHResult IChapteredRowsetReleaseChapter(System.IntPtr hr = (OleDbHResult)Marshal.QueryInterface(ptr, ref IID_IChapteredRowset, out var pChapteredRowset); if (pChapteredRowset != IntPtr.Zero) { - chapteredRowset = (System.Data.Common.UnsafeNativeMethods.IChapteredRowset)Marshal.GetObjectForIUnknown(pChapteredRowset); - hr = (OleDbHResult)chapteredRowset.ReleaseChapter(hchapter, out var refcount); + var chapteredRowset = (System.Data.Common.UnsafeNativeMethods.IChapteredRowset)Marshal.GetObjectForIUnknown(pChapteredRowset); + hr = (OleDbHResult)chapteredRowset.ReleaseChapter(hchapter, out _); Marshal.ReleaseComObject(chapteredRowset); Marshal.Release(pChapteredRowset); } @@ -688,8 +687,7 @@ internal static unsafe OleDbHResult IChapteredRowsetReleaseChapter(System.IntPtr internal static unsafe OleDbHResult ITransactionAbort(System.IntPtr ptr) { - OleDbHResult hr = OleDbHResult.E_UNEXPECTED; - ITransactionLocal? transactionLocal = null; + OleDbHResult hr; RuntimeHelpers.PrepareConstrainedRegions(); try { } @@ -699,7 +697,7 @@ internal static unsafe OleDbHResult ITransactionAbort(System.IntPtr ptr) hr = (OleDbHResult)Marshal.QueryInterface(ptr, ref IID_ITransactionLocal, out var pTransaction); if (pTransaction != IntPtr.Zero) { - transactionLocal = (ITransactionLocal)Marshal.GetObjectForIUnknown(pTransaction); + ITransactionLocal transactionLocal = (ITransactionLocal)Marshal.GetObjectForIUnknown(pTransaction); hr = (OleDbHResult)transactionLocal.Abort(IntPtr.Zero, false, false); Marshal.ReleaseComObject(transactionLocal); Marshal.Release(pTransaction); @@ -710,8 +708,7 @@ internal static unsafe OleDbHResult ITransactionAbort(System.IntPtr ptr) internal static unsafe OleDbHResult ITransactionCommit(System.IntPtr ptr) { - OleDbHResult hr = OleDbHResult.E_UNEXPECTED; - ITransactionLocal? transactionLocal = null; + OleDbHResult hr; RuntimeHelpers.PrepareConstrainedRegions(); try { } @@ -721,7 +718,7 @@ internal static unsafe OleDbHResult ITransactionCommit(System.IntPtr ptr) hr = (OleDbHResult)Marshal.QueryInterface(ptr, ref IID_ITransactionLocal, out var pTransaction); if (pTransaction != IntPtr.Zero) { - transactionLocal = (ITransactionLocal)Marshal.GetObjectForIUnknown(pTransaction); + ITransactionLocal transactionLocal = (ITransactionLocal)Marshal.GetObjectForIUnknown(pTransaction); hr = (OleDbHResult)transactionLocal.Commit(false, (uint)XACTTC.XACTTC_SYNC_PHASETWO, 0); Marshal.ReleaseComObject(transactionLocal); Marshal.Release(pTransaction); diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs index d096b432bc808..aae9ec2029485 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs @@ -352,12 +352,11 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour throw ADP.InternalConnectionError(ADP.ConnectionError.ConnectionOptionsMissing); } - string expandedConnectionString = key.ConnectionString; if (null == userConnectionOptions) { // we only allow one expansion on the connection string userConnectionOptions = connectionOptions; - expandedConnectionString = connectionOptions.Expand(); + string expandedConnectionString = connectionOptions.Expand(); // if the expanded string is same instance (default implementation), the use the already created options if ((object)expandedConnectionString != (object)key.ConnectionString) @@ -432,8 +431,7 @@ internal DbMetaDataFactory GetMetaDataFactory(DbConnectionPoolGroup connectionPo // if two threads happen to hit this at the same time. One will be GC'd if (metaDataFactory == null) { - bool allowCache = false; - metaDataFactory = CreateMetaDataFactory(internalConnection, out allowCache); + metaDataFactory = CreateMetaDataFactory(internalConnection, out bool allowCache); if (allowCache) { connectionPoolGroup.MetaDataFactory = metaDataFactory; diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs index c7cacdaf6cabb..92f8137771f38 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs @@ -144,10 +144,8 @@ internal void AddWeakReference(object value, int tag) protected override DbCommand CreateDbCommand() { - DbCommand? command = null; - DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory; - command = providerFactory.CreateCommand()!; + DbCommand? command = providerFactory.CreateCommand()!; command.Connection = this; return command; } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs index 7aa55a95e73d6..d37dd9fc07a70 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionInternal.Shared.cs @@ -486,7 +486,7 @@ protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnect // ?->Connecting: prevent set_ConnectionString during Open if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) { - DbConnectionInternal? openConnection = null; + DbConnectionInternal? openConnection; try { connectionFactory.PermissionDemand(outerConnection); diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs index 521ea909f11da..e1ba5c74bfa59 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs @@ -1346,7 +1346,7 @@ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal o private DbConnectionInternal? GetFromGeneralPool() { - DbConnectionInternal? obj = null; + DbConnectionInternal? obj; if (!_stackNew.TryPop(out obj)) { diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs index 245209ce74842..015511d792f4c 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs @@ -238,8 +238,6 @@ protected DbConnectionPoolCounters(string? categoryName, string? categoryHelp) // SxS: this method uses GetCurrentProcessId to construct the instance name. private string GetInstanceName() { - string? result = null; - string? instanceName = GetAssemblyName(); // instance perfcounter name if (ADP.IsEmpty(instanceName)) @@ -257,7 +255,7 @@ private string GetInstanceName() // to PERFMON. They recommend that we translate them as shown below, to // prevent problems. - result = $"{instanceName}[{pid}]"; + string result = $"{instanceName}[{pid}]"; result = result.Replace('(', '[').Replace(')', ']').Replace('#', '_').Replace('/', '_').Replace('\\', '_'); // counter instance name cannot be greater than 127 diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs index c0f8270865f52..559e9d31711cd 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs @@ -47,11 +47,10 @@ private static byte[] CreateWellKnownSid(WellKnownSidType sidType) // not having to P/Invoke twice (once to get the buffer, once to get the data) uint length = (uint)SecurityIdentifier.MaxBinaryLength; - byte[] resultSid = new byte[length]; // NOTE - We copied this code from System.Security.Principal.Win32.CreateWellKnownSid... - if (0 == UnsafeNativeMethods.CreateWellKnownSid((int)sidType, null, out resultSid, ref length)) + if (0 == UnsafeNativeMethods.CreateWellKnownSid((int)sidType, null, out byte[] resultSid, ref length)) { IntegratedSecurityError(Win32_CreateWellKnownSid); } diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs index f9a4d529da0f4..2361fc26095c6 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -204,7 +204,6 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest if (reader != null) { reader.Dispose(); - reader = null; } } @@ -215,7 +214,6 @@ private DataColumn[] FilterColumns(DataTable sourceTable, string[]? hiddenColumn { DataColumn newDestinationColumn; int currentColumn; - DataColumn[]? filteredSourceColumns = null; int columnCount = 0; foreach (DataColumn sourceColumn in sourceTable.Columns) @@ -232,7 +230,7 @@ private DataColumn[] FilterColumns(DataTable sourceTable, string[]? hiddenColumn } currentColumn = 0; - filteredSourceColumns = new DataColumn[columnCount]; + var filteredSourceColumns = new DataColumn[columnCount]; foreach (DataColumn sourceColumn in sourceTable.Columns) { @@ -362,13 +360,12 @@ private void FixUpVersion(DataTable dataSourceInfoTable) private string GetParameterName(string neededCollectionName, int neededRestrictionNumber) { - DataTable? restrictionsTable = null; - DataColumnCollection? restrictionColumns = null; + DataTable? restrictionsTable; + DataColumnCollection? restrictionColumns; DataColumn? collectionName = null; DataColumn? parameterName = null; DataColumn? restrictionName = null; DataColumn? restrictionNumber = null; - ; string? result = null; restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions]; @@ -416,13 +413,11 @@ public virtual DataTable GetSchema(DbConnection connection, string collectionNam DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections]!; DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism]!; DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName]!; - DataRow? requestedCollectionRow = null; - DataTable? requestedSchema = null; string[]? hiddenColumns; - string? exactCollectionName = null; + DataTable? requestedSchema; - requestedCollectionRow = FindMetaDataCollectionRow(collectionName); - exactCollectionName = (requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string)!; + DataRow? requestedCollectionRow = FindMetaDataCollectionRow(collectionName); + string exactCollectionName = (requestedCollectionRow[collectionNameColumn, DataRowVersion.Current] as string)!; if (ADP.IsEmptyArray(restrictions) == false) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/ref/System.Diagnostics.DiagnosticSourceActivity.cs b/src/libraries/System.Diagnostics.DiagnosticSource/ref/System.Diagnostics.DiagnosticSourceActivity.cs index fd218a7dbf9df..a94fb9e380da8 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/ref/System.Diagnostics.DiagnosticSourceActivity.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/ref/System.Diagnostics.DiagnosticSourceActivity.cs @@ -25,6 +25,7 @@ public string? Id } public bool IsAllDataRequested { get { throw null; } set { throw null; } } + public bool IsStopped { get { throw null; } } public System.Diagnostics.ActivityIdFormat IdFormat { get { throw null; } } public System.Diagnostics.ActivityKind Kind { get { throw null; } } public string OperationName { get { throw null; } } @@ -214,6 +215,7 @@ public readonly struct ActivityEvent public string? TraceState { get { throw null; } } public bool IsRemote { get { throw null; } } public static bool TryParse(string? traceParent, string? traceState, out System.Diagnostics.ActivityContext context) { throw null; } + public static bool TryParse(string? traceParent, string? traceState, bool isRemote, out System.Diagnostics.ActivityContext context) { throw null; } public static System.Diagnostics.ActivityContext Parse(string traceParent, string? traceState) { throw null; } public static bool operator ==(System.Diagnostics.ActivityContext left, System.Diagnostics.ActivityContext right) { throw null; } public static bool operator !=(System.Diagnostics.ActivityContext left, System.Diagnostics.ActivityContext right) { throw null; } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs index 72c8a20bb7745..49bfc440d59b3 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs @@ -684,9 +684,9 @@ public void Stop() return; } - if (!IsFinished) + if (!IsStopped) { - IsFinished = true; + IsStopped = true; if (Duration == TimeSpan.Zero) { @@ -920,7 +920,7 @@ private static bool IsW3CId(string id) #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif - internal static bool TryConvertIdToContext(string traceParent, string? traceState, out ActivityContext context) + internal static bool TryConvertIdToContext(string traceParent, string? traceState, bool isRemote, out ActivityContext context) { context = default; if (!IsW3CId(traceParent)) @@ -941,7 +941,8 @@ internal static bool TryConvertIdToContext(string traceParent, string? traceStat new ActivityTraceId(traceIdSpan.ToString()), new ActivitySpanId(spanIdSpan.ToString()), (ActivityTraceFlags) ActivityTraceId.HexByteFromChars(traceParent[53], traceParent[54]), - traceState); + traceState, + isRemote); return true; } @@ -951,7 +952,7 @@ internal static bool TryConvertIdToContext(string traceParent, string? traceStat /// public void Dispose() { - if (!IsFinished) + if (!IsStopped) { Stop(); } @@ -1232,7 +1233,7 @@ private static unsafe long GetRandomNumber() private static bool ValidateSetCurrent(Activity? activity) { - bool canSet = activity == null || (activity.Id != null && !activity.IsFinished); + bool canSet = activity == null || (activity.Id != null && !activity.IsStopped); if (!canSet) { NotifyError(new InvalidOperationException(SR.ActivityNotRunning)); @@ -1298,18 +1299,24 @@ private bool W3CIdFlagsSet get => (_w3CIdFlags & ActivityTraceFlagsIsSet) != 0; } - private bool IsFinished + /// + /// Indicates whether this object is stopped + /// + /// + /// When subscribing to stop event using , the received object in the event callback will have as true. + /// + public bool IsStopped { - get => (_state & State.IsFinished) != 0; - set + get => (_state & State.IsStopped) != 0; + private set { if (value) { - _state |= State.IsFinished; + _state |= State.IsStopped; } else { - _state &= ~State.IsFinished; + _state &= ~State.IsStopped; } } } @@ -1623,7 +1630,7 @@ private enum State : byte FormatW3C = 0b_0_00000_10, FormatFlags = 0b_0_00000_11, - IsFinished = 0b_1_00000_00, + IsStopped = 0b_1_00000_00, } } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs index 93661f5d84135..55cacc67053ea 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/ActivityContext.cs @@ -65,8 +65,9 @@ public ActivityContext(ActivityTraceId traceId, ActivitySpanId spanId, ActivityT /// /// W3C trace parent header. /// W3C trace state. + /// Indicate the context is propagated from remote parent. /// The ActivityContext object created from the parsing operation. - public static bool TryParse(string? traceParent, string? traceState, out ActivityContext context) + public static bool TryParse(string? traceParent, string? traceState, bool isRemote, out ActivityContext context) { if (traceParent is null) { @@ -74,9 +75,17 @@ public static bool TryParse(string? traceParent, string? traceState, out Activit return false; } - return Activity.TryConvertIdToContext(traceParent, traceState, out context); + return Activity.TryConvertIdToContext(traceParent, traceState, isRemote, out context); } + /// + /// Parse W3C trace context headers to ActivityContext object. + /// + /// W3C trace parent header. + /// W3C trace state. + /// The ActivityContext object created from the parsing operation. + public static bool TryParse(string? traceParent, string? traceState, out ActivityContext context) => TryParse(traceParent, traceState, isRemote: false, out context); + /// /// Parse W3C trace context headers to ActivityContext object. /// @@ -92,7 +101,7 @@ public static ActivityContext Parse(string traceParent, string? traceState) throw new ArgumentNullException(nameof(traceParent)); } - if (!Activity.TryConvertIdToContext(traceParent, traceState, out ActivityContext context)) + if (!Activity.TryConvertIdToContext(traceParent, traceState, isRemote: false, out ActivityContext context)) { throw new ArgumentException(SR.InvalidTraceParent); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs index b598a75fa85e8..2dc1e539c2534 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs @@ -817,7 +817,7 @@ internal static void AddNewActivitySourceTransform(string filterAndPayloadSpec, activitySourceName = activitySourceName.Slice(0, plusSignIndex).Trim(); } - var transform = new FilterAndTransform(filterAndPayloadSpec, endIdx, colonIdx, activitySourceName.ToString(), activityName, supportedEvent, samplingResult, eventSource); + new FilterAndTransform(filterAndPayloadSpec, endIdx, colonIdx, activitySourceName.ToString(), activityName, supportedEvent, samplingResult, eventSource); } // Check if we are interested to listen to such ActivitySource diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/PassThroughPropagator.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/PassThroughPropagator.cs index 12515555fcf46..a8aec1bb72cfc 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/PassThroughPropagator.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/PassThroughPropagator.cs @@ -52,7 +52,7 @@ private static void GetRootId(out string? parentId, out string? traceState, out traceState = activity?.TraceStateString; parentId = activity?.ParentId ?? activity?.Id; - isW3c = parentId is not null ? Activity.TryConvertIdToContext(parentId, traceState, out _) : false; + isW3c = parentId is not null ? Activity.TryConvertIdToContext(parentId, traceState, isRemote: false, out _) : false; baggage = activity?.Baggage; } } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivitySourceTests.cs b/src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivitySourceTests.cs index edc695503c373..8468ce541c1b3 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivitySourceTests.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivitySourceTests.cs @@ -470,15 +470,32 @@ public void TestActivityContextParsing() Assert.Equal("e82825765f051b47", context.SpanId.ToHexString()); Assert.Equal(ActivityTraceFlags.Recorded, context.TraceFlags); Assert.Equal("k=v", context.TraceState); + Assert.False(context.IsRemote); + + Assert.True(ActivityContext.TryParse(w3cId, "k=v", isRemote: true, out context)); + Assert.Equal("99d43cb30a4cdb4fbeee3a19c29201b0", context.TraceId.ToHexString()); + Assert.Equal("e82825765f051b47", context.SpanId.ToHexString()); + Assert.Equal(ActivityTraceFlags.Recorded, context.TraceFlags); + Assert.Equal("k=v", context.TraceState); + Assert.True(context.IsRemote); + + Assert.True(ActivityContext.TryParse(w3cId, "k=v", isRemote: false, out context)); + Assert.Equal("99d43cb30a4cdb4fbeee3a19c29201b0", context.TraceId.ToHexString()); + Assert.Equal("e82825765f051b47", context.SpanId.ToHexString()); + Assert.Equal(ActivityTraceFlags.Recorded, context.TraceFlags); + Assert.Equal("k=v", context.TraceState); + Assert.False(context.IsRemote); context = ActivityContext.Parse(w3cId, "k=v"); Assert.Equal("99d43cb30a4cdb4fbeee3a19c29201b0", context.TraceId.ToHexString()); Assert.Equal("e82825765f051b47", context.SpanId.ToHexString()); Assert.Equal(ActivityTraceFlags.Recorded, context.TraceFlags); Assert.Equal("k=v", context.TraceState); + Assert.False(context.IsRemote); context = ActivityContext.Parse(w3cId, null); Assert.Null(context.TraceState); + Assert.False(context.IsRemote); Assert.False(ActivityContext.TryParse(null, "k=v", out context)); Assert.Throws(() => ActivityContext.Parse(null, null)); @@ -486,6 +503,8 @@ public void TestActivityContextParsing() const string invalidW3CContext = "00-Z9d43cb30a4cdb4fbeee3a19c29201b0-e82825765f051b47-01"; Assert.False(ActivityContext.TryParse(invalidW3CContext, null, out context)); + Assert.False(ActivityContext.TryParse(invalidW3CContext, null, isRemote: true, out context)); + Assert.False(ActivityContext.TryParse(invalidW3CContext, null, isRemote: false, out context)); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs b/src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs index 2ac5efa2d9fad..6b2a0c8aecf5e 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs @@ -299,7 +299,6 @@ public void ActivityIdOverflow() Assert.Equal('#', activity.Id[activity.Id.Length - 1]); } - /// /// Tests activity start and stop /// Checks Activity.Current correctness, Id generation @@ -320,6 +319,51 @@ public void StartStop() Assert.Null(Activity.Current); } + /// + /// Tests Activity.IsStopped + /// + [Fact] + public void IsStoppedTest() + { + using var activity = new Activity("activity"); + Assert.False(activity.IsStopped); + activity.Start(); + Assert.False(activity.IsStopped); + Assert.Equal(TimeSpan.Zero, activity.Duration); + activity.Stop(); + Assert.NotEqual(TimeSpan.Zero, activity.Duration); + Assert.True(activity.IsStopped); + + using var activity1 = new Activity("activity"); + Assert.False(activity1.IsStopped); + activity1.Start(); + Assert.False(activity1.IsStopped); + activity1.SetEndTime(DateTime.UtcNow.AddMinutes(1)); // Setting end time shouldn't mark the activity as stopped + Assert.False(activity1.IsStopped); + activity1.Stop(); + Assert.True(activity1.IsStopped); + + // + // Validate when receiving Start/Stop Activity events + // + + using ActivitySource aSource = new ActivitySource("TestActivityIsStopped"); + using ActivityListener listener = new ActivityListener(); + + listener.ShouldListenTo = (activitySource) => activitySource.Name == "TestActivityIsStopped"; + listener.Sample = (ref ActivityCreationOptions activityOptions) => ActivitySamplingResult.AllData; + listener.ActivityStarted = a => Assert.False(a.IsStopped); + listener.ActivityStopped = a => Assert.True(a.IsStopped); + ActivitySource.AddActivityListener(listener); + Activity sourceActivity; + using (sourceActivity = aSource.StartActivity("a1")) + { + Assert.NotNull(sourceActivity); + Assert.False(sourceActivity.IsStopped); + } + Assert.True(sourceActivity.IsStopped); + } + /// /// Tests Id generation /// diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs index 543ef529123a5..6eab2a131f7e4 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -849,7 +849,7 @@ internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageN if (sb.Length > 0) { - int num = -1; + int num; if (int.TryParse(sb.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out num)) { largestNumber = Math.Max(largestNumber, num); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs index cb2031e37f104..cc4c6198e178c 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -661,7 +661,7 @@ internal string FormatMessageWrapper(string dllNameList, uint messageNum, string if (dllName == null || dllName.Length == 0) continue; - SafeLibraryHandle hModule = null; + SafeLibraryHandle hModule; if (IsOpen) { @@ -740,7 +740,7 @@ internal EventLogEntry[] GetAllEntries() buf = new byte[minBytesNeeded]; } success = Interop.Advapi32.ReadEventLog(readHandle, Interop.Advapi32.FORWARDS_READ | Interop.Advapi32.SEEK_READ, - oldestEntry + idx, buf, buf.Length, out bytesRead, out minBytesNeeded); + oldestEntry + idx, buf, buf.Length, out bytesRead, out _); if (!success) break; } @@ -873,16 +873,14 @@ internal EventLogEntry GetEntryAtNoThrow(int index) private EventLogEntry GetEntryWithOldest(int index) { - EventLogEntry entry = null; int entryPos = GetCachedEntryPos(index); if (entryPos >= 0) { - entry = new EventLogEntry(cache, entryPos, this); - return entry; + return new EventLogEntry(cache, entryPos, this); } string currentMachineName = this.machineName; - int flags = 0; + int flags; if (GetCachedEntryPos(index + 1) < 0) { flags = Interop.Advapi32.FORWARDS_READ | Interop.Advapi32.SEEK_READ; @@ -919,7 +917,7 @@ private EventLogEntry GetEntryWithOldest(int index) } } success = Interop.Advapi32.ReadEventLog(readHandle, Interop.Advapi32.FORWARDS_READ | Interop.Advapi32.SEEK_READ, index, - cache, cache.Length, out bytesRead, out minBytesNeeded); + cache, cache.Length, out bytesRead, out _); } if (!success) diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs index ce2ad31f7e81f..d42d20e7a0109 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogReader.cs @@ -303,21 +303,18 @@ public IList LogStatus { get { - List list = null; - string[] channelNames = null; - int[] errorStatuses = null; EventLogHandle queryHandle = _handle; if (queryHandle.IsInvalid) throw new InvalidOperationException(); - channelNames = (string[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames); - errorStatuses = (int[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses); + string[] channelNames = (string[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryNames); + int[] errorStatuses = (int[])NativeWrapper.EvtGetQueryInfo(queryHandle, UnsafeNativeMethods.EvtQueryPropertyId.EvtQueryStatuses); if (channelNames.Length != errorStatuses.Length) throw new InvalidOperationException(); - list = new List(channelNames.Length); + var list = new List(channelNames.Length); for (int i = 0; i < channelNames.Length; i++) { EventLogStatus cs = new EventLogStatus(channelNames[i], errorStatuses[i]); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs index 0d8da98aea5b6..285359ddd591f 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/EventLogSession.cs @@ -242,8 +242,6 @@ public void ExportLogAndMessages(string path, PathType pathType, string query, s public void ExportLogAndMessages(string path, PathType pathType, string query, string targetFilePath, bool tolerateQueryErrors, CultureInfo targetCultureInfo) { - if (targetCultureInfo == null) - targetCultureInfo = CultureInfo.CurrentCulture; ExportLog(path, pathType, query, targetFilePath, tolerateQueryErrors); // Ignore the CultureInfo, pass 0 to use the calling thread's locale NativeWrapper.EvtArchiveExportedLog(this.Handle, targetFilePath, 0, 0); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs index 35ee7fefbc9bd..5b116fb59d249 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs @@ -862,7 +862,7 @@ public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandle contextHandle, EventLogHandle eventHandle) { IntPtr buffer = IntPtr.Zero; - IntPtr pointer = IntPtr.Zero; + IntPtr pointer; int bufferNeeded; int propCount; UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; diff --git a/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs b/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs index ce77b52cc6785..4b575173e1fa6 100644 --- a/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs +++ b/src/libraries/System.Diagnostics.FileVersionInfo/src/System/Diagnostics/FileVersionInfo.Windows.cs @@ -70,10 +70,7 @@ private static string ConvertTo8DigitHex(uint value) private static Interop.Version.VS_FIXEDFILEINFO GetFixedFileInfo(IntPtr memPtr) { - IntPtr memRef = IntPtr.Zero; - uint memLen; - - if (Interop.Version.VerQueryValue(memPtr, "\\", out memRef, out memLen)) + if (Interop.Version.VerQueryValue(memPtr, "\\", out IntPtr memRef, out _)) { return (Interop.Version.VS_FIXEDFILEINFO)Marshal.PtrToStructure(memRef); } @@ -93,10 +90,7 @@ private static unsafe string GetFileVersionLanguage(IntPtr memPtr) private static string GetFileVersionString(IntPtr memPtr, string name) { - IntPtr memRef = IntPtr.Zero; - uint memLen; - - if (Interop.Version.VerQueryValue(memPtr, name, out memRef, out memLen)) + if (Interop.Version.VerQueryValue(memPtr, name, out IntPtr memRef, out _)) { if (memRef != IntPtr.Zero) { @@ -109,10 +103,7 @@ private static string GetFileVersionString(IntPtr memPtr, string name) private static uint GetVarEntry(IntPtr memPtr) { - IntPtr memRef = IntPtr.Zero; - uint memLen; - - if (Interop.Version.VerQueryValue(memPtr, "\\VarFileInfo\\Translation", out memRef, out memLen)) + if (Interop.Version.VerQueryValue(memPtr, "\\VarFileInfo\\Translation", out IntPtr memRef, out _)) { return (uint)((Marshal.ReadInt16(memRef) << 16) + Marshal.ReadInt16((IntPtr)((long)memRef + 2))); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs index 00dbe615d66bc..87da3cd584107 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs @@ -575,9 +575,8 @@ public float NextValue() { //No need to initialize or Demand, since NextSample already does. CounterSample newSample = NextSample(); - float retVal = 0.0f; - retVal = CounterSample.Calculate(_oldSample, newSample); + float retVal = CounterSample.Calculate(_oldSample, newSample); _oldSample = newSample; return retVal; diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs index 43d92d2c5729b..8112fd21b4009 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs @@ -257,9 +257,7 @@ private static string SymbolFilePath { if (s_symbolFilePath == null) { - string tempPath; - - tempPath = Path.GetTempPath(); + Path.GetTempPath(); try { @@ -838,13 +836,11 @@ private CategorySample GetCategorySample(string category) if (entry == null) return null; - CategorySample sample = null; byte[] dataRef = GetPerformanceData(entry.NameIndex.ToString(CultureInfo.InvariantCulture), usePool: true); if (dataRef == null) throw new InvalidOperationException(SR.Format(SR.CantReadCategory, category)); - sample = new CategorySample(dataRef, entry, this); - return sample; + return new CategorySample(dataRef, entry, this); } internal static string[] GetCounters(string machine, string category) @@ -1169,17 +1165,13 @@ internal static bool IsBaseCounter(int type) private bool IsCustomCategory(string category) { - PerformanceCounterCategoryType categoryType; - - return FindCustomCategory(category, out categoryType); + return FindCustomCategory(category, out _); } internal static PerformanceCounterCategoryType GetCategoryType(string machine, string category) { - PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown; - PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); - if (!library.FindCustomCategory(category, out categoryType)) + if (!library.FindCustomCategory(category, out PerformanceCounterCategoryType categoryType)) { if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { @@ -1233,7 +1225,7 @@ private static void RegisterFiles(string arg0, bool unregister) else processStartInfo.FileName = Environment.SystemDirectory + "\\lodctr.exe"; - int res = 0; + int res; try { processStartInfo.Arguments = "\"" + arg0 + "\""; @@ -1324,7 +1316,6 @@ internal byte[] GetData(string item, bool usePool) { int waitRetries = 17; //2^16*10ms == approximately 10mins int waitSleep = 0; - byte[] data = null; int error = 0; // no need to revert here since we'll fall off the end of the method @@ -1332,8 +1323,7 @@ internal byte[] GetData(string item, bool usePool) { try { - data = perfDataKey.GetValue(item, usePool); - return data; + return perfDataKey.GetValue(item, usePool); } catch (IOException e) { diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceDataRegistryKey.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceDataRegistryKey.cs index 565966abab34c..98ef10aa35379 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceDataRegistryKey.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceDataRegistryKey.cs @@ -24,8 +24,7 @@ private PerformanceDataRegistryKey(SafeRegistryHandle hkey) public static PerformanceDataRegistryKey OpenRemoteBaseKey(string machineName) { // connect to the specified remote registry - SafeRegistryHandle foreignHKey = null; - int ret = Interop.Advapi32.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr(PerformanceData), ownsHandle: false), out foreignHKey); + int ret = Interop.Advapi32.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr(PerformanceData), ownsHandle: false), out SafeRegistryHandle foreignHKey); if (ret == Interop.Errors.ERROR_DLL_INIT_FAILED) { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.FreeBSD.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.FreeBSD.cs index 709fbba1fb7cf..3fe4314636d33 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.FreeBSD.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.FreeBSD.cs @@ -90,8 +90,7 @@ private unsafe int ParentProcessId // Gets execution path private string? GetPathToOpenFile() { - Interop.Sys.FileStatus stat; - if (Interop.Sys.Stat("/usr/local/bin/open", out stat) == 0) + if (Interop.Sys.Stat("/usr/local/bin/open", out _) == 0) { return "/usr/local/bin/open"; } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs index d764419939174..2a19a2de58777 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs @@ -266,8 +266,7 @@ private ProcessPriorityClass PriorityClassCore { EnsureState(State.HaveNonExitedId); - int pri = 0; - int errno = Interop.Sys.GetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, out pri); + int errno = Interop.Sys.GetPriority(Interop.Sys.PriorityWhich.PRIO_PROCESS, _processId, out int pri); if (errno != 0) // Interop.Sys.GetPriority returns GetLastWin32Error() { throw new Win32Exception(errno); // match Windows exception diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs index 482a627918fe4..5342d99272f4e 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessWaitState.Unix.cs @@ -307,8 +307,7 @@ internal bool HasExited { get { - int? ignored; - return GetExited(out ignored, refresh: true); + return GetExited(out _, refresh: true); } } @@ -679,8 +678,7 @@ internal static void CheckChildren(bool reapAll, bool configureConsole) { do { - int exitCode; - pid = Interop.Sys.WaitPidExitedNoHang(-1, out exitCode); + pid = Interop.Sys.WaitPidExitedNoHang(-1, out _); } while (pid > 0); } } diff --git a/src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs b/src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs index 801a328dc8b1b..604a34dc8cd2a 100644 --- a/src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs +++ b/src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs @@ -312,6 +312,15 @@ public void ToString_NullFrame_ThrowsNullReferenceException() Assert.Equal(Environment.NewLine, stackTrace.ToString()); } + [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/11354", TestRuntimes.Mono)] + public unsafe void ToString_FunctionPointerSignature() + { + // This is sepate from ToString_Invoke_ReturnsExpected since unsafe cannot be used for iterators + var stackTrace = FunctionPointerParameter(null); + Assert.Contains("System.Diagnostics.Tests.StackTraceTests.FunctionPointerParameter(IntPtr x)", stackTrace.ToString()); + } + [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void ToString_ShowILOffset() { @@ -384,6 +393,9 @@ public void ToString_ShowILOffset() [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace TwoParameters(int x, string y) => new StackTrace(); + [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] + private unsafe static StackTrace FunctionPointerParameter(delegate* x) => new StackTrace(); + [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] private static StackTrace Generic() => new StackTrace(); [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] diff --git a/src/libraries/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj b/src/libraries/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj index d6d002664cfef..aec1d92763946 100644 --- a/src/libraries/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj +++ b/src/libraries/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj @@ -3,6 +3,7 @@ $(NetCoreAppCurrent) true true + true true diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj b/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj index 0c0804cfc6f10..ff38f3d644c70 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj @@ -7,7 +7,7 @@ - $(NoWarn);CA1845;CA1846 + $(NoWarn);CA1845;CA1846;IDE0059 annotations true true diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Linux.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Linux.cs index 1cbda9c7cd4c0..7c4b96ba43753 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Linux.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.Linux.cs @@ -12,9 +12,8 @@ private static int DecodeBitStringHelper(ArrayList resultList, SafeBerHandle ber // Windows doesn't really decode BitStrings correctly, and wldap32 will internally treat it as 'O' Octet string. // In order to match behavior, in Linux we will interpret 'B' as 'O' when passing the call to libldap. - int error = 0; // return BerVal - byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', ref error); + byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', out int error); if (!BerPal.IsBerDecodeError(error)) { // add result to the list diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs index b1ca5e02eb6b4..1b91fd7c4de76 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs @@ -166,7 +166,7 @@ public static byte[] Encode(string format, params object[] value) } string[] stringValues = (string[])value[valueCount]; - byte[][] tempValues = null; + byte[][] tempValues; if (stringValues != null) { tempValues = new byte[stringValues.Length][]; @@ -338,7 +338,7 @@ internal static object[] TryDecode(string format, byte[] value, out bool decodeS Marshal.FreeHGlobal(berValue.bv_val); } - int error = 0; + int error; for (int formatCount = 0; formatCount < format.Length; formatCount++) { @@ -360,7 +360,7 @@ internal static object[] TryDecode(string format, byte[] value, out bool decodeS if (fmt == 'b') { // should return a bool - bool boolResult = false; + bool boolResult; if (result == 0) boolResult = false; else @@ -378,7 +378,7 @@ internal static object[] TryDecode(string format, byte[] value, out bool decodeS else if (fmt == 'a') { // return a string - byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', ref error); + byte[] byteArray = DecodingByteArrayHelper(berElement, 'O', out error); if (!BerPal.IsBerDecodeError(error)) { string s = null; @@ -391,7 +391,7 @@ internal static object[] TryDecode(string format, byte[] value, out bool decodeS else if (fmt == 'O') { // return BerVal - byte[] byteArray = DecodingByteArrayHelper(berElement, fmt, ref error); + byte[] byteArray = DecodingByteArrayHelper(berElement, fmt, out error); if (!BerPal.IsBerDecodeError(error)) { // add result to the list @@ -405,10 +405,10 @@ internal static object[] TryDecode(string format, byte[] value, out bool decodeS else if (fmt == 'v') { //null terminate strings - byte[][] byteArrayresult = null; + byte[][] byteArrayresult; string[] stringArray = null; - byteArrayresult = DecodingMultiByteArrayHelper(berElement, 'V', ref error); + byteArrayresult = DecodingMultiByteArrayHelper(berElement, 'V', out error); if (!BerPal.IsBerDecodeError(error)) { if (byteArrayresult != null) @@ -432,9 +432,9 @@ internal static object[] TryDecode(string format, byte[] value, out bool decodeS } else if (fmt == 'V') { - byte[][] result = null; + byte[][] result; - result = DecodingMultiByteArrayHelper(berElement, fmt, ref error); + result = DecodingMultiByteArrayHelper(berElement, fmt, out error); if (!BerPal.IsBerDecodeError(error)) { resultList.Add(result); @@ -465,7 +465,7 @@ internal static object[] TryDecode(string format, byte[] value, out bool decodeS private static int EncodingByteArrayHelper(SafeBerHandle berElement, byte[] tempValue, char fmt, nuint tag) { - int error = 0; + int error; // one byte array, one int arguments if (tempValue != null) @@ -484,9 +484,8 @@ private static int EncodingByteArrayHelper(SafeBerHandle berElement, byte[] temp return error; } - private static byte[] DecodingByteArrayHelper(SafeBerHandle berElement, char fmt, ref int error) + private static byte[] DecodingByteArrayHelper(SafeBerHandle berElement, char fmt, out int error) { - error = 0; IntPtr result = IntPtr.Zero; BerVal binaryValue = new BerVal(); byte[] byteArray = null; @@ -522,7 +521,7 @@ private static byte[] DecodingByteArrayHelper(SafeBerHandle berElement, char fmt private static int EncodingMultiByteArrayHelper(SafeBerHandle berElement, byte[][] tempValue, char fmt, nuint tag) { IntPtr berValArray = IntPtr.Zero; - IntPtr tempPtr = IntPtr.Zero; + IntPtr tempPtr; BerVal[] managedBervalArray = null; int error = 0; @@ -590,14 +589,13 @@ private static int EncodingMultiByteArrayHelper(SafeBerHandle berElement, byte[] return error; } - private static byte[][] DecodingMultiByteArrayHelper(SafeBerHandle berElement, char fmt, ref int error) + private static byte[][] DecodingMultiByteArrayHelper(SafeBerHandle berElement, char fmt, out int error) { - error = 0; // several BerVal IntPtr ptrResult = IntPtr.Zero; int i = 0; ArrayList binaryList = new ArrayList(); - IntPtr tempPtr = IntPtr.Zero; + IntPtr tempPtr; byte[][] result = null; try diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs index 51b09c7d6d73b..c34f9a4e7cc5a 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs @@ -173,7 +173,7 @@ internal static void TransformControls(DirectoryControl[] controls) else if (controls[i].Type == "1.2.840.113556.1.4.474") { // The control is a SortControl. - int result = 0; + int result; string attribute = null; object[] o = BerConverter.TryDecode("{ea}", value, out bool decodeSucceeded); diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.Linux.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.Linux.cs index 6adf1ebac982c..49dfae1059f96 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.Linux.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.Linux.cs @@ -32,7 +32,7 @@ private int InternalConnectToServer() // available during init. Debug.Assert(!_ldapHandle.IsInvalid); - string scheme = null; + string scheme; LdapDirectoryIdentifier directoryIdentifier = (LdapDirectoryIdentifier)_directoryIdentifier; if (directoryIdentifier.Connectionless) { diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs index 7e8c81dc4afb0..69ceeeb774e2e 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs @@ -426,7 +426,7 @@ public void Abort(IAsyncResult asyncResult) throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } - int messageId = -1; + int messageId; LdapAsyncResult result = (LdapAsyncResult)asyncResult; if (!result._partialResults) @@ -1040,7 +1040,7 @@ private void BindHelper(NetworkCredential newCredential, bool needSetCredential) } // Set the credential. - NetworkCredential tempCredential = null; + NetworkCredential tempCredential; if (needSetCredential) { _directoryCredential = tempCredential = (newCredential != null ? new NetworkCredential(newCredential.UserName, newCredential.Password, newCredential.Domain) : null); @@ -1297,7 +1297,7 @@ internal LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList for (int i = 0; i < directoryAttributes.Count; i++) { // Get the managed attribute first. - DirectoryAttribute modAttribute = null; + DirectoryAttribute modAttribute; if (attributeCollection != null) { modAttribute = attributeCollection[i]; @@ -1334,7 +1334,7 @@ internal LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList berValues = new BerVal[valuesCount]; for (int j = 0; j < valuesCount; j++) { - byte[] byteArray = null; + byte[] byteArray; if (modAttribute[j] is string) { byteArray = encoder.GetBytes((string)modAttribute[j]); @@ -1362,10 +1362,10 @@ internal LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList attributes[i].values = Utility.AllocHGlobalIntPtrArray(valuesCount + 1); int structSize = Marshal.SizeOf(typeof(BerVal)); - IntPtr controlPtr = IntPtr.Zero; - IntPtr tempPtr = IntPtr.Zero; + IntPtr controlPtr; + IntPtr tempPtr; - int m = 0; + int m; for (m = 0; m < valuesCount; m++) { controlPtr = Marshal.AllocHGlobal(structSize); @@ -1396,7 +1396,7 @@ internal async ValueTask ConstructResponseAsync(int messageId IntPtr requestName = IntPtr.Zero; IntPtr requestValue = IntPtr.Zero; - IntPtr entryMessage = IntPtr.Zero; + IntPtr entryMessage; bool needAbandon = true; @@ -1827,7 +1827,7 @@ internal DirectoryAttribute ConstructAttribute(IntPtr entryMessage, IntPtr attri { BerVal bervalue = new BerVal(); Marshal.PtrToStructure(tempPtr, bervalue); - byte[] byteArray = null; + byte[] byteArray; if (bervalue.bv_len > 0 && bervalue.bv_val != IntPtr.Zero) { byteArray = new byte[bervalue.bv_len]; @@ -1861,7 +1861,7 @@ internal SearchResultReference ConstructReference(IntPtr referenceMessage) if (error == 0) { var referralList = new ArrayList(); - IntPtr tempPtr = IntPtr.Zero; + IntPtr tempPtr; int count = 0; if (referenceArray != IntPtr.Zero) { diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs index 9a200fc5ba218..fb2a71e51ed1b 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs @@ -1027,7 +1027,7 @@ private int ProcessDereferenceConnection(IntPtr PrimaryConnection, IntPtr Connec { if (ConnectionToDereference != IntPtr.Zero && _callbackRoutine.DereferenceConnection != null) { - LdapConnection dereferenceConnection = null; + LdapConnection dereferenceConnection; WeakReference reference = null; // in most cases it should be in our table diff --git a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj index 6384fde3186b9..71c695235a69e 100644 --- a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj +++ b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj @@ -6,7 +6,7 @@ - $(NoWarn);CA1845;CA1846 + $(NoWarn);CA1845;CA1846;IDE0059 enable true true diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs index 54b8e160ed1bb..e828ec3a9a5a4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs @@ -1280,7 +1280,7 @@ private ArrayList GetChildDomains() private ArrayList GetTrustsHelper(string? targetDomainName) { - string? serverName = null; + string? serverName; IntPtr domains = (IntPtr)0; int count = 0; ArrayList unmanagedTrustList = new ArrayList(); @@ -1288,7 +1288,7 @@ private ArrayList GetTrustsHelper(string? targetDomainName) int localDomainIndex = 0; string? localDomainParent = null; int error = 0; - bool impersonated = false; + bool impersonated; // first decide which server to go to if (context.isServer()) diff --git a/src/libraries/System.Drawing.Common/ref/System.Drawing.Common.netcoreapp.cs b/src/libraries/System.Drawing.Common/ref/System.Drawing.Common.netcoreapp.cs index 7c5f8f890a84d..f9d987de24d1c 100644 --- a/src/libraries/System.Drawing.Common/ref/System.Drawing.Common.netcoreapp.cs +++ b/src/libraries/System.Drawing.Common/ref/System.Drawing.Common.netcoreapp.cs @@ -8,6 +8,8 @@ namespace System.Drawing { public sealed partial class Graphics { + public void DrawRectangle(System.Drawing.Pen pen, System.Drawing.RectangleF rect) { } + public void FillPie(System.Drawing.Brush brush, System.Drawing.RectangleF rect, float startAngle, float sweepAngle) { } public System.Numerics.Matrix3x2 TransformElements { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.cs index 7cacab64ba5eb..581219b060261 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Bitmap.cs @@ -30,7 +30,7 @@ public Bitmap(string filename, bool useIcm) // so if the app's default directory changes we won't get an error. filename = Path.GetFullPath(filename); - IntPtr bitmap = IntPtr.Zero; + IntPtr bitmap; int status; if (useIcm) @@ -88,7 +88,7 @@ public Bitmap(int width, int height, Graphics g) throw new ArgumentNullException(nameof(g)); } - IntPtr bitmap = IntPtr.Zero; + IntPtr bitmap; int status = Gdip.GdipCreateBitmapFromGraphics(width, height, new HandleRef(g, g.NativeGraphics), out bitmap); Gdip.CheckStatus(status); @@ -97,7 +97,7 @@ public Bitmap(int width, int height, Graphics g) public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0) { - IntPtr bitmap = IntPtr.Zero; + IntPtr bitmap; int status = Gdip.GdipCreateBitmapFromScan0(width, height, stride, unchecked((int)format), scan0, out bitmap); Gdip.CheckStatus(status); @@ -106,7 +106,7 @@ public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan public Bitmap(int width, int height, PixelFormat format) { - IntPtr bitmap = IntPtr.Zero; + IntPtr bitmap; int status = Gdip.GdipCreateBitmapFromScan0(width, height, 0, unchecked((int)format), IntPtr.Zero, out bitmap); Gdip.CheckStatus(status); @@ -163,7 +163,7 @@ public static Bitmap FromResource(IntPtr hinstance, string bitmapName) [EditorBrowsable(EditorBrowsableState.Advanced)] public IntPtr GetHbitmap(Color background) { - IntPtr hBitmap = IntPtr.Zero; + IntPtr hBitmap; int status = Gdip.GdipCreateHBITMAPFromBitmap(new HandleRef(this, nativeImage), out hBitmap, ColorTranslator.ToWin32(background)); if (status == 2 /* invalid parameter*/ && (Width >= short.MaxValue || Height >= short.MaxValue)) @@ -179,7 +179,7 @@ public IntPtr GetHbitmap(Color background) [EditorBrowsable(EditorBrowsableState.Advanced)] public IntPtr GetHicon() { - IntPtr hIcon = IntPtr.Zero; + IntPtr hIcon; int status = Gdip.GdipCreateHICONFromBitmap(new HandleRef(this, nativeImage), out hIcon); Gdip.CheckStatus(status); @@ -193,7 +193,7 @@ public Bitmap Clone(RectangleF rect, PixelFormat format) throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString())); } - IntPtr dstHandle = IntPtr.Zero; + IntPtr dstHandle; int status = Gdip.GdipCloneBitmapArea( rect.X, @@ -297,7 +297,7 @@ public Color GetPixel(int x, int y) throw new ArgumentOutOfRangeException(nameof(y), SR.ValidRangeY); } - int color = 0; + int color; int status = Gdip.GdipBitmapGetPixel(new HandleRef(this, nativeImage), x, y, out color); Gdip.CheckStatus(status); @@ -337,7 +337,7 @@ public Bitmap Clone(Rectangle rect, PixelFormat format) throw new ArgumentException(SR.Format(SR.GdiplusInvalidRectangle, rect.ToString())); } - IntPtr dstHandle = IntPtr.Zero; + IntPtr dstHandle; int status = Gdip.GdipCloneBitmapAreaI( rect.X, rect.Y, diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Windows.cs index 0f492fc7bbd3e..4eb8e61eb2601 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Windows.cs @@ -139,7 +139,6 @@ private unsafe bool FillBitmapInfo(IntPtr hdc, IntPtr hpal, ref Interop.Gdi32.BI if (hbm != IntPtr.Zero) { Interop.Gdi32.DeleteObject(hbm); - hbm = IntPtr.Zero; } } return bRet; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs index 92a14ba4c3945..c34fe129b8a3c 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs @@ -35,7 +35,7 @@ internal HatchBrush(IntPtr nativeBrush) public override object Clone() { - IntPtr clonedBrush = IntPtr.Zero; + IntPtr clonedBrush; int status = Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out clonedBrush); Gdip.CheckStatus(status); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs index 8163d0eefb15e..9721c7ff5681f 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs @@ -72,7 +72,7 @@ private void CreateFont(string familyName, float emSize, FontStyle style, Graphi internal void unitConversion(GraphicsUnit fromUnit, GraphicsUnit toUnit, float nSrc, out float nTrg) { - float inchs = 0; + float inchs; nTrg = 0; switch (fromUnit) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs index ace1758b4d577..41a39db24d23d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs @@ -128,7 +128,7 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina char separator = culture.TextInfo.ListSeparator[0]; // For vi-VN: ',' string fontName = font; // start with the assumption that only the font name was provided. string? style = null; - string? sizeStr = null; + string? sizeStr; float fontSize = 8.25f; FontStyle fontStyle = FontStyle.Regular; GraphicsUnit units = GraphicsUnit.Point; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs index 51c451037168d..bfd28aeeb6e27 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/FontFamily.cs @@ -68,7 +68,7 @@ internal FontFamily(string name, bool createDefaultOnFail) // Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them. private void CreateFontFamily(string name, FontCollection? fontCollection) { - IntPtr fontfamily = IntPtr.Zero; + IntPtr fontfamily; IntPtr nativeFontCollection = (fontCollection == null) ? IntPtr.Zero : fontCollection._nativeFontCollection; int status = Gdip.GdipCreateFontFamilyFromName(name, new HandleRef(fontCollection, nativeFontCollection), out fontfamily); @@ -105,7 +105,7 @@ private void CreateFontFamily(string name, FontCollection? fontCollection) /// public FontFamily(GenericFontFamilies genericFamily) { - IntPtr nativeFamily = IntPtr.Zero; + IntPtr nativeFamily; int status; switch (genericFamily) @@ -204,7 +204,7 @@ public unsafe string GetName(int language) private static IntPtr GetGdipGenericSansSerif() { - IntPtr nativeFamily = IntPtr.Zero; + IntPtr nativeFamily; int status = Gdip.GdipGetGenericFontFamilySansSerif(out nativeFamily); Gdip.CheckStatus(status); @@ -253,7 +253,7 @@ public bool IsStyleAvailable(FontStyle style) /// public int GetEmHeight(FontStyle style) { - int result = 0; + int result; int status = Gdip.GdipGetEmHeight(new HandleRef(this, NativeFamily), style, out result); Gdip.CheckStatus(status); @@ -265,7 +265,7 @@ public int GetEmHeight(FontStyle style) /// public int GetCellAscent(FontStyle style) { - int result = 0; + int result; int status = Gdip.GdipGetCellAscent(new HandleRef(this, NativeFamily), style, out result); Gdip.CheckStatus(status); @@ -277,7 +277,7 @@ public int GetCellAscent(FontStyle style) /// public int GetCellDescent(FontStyle style) { - int result = 0; + int result; int status = Gdip.GdipGetCellDescent(new HandleRef(this, NativeFamily), style, out result); Gdip.CheckStatus(status); @@ -290,7 +290,7 @@ public int GetCellDescent(FontStyle style) /// public int GetLineSpacing(FontStyle style) { - int result = 0; + int result; int status = Gdip.GdipGetLineSpacing(new HandleRef(this, NativeFamily), style, out result); Gdip.CheckStatus(status); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/GdiPlusStreamHelper.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/GdiPlusStreamHelper.Unix.cs index fb55982f8068d..8013e23f54936 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/GdiPlusStreamHelper.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/GdiPlusStreamHelper.Unix.cs @@ -85,7 +85,7 @@ public unsafe int StreamGetBytesImpl(byte* buf, int bufsz, bool peek) if (bufsz <= 0) return 0; - int read = 0; + int read; long originalPosition = 0; if (peek) { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Gdiplus.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Gdiplus.cs index be0dd1f4b0a27..512dd06f3bfb0 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Gdiplus.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Gdiplus.cs @@ -30,7 +30,7 @@ static Gdip() // GDI+ ref counts multiple calls to Startup in the same process, so calls from multiple // domains are ok, just make sure to pair each w/GdiplusShutdown - int status = GdiplusStartup(out s_initToken, ref input, out StartupOutput output); + int status = GdiplusStartup(out s_initToken, ref input, out _); CheckStatus(status); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs index 1a85c2a79bd0d..cb74840b78e7b 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs @@ -30,7 +30,7 @@ internal static IntPtr LoadNativeLibrary() { var assembly = System.Reflection.Assembly.GetExecutingAssembly(); - IntPtr lib = IntPtr.Zero; + IntPtr lib; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { if (!NativeLibrary.TryLoad("libgdiplus.dylib", assembly, default, out lib)) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs index 4917e8f33d831..9bb60157e6158 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs @@ -382,7 +382,7 @@ public unsafe Matrix3x2 TransformElements public IntPtr GetHdc() { - IntPtr hdc = IntPtr.Zero; + IntPtr hdc; Gdip.CheckStatus(Gdip.GdipGetDC(new HandleRef(this, NativeGraphics), out hdc)); _nativeHdc = hdc; // need to cache the hdc to be able to release with a call to IDeviceContext.ReleaseHdc(). @@ -708,6 +708,16 @@ public void DrawBezier(Pen pen, Point pt1, Point pt2, Point pt3, Point pt4) DrawBezier(pen, pt1.X, pt1.Y, pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y); } + /// + /// Draws the outline of a rectangle specified by . + /// + /// A Pen that determines the color, width, and style of the rectangle. + /// A Rectangle structure that represents the rectangle to draw. + public void DrawRectangle(Pen pen, RectangleF rect) + { + DrawRectangle(pen, rect.X, rect.Y, rect.Width, rect.Height); + } + /// /// Draws the outline of a rectangle specified by . /// @@ -1325,6 +1335,18 @@ public void FillPie(Brush brush, Rectangle rect, float startAngle, float sweepAn FillPie(brush, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); } + /// + /// Fills the interior of a pie section defined by an ellipse and two radial lines. + /// + /// A Brush that determines the characteristics of the fill. + /// A Rectangle structure that represents the bounding rectangle that defines the ellipse from which the pie section comes. + /// Angle in degrees measured clockwise from the x-axis to the first side of the pie section. + /// Angle in degrees measured clockwise from the parameter to the second side of the pie section. + public void FillPie(Brush brush, RectangleF rect, float startAngle, float sweepAngle) + { + FillPie(brush, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle); + } + /// /// Fills the interior of a pie section defined by an ellipse and two radial lines. /// @@ -1544,8 +1566,8 @@ public SizeF MeasureString(string? text, Font font, PointF origin, StringFormat? ref layout, new HandleRef(stringFormat, stringFormat?.nativeFormat ?? IntPtr.Zero), ref boundingBox, - out int a, - out int b)); + out _, + out _)); return boundingBox.Size; } @@ -1570,8 +1592,8 @@ public SizeF MeasureString(string? text, Font font, SizeF layoutArea, StringForm ref layout, new HandleRef(stringFormat, stringFormat?.nativeFormat ?? IntPtr.Zero), ref boundingBox, - out int a, - out int b)); + out _, + out _)); return boundingBox.Size; } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs index bd14e2d73e7f7..9cb8421417051 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs @@ -545,10 +545,6 @@ internal Bitmap BuildBitmapOnWin32() BitmapInfoHeader bih = ii.iconHeader; int biHeight = bih.biHeight / 2; - int ncolors = (int)bih.biClrUsed; - if ((ncolors == 0) && (bih.biBitCount < 24)) - ncolors = (int)(1 << bih.biBitCount); - switch (bih.biBitCount) { case 1: diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs index 73e65b379fe57..1ee3b3705ecf1 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs @@ -314,8 +314,8 @@ private void DrawIcon(IntPtr dc, Rectangle imageRect, Rectangle targetRect, bool int imageHeight; int targetX = 0; int targetY = 0; - int targetWidth = 0; - int targetHeight = 0; + int targetWidth; + int targetHeight; Size cursorSize = Size; @@ -398,7 +398,6 @@ private static IntPtr SaveClipRgn(IntPtr hDC) if (result > 0) { hSaveRgn = hTempRgn; - hTempRgn = IntPtr.Zero; } else { @@ -811,7 +810,7 @@ private unsafe Bitmap BmpFrame() Size size = Size; bitmap = new Bitmap(size.Width, size.Height); // initialized to transparent - Graphics? graphics = null; + Graphics? graphics; using (graphics = Graphics.FromImage(bitmap)) { try diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs index 45504c00830ef..c12a369534938 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs @@ -328,7 +328,7 @@ protected virtual void Dispose(bool disposing) public object Clone() { - IntPtr newimage = IntPtr.Zero; + IntPtr newimage; int status = Gdip.GdipCloneImage(nativeImage, out newimage); Gdip.CheckStatus(status); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs index c359e7af7fdd3..b561398144222 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Windows.cs @@ -41,9 +41,7 @@ private IntPtr InitializeFromStream(Stream stream) nativeImage = image; - int type = -1; - - Gdip.CheckStatus(Gdip.GdipGetImageType(new HandleRef(this, nativeImage), out type)); + Gdip.CheckStatus(Gdip.GdipGetImageType(new HandleRef(this, nativeImage), out _)); EnsureSave(this, null, stream); return image; } @@ -71,7 +69,7 @@ private static unsafe IntPtr LoadGdipImageFromStream(GPStream stream, bool useEm /// public object Clone() { - IntPtr cloneImage = IntPtr.Zero; + IntPtr cloneImage; Gdip.CheckStatus(Gdip.GdipCloneImage(new HandleRef(this, nativeImage), out cloneImage)); ValidateImage(cloneImage); @@ -386,7 +384,7 @@ public ColorPalette Palette /// public Image GetThumbnailImage(int thumbWidth, int thumbHeight, GetThumbnailImageAbort? callback, IntPtr callbackData) { - IntPtr thumbImage = IntPtr.Zero; + IntPtr thumbImage; Gdip.CheckStatus(Gdip.GdipGetImageThumbnail( new HandleRef(this, nativeImage), diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs index 24977ec94a51f..c84a286c0df1b 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.cs @@ -109,7 +109,7 @@ public static Image FromFile(string filename, bool useEmbeddedColorManagement) // so if our app changes default directory we won't get an error filename = Path.GetFullPath(filename); - IntPtr image = IntPtr.Zero; + IntPtr image; if (useEmbeddedColorManagement) { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs index dca1674b2d536..cf64a391c60c0 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ImageAttributes.cs @@ -55,7 +55,7 @@ internal void SetNativeImageAttributes(IntPtr handle) /// public ImageAttributes() { - IntPtr newImageAttributes = IntPtr.Zero; + IntPtr newImageAttributes; int status = Gdip.GdipCreateImageAttributes(out newImageAttributes); @@ -126,7 +126,7 @@ private void Dispose(bool disposing) /// public object Clone() { - IntPtr clone = IntPtr.Zero; + IntPtr clone; int status = Gdip.GdipCloneImageAttributes( new HandleRef(this, nativeImageAttributes), @@ -443,7 +443,7 @@ public void SetRemapTable(ColorMap[] map) public void SetRemapTable(ColorMap[] map, ColorAdjustType type) { - int index = 0; + int index; int mapSize = map.Length; int size = 4; // Marshal.SizeOf(index.GetType()); IntPtr memory = Marshal.AllocHGlobal(checked(mapSize * size * 2)); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs index 3e23c5226b3bb..500ab7f54e6a2 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs @@ -63,7 +63,7 @@ public Metafile(IntPtr referenceHdc, EmfType emfType, string? description) /// public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string? desc) { - IntPtr metafile = IntPtr.Zero; + IntPtr metafile; if (frameRect.IsEmpty) { @@ -117,7 +117,7 @@ public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, Metaf // Called in order to emulate exception behavior from .NET Framework related to invalid file paths. Path.GetFullPath(fileName); - IntPtr metafile = IntPtr.Zero; + IntPtr metafile; if (frameRect.IsEmpty) { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Unix.cs index 4ac028d91dccf..42a552112e650 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Unix.cs @@ -21,7 +21,7 @@ public CustomLineCap CustomStartCap { get { - IntPtr lineCap = IntPtr.Zero; + IntPtr lineCap; int status = Gdip.GdipGetPenCustomStartCap(new HandleRef(this, NativePen), out lineCap); Gdip.CheckStatus(status); if (lineCap == IntPtr.Zero) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Windows.cs index 8f2a76b8f5824..6c295fe9b0033 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Windows.cs @@ -16,7 +16,7 @@ public CustomLineCap CustomStartCap { get { - IntPtr lineCap = IntPtr.Zero; + IntPtr lineCap; int status = Gdip.GdipGetPenCustomStartCap(new HandleRef(this, NativePen), out lineCap); Gdip.CheckStatus(status); @@ -42,7 +42,7 @@ public CustomLineCap CustomEndCap { get { - IntPtr lineCap = IntPtr.Zero; + IntPtr lineCap; int status = Gdip.GdipGetPenCustomEndCap(new HandleRef(this, NativePen), out lineCap); Gdip.CheckStatus(status); return CustomLineCap.CreateCustomLineCapObject(lineCap); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs index ca5d045000dd4..cf22eae646cd4 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Pen.cs @@ -91,7 +91,7 @@ public Pen(Brush brush, float width) throw new ArgumentNullException(nameof(brush)); } - IntPtr pen = IntPtr.Zero; + IntPtr pen; int status = Gdip.GdipCreatePen2(new HandleRef(brush, brush.NativeBrush), width, (int)GraphicsUnit.World, @@ -115,7 +115,7 @@ internal void SetNativePen(IntPtr nativePen) /// public object Clone() { - IntPtr clonedPen = IntPtr.Zero; + IntPtr clonedPen; int status = Gdip.GdipClonePen(new HandleRef(this, NativePen), out clonedPen); Gdip.CheckStatus(status); @@ -226,7 +226,7 @@ public LineCap StartCap { get { - int startCap = 0; + int startCap; int status = Gdip.GdipGetPenStartCap(new HandleRef(this, NativePen), out startCap); Gdip.CheckStatus(status); @@ -268,7 +268,7 @@ public LineCap EndCap { get { - int endCap = 0; + int endCap; int status = Gdip.GdipGetPenEndCap(new HandleRef(this, NativePen), out endCap); Gdip.CheckStatus(status); @@ -311,7 +311,7 @@ public DashCap DashCap { get { - int dashCap = 0; + int dashCap; int status = Gdip.GdipGetPenDashCap197819(new HandleRef(this, NativePen), out dashCap); Gdip.CheckStatus(status); @@ -341,7 +341,7 @@ public LineJoin LineJoin { get { - int lineJoin = 0; + int lineJoin; int status = Gdip.GdipGetPenLineJoin(new HandleRef(this, NativePen), out lineJoin); Gdip.CheckStatus(status); @@ -396,7 +396,7 @@ public PenAlignment Alignment { get { - PenAlignment penMode = 0; + PenAlignment penMode; int status = Gdip.GdipGetPenMode(new HandleRef(this, NativePen), out penMode); Gdip.CheckStatus(status); @@ -543,7 +543,7 @@ public PenType PenType { get { - int type = -1; + int type; int status = Gdip.GdipGetPenFillType(new HandleRef(this, NativePen), out type); Gdip.CheckStatus(status); @@ -565,7 +565,7 @@ public Color Color throw new ArgumentException(SR.GdiplusInvalidParameter); } - int colorARGB = 0; + int colorARGB; int status = Gdip.GdipGetPenColor(new HandleRef(this, NativePen), out colorARGB); Gdip.CheckStatus(status); @@ -659,7 +659,7 @@ public Brush Brush private IntPtr GetNativeBrush() { - IntPtr nativeBrush = IntPtr.Zero; + IntPtr nativeBrush; int status = Gdip.GdipGetPenBrushFill(new HandleRef(this, NativePen), out nativeBrush); Gdip.CheckStatus(status); @@ -673,7 +673,7 @@ public DashStyle DashStyle { get { - int dashStyle = 0; + int dashStyle; int status = Gdip.GdipGetPenDashStyle(new HandleRef(this, NativePen), out dashStyle); Gdip.CheckStatus(status); @@ -714,7 +714,7 @@ public DashStyle DashStyle /// private void EnsureValidDashPattern() { - int retval = 0; + int retval; int status = Gdip.GdipGetPenDashCount(new HandleRef(this, NativePen), out retval); Gdip.CheckStatus(status); @@ -832,7 +832,7 @@ public float[] CompoundArray { get { - int count = 0; + int count; int status = Gdip.GdipGetPenCompoundCount(new HandleRef(this, NativePen), out count); Gdip.CheckStatus(status); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs index 47bb8a61937b1..24c8e0761adb2 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs @@ -188,12 +188,12 @@ public static StringCollection InstalledPrinters int bufferSize; int count; - Interop.Winspool.EnumPrinters(SafeNativeMethods.PRINTER_ENUM_LOCAL | SafeNativeMethods.PRINTER_ENUM_CONNECTIONS, null, Level, IntPtr.Zero, 0, out bufferSize, out count); + Interop.Winspool.EnumPrinters(SafeNativeMethods.PRINTER_ENUM_LOCAL | SafeNativeMethods.PRINTER_ENUM_CONNECTIONS, null, Level, IntPtr.Zero, 0, out bufferSize, out _); IntPtr buffer = Marshal.AllocCoTaskMem(bufferSize); int returnCode = Interop.Winspool.EnumPrinters(SafeNativeMethods.PRINTER_ENUM_LOCAL | SafeNativeMethods.PRINTER_ENUM_CONNECTIONS, null, Level, buffer, - bufferSize, out bufferSize, out count); + bufferSize, out _, out count); var array = new string[count]; if (returnCode == 0) @@ -448,7 +448,7 @@ public bool IsDirectPrintingSupported(ImageFormat imageFormat) if (imageFormat.Equals(ImageFormat.Jpeg) || imageFormat.Equals(ImageFormat.Png)) { int nEscape = imageFormat.Equals(ImageFormat.Jpeg) ? Interop.Gdi32.CHECKJPEGFORMAT : Interop.Gdi32.CHECKPNGFORMAT; - int outData = 0; + int outData; DeviceContext dc = CreateInformationContext(DefaultPageSettings); HandleRef hdc = new HandleRef(dc, dc.Hdc); try @@ -707,7 +707,6 @@ private static string GetDefaultPrinterName() string name = ReadOneDEVNAME(names, 1); Interop.Kernel32.GlobalUnlock(handle); - names = IntPtr.Zero; // Windows allocates them, but we have to free them Interop.Kernel32.GlobalFree(data.hDevNames); @@ -731,7 +730,6 @@ private static string GetDefaultPrinterName() string name = ReadOneDEVNAME(names, 1); Interop.Kernel32.GlobalUnlock(handle); - names = IntPtr.Zero; // Windows allocates them, but we have to free them Interop.Kernel32.GlobalFree(data.hDevNames); @@ -761,7 +759,6 @@ private static string GetOutputPort() string name = ReadOneDEVNAME(names, 2); Interop.Kernel32.GlobalUnlock(handle); - names = IntPtr.Zero; // Windows allocates them, but we have to free them Interop.Kernel32.GlobalFree(data.hDevNames); @@ -786,7 +783,6 @@ private static string GetOutputPort() string name = ReadOneDEVNAME(names, 2); Interop.Kernel32.GlobalUnlock(handle); - names = IntPtr.Zero; // Windows allocates them, but we have to free them Interop.Kernel32.GlobalFree(data.hDevNames); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs index 07c60aa8f943f..6ccb314c06078 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs @@ -202,7 +202,7 @@ internal static void LoadPrinterSettings(string printer, PrinterSettings setting settings.PrinterCapabilities.Clear(); - IntPtr dests = IntPtr.Zero, ptr = IntPtr.Zero, ptr_printer, ppd_handle = IntPtr.Zero; + IntPtr dests = IntPtr.Zero, ptr, ptr_printer, ppd_handle; string name = string.Empty; CUPS_DESTS printer_dest; PPD_FILE ppd; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs index 379fc61e2e154..d53c41d5e528c 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Region.cs @@ -337,7 +337,7 @@ public bool Equals(Region region, Graphics g) return null; byte[] regionData = new byte[regionSize]; - Gdip.CheckStatus(Gdip.GdipGetRegionData(new HandleRef(this, NativeRegion), regionData, regionSize, out regionSize)); + Gdip.CheckStatus(Gdip.GdipGetRegionData(new HandleRef(this, NativeRegion), regionData, regionSize, out _)); return new RegionData(regionData); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/SolidBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/SolidBrush.cs index 951947d87b5de..6ff77667eae7b 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/SolidBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/SolidBrush.cs @@ -53,7 +53,7 @@ internal SolidBrush(IntPtr nativeBrush) public override object Clone() { - IntPtr clonedBrush = IntPtr.Zero; + IntPtr clonedBrush; int status = Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out clonedBrush); Gdip.CheckStatus(status); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs index cd0a7d074d1c1..e233fe56798f3 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/StringFormat.cs @@ -110,7 +110,7 @@ private void Dispose(bool disposing) /// public object Clone() { - IntPtr cloneFormat = IntPtr.Zero; + IntPtr cloneFormat; int status = Gdip.GdipCloneStringFormat(new HandleRef(this, nativeFormat), out cloneFormat); @@ -167,7 +167,7 @@ public StringAlignment Alignment { get { - StringAlignment alignment = 0; + StringAlignment alignment; int status = Gdip.GdipGetStringFormatAlign(new HandleRef(this, nativeFormat), out alignment); if (status != Gdip.Ok) @@ -197,7 +197,7 @@ public StringAlignment LineAlignment { get { - StringAlignment alignment = 0; + StringAlignment alignment; int status = Gdip.GdipGetStringFormatLineAlign(new HandleRef(this, nativeFormat), out alignment); if (status != Gdip.Ok) @@ -279,7 +279,7 @@ public void SetTabStops(float firstTabOffset, float[] tabStops) /// public float[] GetTabStops(out float firstTabOffset) { - int count = 0; + int count; int status = Gdip.GdipGetStringFormatTabStopCount(new HandleRef(this, nativeFormat), out count); if (status != Gdip.Ok) @@ -393,9 +393,8 @@ public StringDigitSubstitute DigitSubstitutionMethod get { StringDigitSubstitute digitSubstitute; - int lang = 0; - int status = Gdip.GdipGetStringFormatDigitSubstitution(new HandleRef(this, nativeFormat), out lang, out digitSubstitute); + int status = Gdip.GdipGetStringFormatDigitSubstitution(new HandleRef(this, nativeFormat), out _, out digitSubstitute); if (status != Gdip.Ok) throw Gdip.StatusException(status); @@ -411,9 +410,8 @@ public int DigitSubstitutionLanguage { get { - StringDigitSubstitute digitSubstitute; - int language = 0; - int status = Gdip.GdipGetStringFormatDigitSubstitution(new HandleRef(this, nativeFormat), out language, out digitSubstitute); + int language; + int status = Gdip.GdipGetStringFormatDigitSubstitution(new HandleRef(this, nativeFormat), out language, out _); if (status != Gdip.Ok) throw Gdip.StatusException(status); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/FontCollection.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/FontCollection.cs index aa76ed2e15d69..e774b82c205c0 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/FontCollection.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/FontCollection.cs @@ -35,12 +35,12 @@ public FontFamily[] Families { get { - int numSought = 0; + int numSought; int status = Gdip.GdipGetFontCollectionFamilyCount(new HandleRef(this, _nativeFontCollection), out numSought); Gdip.CheckStatus(status); var gpfamilies = new IntPtr[numSought]; - int numFound = 0; + int numFound; status = Gdip.GdipGetFontCollectionFamilyList(new HandleRef(this, _nativeFontCollection), numSought, gpfamilies, out numFound); Gdip.CheckStatus(status); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/TextureBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/TextureBrush.cs index 56ce6c20e3c97..53d9ea5c117f7 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/TextureBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/TextureBrush.cs @@ -34,7 +34,7 @@ public TextureBrush(Image image, WrapMode wrapMode) throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); } - IntPtr brush = IntPtr.Zero; + IntPtr brush; int status = Gdip.GdipCreateTexture(new HandleRef(image, image.nativeImage), (int)wrapMode, out brush); @@ -55,7 +55,7 @@ public TextureBrush(Image image, WrapMode wrapMode, RectangleF dstRect) throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); } - IntPtr brush = IntPtr.Zero; + IntPtr brush; int status = Gdip.GdipCreateTexture2(new HandleRef(image, image.nativeImage), unchecked((int)wrapMode), dstRect.X, @@ -80,7 +80,7 @@ public TextureBrush(Image image, WrapMode wrapMode, Rectangle dstRect) throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode)); } - IntPtr brush = IntPtr.Zero; + IntPtr brush; int status = Gdip.GdipCreateTexture2I(new HandleRef(image, image.nativeImage), unchecked((int)wrapMode), dstRect.X, @@ -102,7 +102,7 @@ public TextureBrush(Image image, RectangleF dstRect, ImageAttributes? imageAttr) throw new ArgumentNullException(nameof(image)); } - IntPtr brush = IntPtr.Zero; + IntPtr brush; int status = Gdip.GdipCreateTextureIA(new HandleRef(image, image.nativeImage), new HandleRef(imageAttr, (imageAttr == null) ? IntPtr.Zero : imageAttr.nativeImageAttributes), @@ -125,7 +125,7 @@ public TextureBrush(Image image, Rectangle dstRect, ImageAttributes? imageAttr) throw new ArgumentNullException(nameof(image)); } - IntPtr brush = IntPtr.Zero; + IntPtr brush; int status = Gdip.GdipCreateTextureIAI(new HandleRef(image, image.nativeImage), new HandleRef(imageAttr, (imageAttr == null) ? IntPtr.Zero : imageAttr.nativeImageAttributes), @@ -147,7 +147,7 @@ internal TextureBrush(IntPtr nativeBrush) public override object Clone() { - IntPtr cloneBrush = IntPtr.Zero; + IntPtr cloneBrush; int status = Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out cloneBrush); Gdip.CheckStatus(status); @@ -180,7 +180,7 @@ public WrapMode WrapMode { get { - int mode = 0; + int mode; int status = Gdip.GdipGetTextureWrapMode(new HandleRef(this, NativeBrush), out mode); Gdip.CheckStatus(status); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs index aad75a27f3516..be2a5c7d7679a 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs @@ -88,7 +88,7 @@ public override bool Equals([NotNullWhen(true)] object? value) { if ((large && _largeImage == null) || (!large && _smallImage == null)) { - Image? img = null; + Image? img; if (large) { img = _largeImage; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/macFunctions.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/macFunctions.cs index b8483c9fa53ef..90b91cbe54729 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/macFunctions.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/macFunctions.cs @@ -61,8 +61,8 @@ internal static CocoaContext GetCGContextForNSView(IntPtr handle) internal static CarbonContext GetCGContextForView(IntPtr handle) { IntPtr context = IntPtr.Zero; - IntPtr port = IntPtr.Zero; - IntPtr window = IntPtr.Zero; + IntPtr port; + IntPtr window; window = GetControlOwner(handle); diff --git a/src/libraries/System.Drawing.Common/tests/GraphicsTests.Core.cs b/src/libraries/System.Drawing.Common/tests/GraphicsTests.Core.cs index 3a137da17c7e5..d691cd23ff9df 100644 --- a/src/libraries/System.Drawing.Common/tests/GraphicsTests.Core.cs +++ b/src/libraries/System.Drawing.Common/tests/GraphicsTests.Core.cs @@ -77,5 +77,154 @@ public void TransformElements_RoundTrip() } } } + + [ConditionalFact(Helpers.IsDrawingSupported)] + public void DrawRectangle_NullPen_ThrowsArgumentNullException_Core() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + { + AssertExtensions.Throws("pen", () => graphics.DrawRectangle(null, new RectangleF(0f, 0f, 1f, 1f))); + // other DrawRectangle overloads tested in DrawRectangle_NullPen_ThrowsArgumentNullException() + } + } + + [ConditionalFact(Helpers.IsDrawingSupported)] + public void DrawRectangle_DisposedPen_ThrowsArgumentException_Core() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + { + var pen = new Pen(Color.Red); + pen.Dispose(); + + AssertExtensions.Throws(null, () => graphics.DrawRectangle(pen, new RectangleF(0f, 0f, 1f, 1f))); + // other DrawRectangle overloads tested in DrawRectangle_DisposedPen_ThrowsArgumentException() + } + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/22221", TestPlatforms.AnyUnix)] + [ConditionalFact(Helpers.IsDrawingSupported)] + public void DrawRectangle_Busy_ThrowsInvalidOperationException_Core() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + using (var pen = new Pen(Color.Red)) + { + graphics.GetHdc(); + try + { + Assert.Throws(() => graphics.DrawRectangle(pen, new RectangleF(0f, 0f, 1f, 1f))); + // other DrawRectangle overloads tested in DrawRectangle_Busy_ThrowsInvalidOperationException() + } + finally + { + graphics.ReleaseHdc(); + } + } + } + + [ConditionalFact(Helpers.IsDrawingSupported)] + public void DrawRectangle_Disposed_ThrowsArgumentException_Core() + { + using (var image = new Bitmap(10, 10)) + using (var pen = new Pen(Color.Red)) + { + Graphics graphics = Graphics.FromImage(image); + graphics.Dispose(); + + AssertExtensions.Throws(null, () => graphics.DrawRectangle(pen, new RectangleF(0f, 0f, 1f, 1f))); + // other DrawRectangle overloads tested in DrawRectangle_Disposed_ThrowsArgumentException() + } + } + + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_NullPen_ThrowsArgumentNullException_Core() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + { + AssertExtensions.Throws("brush", () => graphics.FillPie(null, new RectangleF(0, 0, 1, 1), 0, 90)); + // other FillPie overloads tested in FillPie_NullPen_ThrowsArgumentNullException() + } + } + + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_DisposedPen_ThrowsArgumentException_Core() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + { + var brush = new SolidBrush(Color.Red); + brush.Dispose(); + + AssertExtensions.Throws(null, () => graphics.FillPie(brush, new RectangleF(0, 0, 1, 1), 0, 90)); + // other FillPie overloads tested in FillPie_DisposedPen_ThrowsArgumentException() + } + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/22221", TestPlatforms.AnyUnix)] + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_ZeroWidth_ThrowsArgumentException_Core() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + using (var brush = new SolidBrush(Color.Red)) + { + AssertExtensions.Throws(null, () => graphics.FillPie(brush, new RectangleF(0, 0, 0, 1), 0, 90)); + // other FillPie overloads tested in FillPie_ZeroWidth_ThrowsArgumentException() + } + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/22221", TestPlatforms.AnyUnix)] + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_ZeroHeight_ThrowsArgumentException_Core() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + using (var brush = new SolidBrush(Color.Red)) + { + AssertExtensions.Throws(null, () => graphics.FillPie(brush, new RectangleF(0, 0, 1, 0), 0, 90)); + // other FillPie overloads tested in FillPie_ZeroHeight_ThrowsArgumentException() + } + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/22221", TestPlatforms.AnyUnix)] + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_Busy_ThrowsInvalidOperationException_Core() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + using (var brush = new SolidBrush(Color.Red)) + { + graphics.GetHdc(); + try + { + Assert.Throws(() => graphics.FillPie(brush, new RectangleF(0, 0, 1, 1), 0, 90)); + // other FillPie overloads tested in FillPie_Busy_ThrowsInvalidOperationException() + } + finally + { + graphics.ReleaseHdc(); + } + } + } + + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_Disposed_ThrowsArgumentException_Core() + { + using (var image = new Bitmap(10, 10)) + using (var brush = new SolidBrush(Color.Red)) + { + Graphics graphics = Graphics.FromImage(image); + graphics.Dispose(); + + AssertExtensions.Throws(null, () => graphics.FillPie(brush, new RectangleF(0, 0, 1, 1), 0, 90)); + // other FillPie overloads tested in FillPie_Disposed_ThrowsArgumentException() + } + } + + + } } diff --git a/src/libraries/System.Drawing.Common/tests/GraphicsTests.cs b/src/libraries/System.Drawing.Common/tests/GraphicsTests.cs index 8c0f280b86361..c99ad88ea40ae 100644 --- a/src/libraries/System.Drawing.Common/tests/GraphicsTests.cs +++ b/src/libraries/System.Drawing.Common/tests/GraphicsTests.cs @@ -2399,7 +2399,6 @@ public void DrawRectangle_DisposedPen_ThrowsArgumentException() var pen = new Pen(Color.Red); pen.Dispose(); - AssertExtensions.Throws(null, () => graphics.DrawRectangle(pen, new Rectangle(0, 0, 1, 1))); AssertExtensions.Throws(null, () => graphics.DrawRectangle(pen, 0, 0, 1, 1)); AssertExtensions.Throws(null, () => graphics.DrawRectangle(pen, 0f, 0f, 1f, 1f)); @@ -3099,6 +3098,98 @@ public void DrawClosedCurve_Disposed_ThrowsArgumentException() } } + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_NullPen_ThrowsArgumentNullException() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + { + AssertExtensions.Throws("brush", () => graphics.FillPie(null, new Rectangle(0, 0, 1, 1), 0, 90)); + AssertExtensions.Throws("brush", () => graphics.FillPie(null, 0, 0, 1, 1, 0, 90)); + AssertExtensions.Throws("brush", () => graphics.FillPie(null, 0f, 0f, 1f, 1f, 0, 90)); + } + } + + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_DisposedPen_ThrowsArgumentException() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + { + var brush = new SolidBrush(Color.Red); + brush.Dispose(); + + AssertExtensions.Throws(null, () => graphics.FillPie(brush, new Rectangle(0, 0, 1, 1), 0, 90)); + AssertExtensions.Throws(null, () => graphics.FillPie(brush, 0, 0, 1, 1, 0, 90)); + AssertExtensions.Throws(null, () => graphics.FillPie(brush, 0f, 0f, 1f, 1f, 0, 90)); + } + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/22221", TestPlatforms.AnyUnix)] + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_ZeroWidth_ThrowsArgumentException() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + using (var brush = new SolidBrush(Color.Red)) + { + AssertExtensions.Throws(null, () => graphics.FillPie(brush, new Rectangle(0, 0, 0, 1), 0, 90)); + AssertExtensions.Throws(null, () => graphics.FillPie(brush, 0, 0, 0, 1, 0, 90)); + AssertExtensions.Throws(null, () => graphics.FillPie(brush, 0f, 0f, 0f, 1f, 0, 90)); + } + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/22221", TestPlatforms.AnyUnix)] + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_ZeroHeight_ThrowsArgumentException() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + using (var brush = new SolidBrush(Color.Red)) + { + AssertExtensions.Throws(null, () => graphics.FillPie(brush, new Rectangle(0, 0, 1, 0), 0, 90)); + AssertExtensions.Throws(null, () => graphics.FillPie(brush, 0, 0, 1, 0, 0, 90)); + AssertExtensions.Throws(null, () => graphics.FillPie(brush, 0f, 0f, 1f, 0f, 0, 90)); + } + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/22221", TestPlatforms.AnyUnix)] + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_Busy_ThrowsInvalidOperationException() + { + using (var image = new Bitmap(10, 10)) + using (Graphics graphics = Graphics.FromImage(image)) + using (var brush = new SolidBrush(Color.Red)) + { + graphics.GetHdc(); + try + { + Assert.Throws(() => graphics.FillPie(brush, new Rectangle(0, 0, 1, 1), 0, 90)); + Assert.Throws(() => graphics.FillPie(brush, 0, 0, 1, 1, 0, 90)); + Assert.Throws(() => graphics.FillPie(brush, 0f, 0f, 1f, 1f, 0, 90)); + } + finally + { + graphics.ReleaseHdc(); + } + } + } + + [ConditionalFact(Helpers.IsDrawingSupported)] + public void FillPie_Disposed_ThrowsArgumentException() + { + using (var image = new Bitmap(10, 10)) + using (var brush = new SolidBrush(Color.Red)) + { + Graphics graphics = Graphics.FromImage(image); + graphics.Dispose(); + + AssertExtensions.Throws(null, () => graphics.FillPie(brush, new Rectangle(0, 0, 1, 1), 0, 90)); + AssertExtensions.Throws(null, () => graphics.FillPie(brush, 0, 0, 1, 1, 0, 90)); + AssertExtensions.Throws(null, () => graphics.FillPie(brush, 0f, 0f, 1f, 1f, 0, 90)); + } + } + [ConditionalFact(Helpers.IsDrawingSupported)] public void Clear_Color_Success() { diff --git a/src/libraries/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs b/src/libraries/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs index ee007af28b6d0..36ff2977b807d 100644 --- a/src/libraries/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs +++ b/src/libraries/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs @@ -65,7 +65,11 @@ internal static int[] GetCurrencyNegativePatterns(string localeName) return PlatformDetection.IsNlsGlobalization ? new int[] { 12 } : new int[] { 9 }; case "es-BO": - return (PlatformDetection.IsNlsGlobalization && PlatformDetection.WindowsVersion < 10) ? new int[] { 14 } : new int[] { 1 }; + return (PlatformDetection.IsNlsGlobalization && PlatformDetection.WindowsVersion < 10) ? + new int[] { 14 } : + // Mac OSX used to return 1 which is the format "-$n". OSX Version 12 (Monterey) started + // to return a different value 12 "$ -n". + PlatformDetection.IsOSX ? new int[] { 1, 12 } : new int[] { 1 }; case "fr-CA": return PlatformDetection.IsNlsGlobalization ? new int[] { 15 } : new int[] { 8, 15 }; diff --git a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs index fbd813f4412ec..c0e737bb10322 100644 --- a/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs +++ b/src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliEncoder.cs @@ -129,7 +129,7 @@ public static int GetMaxCompressedLength(int inputSize) /// When this method returns, a span of bytes where the compressed data will be stored. /// When this method returns, the total number of bytes that were written to . /// One of the enumeration values that describes the status with which the operation finished. - public OperationStatus Flush(Span destination, out int bytesWritten) => Compress(ReadOnlySpan.Empty, destination, out int bytesConsumed, out bytesWritten, BrotliEncoderOperation.Flush); + public OperationStatus Flush(Span destination, out int bytesWritten) => Compress(ReadOnlySpan.Empty, destination, out _, out bytesWritten, BrotliEncoderOperation.Flush); internal OperationStatus Compress(ReadOnlyMemory source, Memory destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock) => Compress(source.Span, destination.Span, out bytesConsumed, out bytesWritten, isFinalBlock); diff --git a/src/libraries/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj b/src/libraries/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj index 7a2fed130efe4..0a6a7088ace39 100644 --- a/src/libraries/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj +++ b/src/libraries/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj @@ -4,6 +4,15 @@ true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser + + + + WasmTestOnBrowser + $(TestArchiveRoot)browserornodejs/ + $(TestArchiveTestsRoot)$(OSPlatformConfig)/ + $(DefineConstants);TARGET_BROWSER + + diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InflaterManaged.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InflaterManaged.cs index 1031b5128e624..a127d93bd1d44 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InflaterManaged.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InflaterManaged.cs @@ -165,7 +165,7 @@ public int Inflate(Span bytes) private bool Decode() { bool eob = false; - bool result = false; + bool result; if (Finished()) { diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs index 8d818b2fe3ebc..a12f16f61080d 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs @@ -592,8 +592,7 @@ private void PurgeBuffers(bool disposing) bool finished; do { - int compressedBytes; - finished = _deflater.Finish(_buffer, out compressedBytes); + finished = _deflater.Finish(_buffer, out _); } while (!finished); } } @@ -640,8 +639,7 @@ private async ValueTask PurgeBuffersAsync() bool finished; do { - int compressedBytes; - finished = _deflater.Finish(_buffer, out compressedBytes); + finished = _deflater.Finish(_buffer, out _); } while (!finished); } } diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs index 0481ee770dfba..0d5de3cbac6bd 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs @@ -555,7 +555,7 @@ internal void WriteCentralDirectoryFileHeader() internal bool LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded() { // we should have made this exact call in _archive.Init through ThrowIfOpenable - Debug.Assert(IsOpenable(false, true, out string? message)); + Debug.Assert(IsOpenable(false, true, out _)); // load local header's extra fields. it will be null if we couldn't read for some reason if (_originallyInArchive) @@ -641,7 +641,7 @@ private CheckSumAndSizeWriteStream GetDataCompressor(Stream backingStream, bool private Stream GetDataDecompressor(Stream compressedStreamToRead) { - Stream? uncompressedStream = null; + Stream? uncompressedStream; switch (CompressionMethod) { case CompressionMethodValues.Deflate: diff --git a/src/libraries/System.IO.Compression/tests/System.IO.Compression.Tests.csproj b/src/libraries/System.IO.Compression/tests/System.IO.Compression.Tests.csproj index 9b51d5b5d34ff..509c7202afb43 100644 --- a/src/libraries/System.IO.Compression/tests/System.IO.Compression.Tests.csproj +++ b/src/libraries/System.IO.Compression/tests/System.IO.Compression.Tests.csproj @@ -3,6 +3,15 @@ $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser true + + + + WasmTestOnBrowser + $(TestArchiveRoot)browserornodejs/ + $(TestArchiveTestsRoot)$(OSPlatformConfig)/ + $(DefineConstants);TARGET_BROWSER + + diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs index 6b1956aeb2352..a04d60120c741 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/DirectoryObjectSecurity.cs @@ -531,8 +531,7 @@ protected void AddAccessRule(ObjectAccessRule rule) try { - bool modified; - ModifyAccess(AccessControlModification.Add, rule, out modified); + ModifyAccess(AccessControlModification.Add, rule, out _); } finally { @@ -553,8 +552,7 @@ protected void SetAccessRule(ObjectAccessRule rule) try { - bool modified; - ModifyAccess(AccessControlModification.Set, rule, out modified); + ModifyAccess(AccessControlModification.Set, rule, out _); } finally { @@ -573,8 +571,7 @@ protected void ResetAccessRule(ObjectAccessRule rule) try { - bool modified; - ModifyAccess(AccessControlModification.Reset, rule, out modified); + ModifyAccess(AccessControlModification.Reset, rule, out _); } finally { @@ -598,8 +595,7 @@ protected bool RemoveAccessRule(ObjectAccessRule rule) return true; } - bool modified; - return ModifyAccess(AccessControlModification.Remove, rule, out modified); + return ModifyAccess(AccessControlModification.Remove, rule, out _); } finally { @@ -623,8 +619,7 @@ protected void RemoveAccessRuleAll(ObjectAccessRule rule) return; } - bool modified; - ModifyAccess(AccessControlModification.RemoveAll, rule, out modified); + ModifyAccess(AccessControlModification.RemoveAll, rule, out _); } finally { @@ -648,8 +643,7 @@ protected void RemoveAccessRuleSpecific(ObjectAccessRule rule) try { - bool modified; - ModifyAccess(AccessControlModification.RemoveSpecific, rule, out modified); + ModifyAccess(AccessControlModification.RemoveSpecific, rule, out _); } finally { @@ -668,8 +662,7 @@ protected void AddAuditRule(ObjectAuditRule rule) try { - bool modified; - ModifyAudit(AccessControlModification.Add, rule, out modified); + ModifyAudit(AccessControlModification.Add, rule, out _); } finally { @@ -688,8 +681,7 @@ protected void SetAuditRule(ObjectAuditRule rule) try { - bool modified; - ModifyAudit(AccessControlModification.Set, rule, out modified); + ModifyAudit(AccessControlModification.Set, rule, out _); } finally { @@ -708,8 +700,7 @@ protected bool RemoveAuditRule(ObjectAuditRule rule) try { - bool modified; - return ModifyAudit(AccessControlModification.Remove, rule, out modified); + return ModifyAudit(AccessControlModification.Remove, rule, out _); } finally { @@ -728,8 +719,7 @@ protected void RemoveAuditRuleAll(ObjectAuditRule rule) try { - bool modified; - ModifyAudit(AccessControlModification.RemoveAll, rule, out modified); + ModifyAudit(AccessControlModification.RemoveAll, rule, out _); } finally { @@ -748,8 +738,7 @@ protected void RemoveAuditRuleSpecific(ObjectAuditRule rule) try { - bool modified; - ModifyAudit(AccessControlModification.RemoveSpecific, rule, out modified); + ModifyAudit(AccessControlModification.RemoveSpecific, rule, out _); } finally { diff --git a/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.Unix.cs b/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.Unix.cs index bc696ef7b5724..e1eb1b53e0ee4 100644 --- a/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.Unix.cs +++ b/src/libraries/System.IO.FileSystem.DriveInfo/src/System/IO/DriveInfo.Unix.cs @@ -43,7 +43,7 @@ public string DriveFormat { get { - string format = string.Empty; + string format; CheckStatfsResultAndThrowIfNecessary(Interop.Sys.GetFormatInfoForMountPoint(Name, out format)); return format; } @@ -53,7 +53,7 @@ public long AvailableFreeSpace { get { - Interop.Sys.MountPointInformation mpi = default(Interop.Sys.MountPointInformation); + Interop.Sys.MountPointInformation mpi; CheckStatfsResultAndThrowIfNecessary(Interop.Sys.GetSpaceInfoForMountPoint(Name, out mpi)); return checked((long)mpi.AvailableFreeSpace); } @@ -63,7 +63,7 @@ public long TotalFreeSpace { get { - Interop.Sys.MountPointInformation mpi = default(Interop.Sys.MountPointInformation); + Interop.Sys.MountPointInformation mpi; CheckStatfsResultAndThrowIfNecessary(Interop.Sys.GetSpaceInfoForMountPoint(Name, out mpi)); return checked((long)mpi.TotalFreeSpace); } @@ -73,7 +73,7 @@ public long TotalSize { get { - Interop.Sys.MountPointInformation mpi = default(Interop.Sys.MountPointInformation); + Interop.Sys.MountPointInformation mpi; CheckStatfsResultAndThrowIfNecessary(Interop.Sys.GetSpaceInfoForMountPoint(Name, out mpi)); return checked((long)mpi.TotalSize); } diff --git a/src/libraries/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Unix.Tests.cs b/src/libraries/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Unix.Tests.cs index e7723229c0d2d..14abd97e397af 100644 --- a/src/libraries/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Unix.Tests.cs +++ b/src/libraries/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Unix.Tests.cs @@ -42,7 +42,7 @@ public void TestGetDrives() } [Fact] - [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser)] + [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Browser)] public void PropertiesOfInvalidDrive() { string invalidDriveName = "NonExistentDriveName"; diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/Exists.cs b/src/libraries/System.IO.FileSystem/tests/Directory/Exists.cs index 5337ae1fef824..9e3e21978eb13 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/Exists.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/Exists.cs @@ -299,6 +299,7 @@ public void PathWithReservedDeviceNameAsPath_ReturnsFalse(string component) Assert.False(Exists(component)); } + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/901", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] [Theory, MemberData(nameof(UncPathsWithoutShareName))] public void UncPathWithoutShareNameAsPath_ReturnsFalse(string component) diff --git a/src/libraries/System.IO.FileSystem/tests/File/Exists.cs b/src/libraries/System.IO.FileSystem/tests/File/Exists.cs index 618f6df535609..97a3d03e017f2 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Exists.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Exists.cs @@ -230,6 +230,7 @@ public void PathWithReservedDeviceNameAsPath_ReturnsFalse(string component) Assert.False(Exists(component)); } + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/901", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] [Theory, MemberData(nameof(UncPathsWithoutShareName))] public void UncPathWithoutShareNameAsPath_ReturnsFalse(string component) diff --git a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs index 26dd666d06916..4d3a96c80665a 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytes.cs @@ -166,7 +166,7 @@ public void ProcFs_NotEmpty(string path) [ActiveIssue("https://github.com/dotnet/runtime/issues/60427")] public async Task ReadAllBytes_NonSeekableFileStream_InWindows() { - string pipeName = FileSystemTest.GetNamedPipeServerStreamName(); + string pipeName = GetNamedPipeServerStreamName(); string pipePath = Path.GetFullPath($@"\\.\pipe\{pipeName}"); var namedPipeWriterStream = new NamedPipeServerStream(pipeName, PipeDirection.Out); diff --git a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs index c4f147cbb8009..c6fbb37880b95 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/ReadWriteAllBytesAsync.cs @@ -177,7 +177,7 @@ public async Task ProcFs_NotEmpty(string path) [PlatformSpecific(TestPlatforms.Windows)] // DOS device paths (\\.\ and \\?\) are a Windows concept public async Task ReadAllBytesAsync_NonSeekableFileStream_InWindows() { - string pipeName = FileSystemTest.GetNamedPipeServerStreamName(); + string pipeName = GetNamedPipeServerStreamName(); string pipePath = Path.GetFullPath($@"\\.\pipe\{pipeName}"); var namedPipeWriterStream = new NamedPipeServerStream(pipeName, PipeDirection.Out); diff --git a/src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.Windows.cs b/src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.Windows.cs index 6e694e4347369..044343f91a9f6 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.Windows.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.Windows.cs @@ -19,7 +19,7 @@ public class UnseekableDeviceFileStreamConnectedConformanceTests : ConnectedStre { protected override async Task CreateConnectedStreamsAsync() { - string pipeName = FileSystemTest.GetNamedPipeServerStreamName(); + string pipeName = GetNamedPipeServerStreamName(); string pipePath = Path.GetFullPath($@"\\.\pipe\{pipeName}"); var server = new NamedPipeServerStream(pipeName, PipeDirection.In); diff --git a/src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.cs b/src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.cs index d1fd4fe764f4d..d9d36053a8e11 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileStream/FileStreamConformanceTests.cs @@ -252,7 +252,7 @@ public class NamedPipeFileStreamConnectedConformanceTests : ConnectedStreamConfo { protected override async Task CreateConnectedStreamsAsync() { - string name = FileSystemTest.GetNamedPipeServerStreamName(); + string name = GetNamedPipeServerStreamName(); var server = new NamedPipeServerStream(name, PipeDirection.In); var client = new NamedPipeClientStream(".", name, PipeDirection.Out); diff --git a/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs b/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs index b2dda99e0831e..53251552104f6 100644 --- a/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs +++ b/src/libraries/System.IO.FileSystem/tests/FileSystemTest.cs @@ -55,31 +55,6 @@ public static TheoryData TrailingSeparators } } - public static string GetNamedPipeServerStreamName() - { - if (PlatformDetection.IsInAppContainer) - { - return @"LOCAL\" + Guid.NewGuid().ToString("N"); - } - - if (PlatformDetection.IsWindows || !PlatformDetection.IsNotRunningOnMacOS) - { - return Guid.NewGuid().ToString("N"); - } - - const int MinUdsPathLength = 104; // required min is 92, but every platform we currently target is at least 104 - const int MinAvailableForSufficientRandomness = 5; // we want enough randomness in the name to avoid conflicts between concurrent tests - string prefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_"); - int availableLength = MinUdsPathLength - prefix.Length - 1; // 1 - for possible null terminator - Assert.True(availableLength >= MinAvailableForSufficientRandomness, $"UDS prefix {prefix} length {prefix.Length} is too long"); - - return string.Create(availableLength, 0, (span, _) => - { - for (int i = 0; i < span.Length; i++) - span[i] = (char)('a' + Random.Shared.Next(0, 26)); - }); - } - /// /// Do a test action against read only file system (for Unix). /// diff --git a/src/libraries/System.IO.FileSystem/tests/RandomAccess/NoBuffering.Windows.cs b/src/libraries/System.IO.FileSystem/tests/RandomAccess/NoBuffering.Windows.cs index ef60a9f223fb2..83b4c87bb64f5 100644 --- a/src/libraries/System.IO.FileSystem/tests/RandomAccess/NoBuffering.Windows.cs +++ b/src/libraries/System.IO.FileSystem/tests/RandomAccess/NoBuffering.Windows.cs @@ -38,15 +38,6 @@ public async Task ReadUsingSingleBuffer(bool asyncOperation, bool asyncHandle) int current = 0; int total = 0; - // From https://docs.microsoft.com/en-us/windows/win32/fileio/file-buffering: - // "File access sizes, including the optional file offset in the OVERLAPPED structure, - // if specified, must be for a number of bytes that is an integer multiple of the volume sector size." - // So if buffer and physical sector size is 4096 and the file size is 4097: - // the read from offset=0 reads 4096 bytes - // the read from offset=4096 reads 1 byte - // the read from offset=4097 THROWS (Invalid argument, offset is not a multiple of sector size!) - // That is why we stop at the first incomplete read (the next one would throw). - // It's possible to get 0 if we are lucky and file size is a multiple of physical sector size. do { current = asyncOperation @@ -57,7 +48,7 @@ public async Task ReadUsingSingleBuffer(bool asyncOperation, bool asyncHandle) total += current; } - while (current == buffer.Memory.Length); + while (current != 0); Assert.Equal(fileSize, total); } @@ -222,6 +213,36 @@ public async Task ReadWriteAsyncUsingEmptyBuffers() await RandomAccess.WriteAsync(handle, Array.Empty>(), 0); } + [Theory] + [MemberData(nameof(AllAsyncSyncCombinations))] + public async Task ReadShouldReturnZeroForEndOfFile(bool asyncOperation, bool asyncHandle) + { + int fileSize = Environment.SystemPageSize + 1; // it MUST NOT be a multiple of it (https://github.com/dotnet/runtime/issues/62851) + string filePath = GetTestFilePath(); + byte[] expected = RandomNumberGenerator.GetBytes(fileSize); + File.WriteAllBytes(filePath, expected); + + using FileStream fileStream = new (filePath, FileMode.Open, FileAccess.Read, FileShare.None, 0, GetFileOptions(asyncHandle)); + using SectorAlignedMemory buffer = SectorAlignedMemory.Allocate(Environment.SystemPageSize); + + int current = 0; + int total = 0; + + do + { + current = asyncOperation + ? await fileStream.ReadAsync(buffer.Memory) + : fileStream.Read(buffer.GetSpan()); + + Assert.True(expected.AsSpan(total, current).SequenceEqual(buffer.GetSpan().Slice(0, current))); + + total += current; + } + while (current != 0); + + Assert.Equal(fileSize, total); + } + // when using FileOptions.Asynchronous we are testing Scatter&Gather APIs on Windows (FILE_FLAG_OVERLAPPED requirement) private static FileOptions GetFileOptions(bool asyncHandle) => (asyncHandle ? FileOptions.Asynchronous : FileOptions.None) | NoBuffering; } diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs index d2f04e84d27ef..cc8d30ca73ef1 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.cs @@ -148,7 +148,12 @@ public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, nameof(access)); } - bool existed = File.Exists(path); + bool existed = mode switch + { + FileMode.Open => true, // FileStream ctor will throw if the file doesn't exist + FileMode.CreateNew => false, + _ => File.Exists(path) + }; FileStream fileStream = new FileStream(path, mode, GetFileAccess(access), FileShare.Read, 0x1000, FileOptions.None); if (capacity == 0 && fileStream.Length == 0) @@ -162,7 +167,7 @@ public static MemoryMappedFile CreateFromFile(string path, FileMode mode, string capacity = fileStream.Length; } - SafeMemoryMappedFileHandle? handle = null; + SafeMemoryMappedFileHandle? handle; try { handle = CreateCore(fileStream, mapName, HandleInheritability.None, diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs index b974d4a0bdd98..9d14b133f8a91 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs @@ -59,7 +59,7 @@ public static MemoryMappedView CreateView(SafeMemoryMappedFileHandle memMappedFi // VirtualQueryEx: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx if (((viewInfo.State & Interop.Kernel32.MemOptions.MEM_RESERVE) != 0) || ((ulong)viewSize < (ulong)nativeSize)) { - IntPtr tempHandle = Interop.VirtualAlloc( + Interop.VirtualAlloc( viewHandle, (UIntPtr)(nativeSize != MemoryMappedFile.DefaultSize ? nativeSize : viewSize), Interop.Kernel32.MemOptions.MEM_COMMIT, MemoryMappedFile.GetPageAccess(access)); int lastError = Marshal.GetLastPInvokeError(); diff --git a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateFromFile.Tests.cs b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateFromFile.Tests.cs index 824f9b9fd17e3..c9feabeae25de 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateFromFile.Tests.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateFromFile.Tests.cs @@ -5,6 +5,8 @@ using System.Collections.Generic; using Microsoft.DotNet.XUnitExtensions; using Xunit; +using System.IO.Pipes; +using System.Threading.Tasks; namespace System.IO.MemoryMappedFiles.Tests { @@ -968,5 +970,55 @@ public void MapHandleMatchesFileStreamHandle() } } } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [SkipOnPlatform(TestPlatforms.Browser, "mkfifo is not supported on WASM")] + public async Task OpeningMemoryMappedFileFromFileStreamThatWrapsPipeThrowsNotSupportedException(long capacity) + { + (string pipePath, NamedPipeServerStream? serverStream) = CreatePipe(); + using FileStream clientStream = new (pipePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None); + + if (serverStream is not null) + { + await serverStream.WaitForConnectionAsync(); + } + + Assert.Throws(() => MemoryMappedFile.CreateFromFile(clientStream, null, capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false)); + + serverStream?.Dispose(); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [SkipOnPlatform(TestPlatforms.Browser, "mkfifo is not supported on WASM")] + public void OpeningMemoryMappedFileFromPipePathThrowsNotSupportedException(long capacity) + { + (string pipePath, NamedPipeServerStream? serverStream) = CreatePipe(); + + Assert.Throws(() => MemoryMappedFile.CreateFromFile(pipePath, FileMode.Open, null, capacity, MemoryMappedFileAccess.ReadWrite)); + + serverStream?.Dispose(); + } + + private (string pipePath, NamedPipeServerStream? serverStream) CreatePipe() + { + if (OperatingSystem.IsWindows()) + { + string pipeName = GetNamedPipeServerStreamName(); + string pipePath = Path.GetFullPath($@"\\.\pipe\{pipeName}"); + + return (pipePath, new NamedPipeServerStream(pipeName, PipeDirection.InOut)); + } + else + { + string fifoPath = GetTestFilePath(); + Assert.Equal(0, mkfifo(fifoPath, 438 /* 666 in octal */ )); + + return (fifoPath, null); + } + } } } diff --git a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateNew.Tests.cs b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateNew.Tests.cs index 70b82398301d5..4336ce74d6a22 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateNew.Tests.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CreateNew.Tests.cs @@ -11,6 +11,7 @@ namespace System.IO.MemoryMappedFiles.Tests /// /// Tests for MemoryMappedFile.CreateNew. /// + [ActiveIssue("https://github.com/dotnet/runtime/issues/63240", typeof(PlatformDetection), nameof(PlatformDetection.IsOSX), nameof(PlatformDetection.IsArm64Process), nameof(PlatformDetection.IsNotMonoRuntime))] public class MemoryMappedFileTests_CreateNew : MemoryMappedFilesTestBase { /// diff --git a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFilesTestsBase.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFilesTestsBase.Unix.cs index 670aa4d70aa0d..8024754a921da 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFilesTestsBase.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFilesTestsBase.Unix.cs @@ -34,6 +34,9 @@ public abstract partial class MemoryMappedFilesTestBase : FileCleanupTestBase [DllImport("libc", SetLastError = true)] private static extern int sysconf(int name); + [DllImport("libc", SetLastError = true)] + protected static extern int mkfifo(string path, int mode); + /// Asserts that the handle's inheritability matches the specified value. protected static void AssertInheritability(SafeHandle handle, HandleInheritability inheritability) { diff --git a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFilesTestsBase.Windows.cs b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFilesTestsBase.Windows.cs index 9473abe2e0529..2460c15fd5985 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFilesTestsBase.Windows.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedFilesTestsBase.Windows.cs @@ -43,10 +43,9 @@ private struct SYSTEM_INFO internal short wProcessorRevision; } - protected static int geteuid() - { - throw new PlatformNotSupportedException(); - } + protected static int geteuid() => throw new PlatformNotSupportedException(); + + protected static int mkfifo(string path, int mode) => throw new PlatformNotSupportedException(); /// Asserts that the handle's inheritability matches the specified value. protected static void AssertInheritability(SafeHandle handle, HandleInheritability inheritability) diff --git a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewAccessor.Tests.cs b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewAccessor.Tests.cs index 8fe35396ae804..adcfb0e9d4cc4 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewAccessor.Tests.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewAccessor.Tests.cs @@ -11,6 +11,7 @@ namespace System.IO.MemoryMappedFiles.Tests /// /// Tests for MemoryMappedViewAccessor. /// + [ActiveIssue("https://github.com/dotnet/runtime/issues/63240", typeof(PlatformDetection), nameof(PlatformDetection.IsOSX), nameof(PlatformDetection.IsArm64Process), nameof(PlatformDetection.IsNotMonoRuntime))] public class MemoryMappedViewAccessorTests : MemoryMappedFilesTestBase { /// diff --git a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewStream.Tests.cs b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewStream.Tests.cs index f279b8c33f98f..3a950662e5d49 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewStream.Tests.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewStream.Tests.cs @@ -11,6 +11,7 @@ namespace System.IO.MemoryMappedFiles.Tests /// /// Tests for MemoryMappedViewStream. /// + [ActiveIssue("https://github.com/dotnet/runtime/issues/63240", typeof(PlatformDetection), nameof(PlatformDetection.IsOSX), nameof(PlatformDetection.IsArm64Process), nameof(PlatformDetection.IsNotMonoRuntime))] public class MemoryMappedViewStreamTests : MemoryMappedFilesTestBase { /// diff --git a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewStreamConformanceTests.cs b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewStreamConformanceTests.cs index c190d329a00fe..1ec0b14fb8a15 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewStreamConformanceTests.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/tests/MemoryMappedViewStreamConformanceTests.cs @@ -45,6 +45,7 @@ private Task CreateStream(byte[] initialData, FileAccess access) } } + [ActiveIssue("https://github.com/dotnet/runtime/issues/63240", typeof(PlatformDetection), nameof(PlatformDetection.IsOSX), nameof(PlatformDetection.IsArm64Process), nameof(PlatformDetection.IsNotMonoRuntime))] public class AnonymousMemoryMappedViewStreamConformanceTests : MemoryMappedViewStreamConformanceTests { protected override MemoryMappedFile CreateFile(int length) => diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs index ecfd746602a2c..12da788ace902 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs @@ -369,7 +369,7 @@ private static int GetLengthOfParameterValue(string s, int startIndex) { Debug.Assert(s != null); - int length = 0; + int length; //if the parameter value does not start with a '"' then, //we expect a valid token. So we look for Linear White Spaces or diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs index 616111cc36cbf..15c89947da327 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackUriHelper.cs @@ -389,7 +389,7 @@ internal static string GetStringForPartUri(Uri partUri) if (partUri == null) return new ArgumentNullException(nameof(partUri)); - Exception? argumentException = null; + Exception? argumentException; argumentException = GetExceptionIfAbsoluteUri(partUri); if (argumentException != null) diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PartBasedPackageProperties.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PartBasedPackageProperties.cs index 20885d57997e3..20e59798df147 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PartBasedPackageProperties.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PartBasedPackageProperties.cs @@ -438,7 +438,7 @@ private void ReadPropertyValuesFromPackage() if (corePropertiesRelationship.TargetMode != TargetMode.Internal) throw new FileFormatException(SR.NoExternalTargetForMetadataRelationship); - PackagePart? propertiesPart = null; + PackagePart? propertiesPart; Uri propertiesPartUri = PackUriHelper.ResolvePartUri( PackUriHelper.PackageRootUri, corePropertiesRelationship.TargetUri); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs index df65e29fdf149..db69f44ecbb1b 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/XmlCompatibilityReader.cs @@ -339,7 +339,7 @@ private bool ReadEndElement(ref bool more) /// public override string GetAttribute(int i) { - string? result = null; + string? result; if (_ignoredAttributeCount == 0) { diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs index 8f4fd15ddfc5a..36938798542a4 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs @@ -260,7 +260,7 @@ internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFil : base(packageFileAccess) { ZipArchive? zipArchive = null; - ContentTypeHelper? contentTypeHelper = null; + ContentTypeHelper? contentTypeHelper; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; @@ -302,7 +302,7 @@ internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAc : base(packageFileAccess) { ZipArchive? zipArchive = null; - ContentTypeHelper? contentTypeHelper = null; + ContentTypeHelper? contentTypeHelper; _packageFileMode = packageFileMode; _packageFileAccess = packageFileAccess; diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs index 0c904b33c7c86..8c62382f50980 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/AnonymousPipeClientStream.cs @@ -30,8 +30,7 @@ public AnonymousPipeClientStream(PipeDirection direction, string pipeHandleAsStr } // Initialize SafePipeHandle from String and check if it's valid. First see if it's parseable - long result = 0; - bool parseable = long.TryParse(pipeHandleAsString, out result); + bool parseable = long.TryParse(pipeHandleAsString, out long result); if (!parseable) { throw new ArgumentException(SR.Argument_InvalidHandle, nameof(pipeHandleAsString)); diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs index a30e4abe46ad6..dd490acaecf62 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs @@ -517,7 +517,7 @@ private Interop.PollEvents PollEvents(int timeout, bool pollReadEvents, bool pol eventsToPoll |= Interop.PollEvents.POLLOUT; } - Interop.PollEvents events = Interop.PollEvents.POLLNONE; + Interop.PollEvents events; Interop.Error ret = Interop.Serial.Poll( _handle, eventsToPoll, diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs index 56f5ef5852226..2c9e86a822075 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs @@ -429,7 +429,7 @@ internal StopBits StopBits { Debug.Assert(!(value < StopBits.One || value > StopBits.OnePointFive), "An invalid value was passed to StopBits"); - byte nativeValue = 0; + byte nativeValue; if (value == StopBits.One) { nativeValue = Interop.Kernel32.DCBStopBits.ONESTOPBIT; @@ -1021,8 +1021,7 @@ internal unsafe int Read(byte[] array, int offset, int count, int timeout) } else { - int hr; - numBytes = ReadFileNative(array, offset, count, null, out hr); + numBytes = ReadFileNative(array, offset, count, null, out _); if (numBytes == -1) { throw Win32Marshal.GetExceptionForLastWin32Error(); @@ -1047,8 +1046,7 @@ internal unsafe int ReadByte(int timeout) } else { - int hr; - numBytes = ReadFileNative(_tempBuf, 0, 1, null, out hr); + numBytes = ReadFileNative(_tempBuf, 0, 1, null, out _); if (numBytes == -1) { throw Win32Marshal.GetExceptionForLastWin32Error(); @@ -1121,7 +1119,6 @@ internal unsafe void WriteByte(byte value, int timeout) int numBytes; - int hr; if (_isAsync) { IAsyncResult result = BeginWriteCore(_tempBuf, 0, 1, null, null); @@ -1133,7 +1130,7 @@ internal unsafe void WriteByte(byte value, int timeout) } else { - numBytes = WriteFileNative(_tempBuf, 0, 1, null, out hr); + numBytes = WriteFileNative(_tempBuf, 0, 1, null, out _); if (numBytes == -1) { // This is how writes timeout on Win9x. @@ -1334,8 +1331,7 @@ private unsafe SerialStreamAsyncResult BeginReadCore(byte[] array, int offset, i // queue an async ReadFile operation and pass in a packed overlapped //int r = ReadFile(_handle, array, numBytes, null, intOverlapped); - int hr = 0; - int r = ReadFileNative(array, offset, numBytes, intOverlapped, out hr); + int r = ReadFileNative(array, offset, numBytes, intOverlapped, out int hr); // ReadFile, the OS version, will return 0 on failure. But // my ReadFileNative wrapper returns -1. My wrapper will return @@ -1379,9 +1375,8 @@ private unsafe SerialStreamAsyncResult BeginWriteCore(byte[] array, int offset, asyncResult._overlapped = intOverlapped; - int hr = 0; // queue an async WriteFile operation and pass in a packed overlapped - int r = WriteFileNative(array, offset, numBytes, intOverlapped, out hr); + int r = WriteFileNative(array, offset, numBytes, intOverlapped, out int hr); // WriteFile, the OS version, will return 0 on failure. But // my WriteFileNative wrapper returns -1. My wrapper will return @@ -1762,8 +1757,6 @@ private void CallErrorEvents(object state) if ((errors & (int)SerialError.Frame) != 0) stream.ErrorReceived(stream, new SerialErrorReceivedEventArgs(SerialError.Frame)); } - - stream = null; } private void CallReceiveEvents(object state) @@ -1780,8 +1773,6 @@ private void CallReceiveEvents(object state) if ((nativeEvents & (int)SerialData.Eof) != 0) stream.DataReceived(stream, new SerialDataReceivedEventArgs(SerialData.Eof)); } - - stream = null; } private void CallPinEvents(object state) @@ -1809,8 +1800,6 @@ private void CallPinEvents(object state) if ((nativeEvents & (int)SerialPinChange.Break) != 0) stream.PinChanged(stream, new SerialPinChangedEventArgs(SerialPinChange.Break)); } - - stream = null; } } diff --git a/src/libraries/System.Management/src/System.Management.csproj b/src/libraries/System.Management/src/System.Management.csproj index a90719285f052..d79acc744ac2f 100644 --- a/src/libraries/System.Management/src/System.Management.csproj +++ b/src/libraries/System.Management/src/System.Management.csproj @@ -4,7 +4,7 @@ $(NoWarn);0618 - $(NoWarn);CA1845 + $(NoWarn);CA1845;IDE0059 annotations true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0 diff --git a/src/libraries/System.Management/tests/System/Management/ManagementObjectTests.cs b/src/libraries/System.Management/tests/System/Management/ManagementObjectTests.cs index 4c349613a352f..15f0f6b48f6e9 100644 --- a/src/libraries/System.Management/tests/System/Management/ManagementObjectTests.cs +++ b/src/libraries/System.Management/tests/System/Management/ManagementObjectTests.cs @@ -5,6 +5,7 @@ using System.IO; using System.Runtime.Serialization.Formatters.Binary; using Xunit; +using Xunit.Sdk; namespace System.Management.Tests { @@ -64,28 +65,33 @@ public void Set_Property_Win32_ComputerSystem() [OuterLoop] public void Invoke_Instance_And_Static_Method_Win32_Process() { - var processClass = new ManagementClass("Win32_Process"); - object[] methodArgs = { "notepad.exe", null, null, 0 }; + // Retries are sometimes necessary as underlying API call can return + // ERROR_NOT_READY or occasionally ERROR_INVALID_BLOCK or ERROR_NOT_ENOUGH_MEMORY + RetryHelper.Execute(() => + { + var processClass = new ManagementClass("Win32_Process"); + object[] methodArgs = { "notepad.exe", null, null, 0 }; - object resultObj = processClass.InvokeMethod("Create", methodArgs); + object resultObj = processClass.InvokeMethod("Create", methodArgs); - var resultCode = (uint)resultObj; - Assert.Equal(0u, resultCode); + var resultCode = (uint)resultObj; + Assert.Equal(0u, resultCode); - var processId = (uint)methodArgs[3]; - Assert.True(0u != processId, $"Unexpected process ID: {processId}"); + var processId = (uint)methodArgs[3]; + Assert.True(0u != processId, $"Unexpected process ID: {processId}"); - using (Process targetProcess = Process.GetProcessById((int)processId)) - using (var process = new ManagementObject($"Win32_Process.Handle=\"{processId}\"")) - { - Assert.False(targetProcess.HasExited); + using (Process targetProcess = Process.GetProcessById((int)processId)) + using (var process = new ManagementObject($"Win32_Process.Handle=\"{processId}\"")) + { + Assert.False(targetProcess.HasExited); - resultObj = process.InvokeMethod("Terminate", new object[] { 0 }); - resultCode = (uint)resultObj; - Assert.Equal(0u, resultCode); + resultObj = process.InvokeMethod("Terminate", new object[] { 0 }); + resultCode = (uint)resultObj; + Assert.Equal(0u, resultCode); - Assert.True(targetProcess.HasExited); - } + Assert.True(targetProcess.HasExited); + } + }, maxAttempts: 10, retryWhen: e => e is XunitException); } [ConditionalFact(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))] diff --git a/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs b/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs index 97658fb8531c0..11ec18302bd03 100644 --- a/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs +++ b/src/libraries/System.Memory/src/System/Text/EncodingExtensions.cs @@ -59,7 +59,7 @@ public static long GetBytes(this Encoding encoding, ReadOnlySpan chars, IB { // Allocate a stateful Encoder instance and chunk this. - Convert(encoding.GetEncoder(), chars, writer, flush: true, out long totalBytesWritten, out bool completed); + Convert(encoding.GetEncoder(), chars, writer, flush: true, out long totalBytesWritten, out _); return totalBytesWritten; } } @@ -95,7 +95,7 @@ public static long GetBytes(this Encoding encoding, in ReadOnlySequence ch } else { - Convert(encoding.GetEncoder(), chars, writer, flush: true, out long bytesWritten, out bool completed); + Convert(encoding.GetEncoder(), chars, writer, flush: true, out long bytesWritten, out _); return bytesWritten; } } @@ -270,7 +270,7 @@ public static long GetChars(this Encoding encoding, ReadOnlySpan bytes, IB { // Allocate a stateful Decoder instance and chunk this. - Convert(encoding.GetDecoder(), bytes, writer, flush: true, out long totalCharsWritten, out bool completed); + Convert(encoding.GetDecoder(), bytes, writer, flush: true, out long totalCharsWritten, out _); return totalCharsWritten; } } @@ -306,7 +306,7 @@ public static long GetChars(this Encoding encoding, in ReadOnlySequence by } else { - Convert(encoding.GetDecoder(), bytes, writer, flush: true, out long charsWritten, out bool completed); + Convert(encoding.GetDecoder(), bytes, writer, flush: true, out long charsWritten, out _); return charsWritten; } } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs index cc8ef875b9d71..976b40250a6c3 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/TranscodingReadStream.cs @@ -139,7 +139,7 @@ private async Task ReadAsyncCore(ArraySegment readBuffer, Cancellatio } _encoder.Convert(_charBuffer.Array!, _charBuffer.Offset, _charBuffer.Count, _overflowBuffer.Array!, byteIndex: 0, _overflowBuffer.Array!.Length, - flush: shouldFlushEncoder, out int overFlowChars, out int overflowBytes, out completed); + flush: shouldFlushEncoder, out int overFlowChars, out int overflowBytes, out _); Debug.Assert(overflowBytes > 0 && overFlowChars > 0, "We expect writes to the overflow buffer to always succeed since it is large enough to accommodate at least one char."); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs index b0b6d86c67541..a8a364a8aaa81 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpAuthHelper.cs @@ -51,9 +51,8 @@ public void CheckResponseForAuthentication( ref uint proxyAuthScheme, ref uint serverAuthScheme) { - uint supportedSchemes = 0; - uint firstSchemeIgnored = 0; - uint authTarget = 0; + uint supportedSchemes; + uint authTarget; Debug.Assert(state.RequestMessage != null); Debug.Assert(state.RequestMessage.RequestUri != null); @@ -87,7 +86,7 @@ public void CheckResponseForAuthentication( if (!Interop.WinHttp.WinHttpQueryAuthSchemes( state.RequestHandle, out supportedSchemes, - out firstSchemeIgnored, + out _, out authTarget)) { // WinHTTP returns an error for schemes it doesn't handle. @@ -140,7 +139,7 @@ public void CheckResponseForAuthentication( if (!Interop.WinHttp.WinHttpQueryAuthSchemes( state.RequestHandle, out supportedSchemes, - out firstSchemeIgnored, + out _, out authTarget)) { // WinHTTP returns an error for schemes it doesn't handle. @@ -244,7 +243,7 @@ public bool GetServerCredentialsFromCache( serverAuthScheme = 0; serverCredentials = null; - NetworkCredential? cred = null; + NetworkCredential? cred; lock (_credentialCacheLock) { diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpChannelBinding.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpChannelBinding.cs index 9d3dbc8145367..de47f6caaa25d 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpChannelBinding.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpChannelBinding.cs @@ -18,14 +18,13 @@ internal sealed class WinHttpChannelBinding : ChannelBinding internal WinHttpChannelBinding(SafeWinHttpHandle requestHandle) { - IntPtr data = IntPtr.Zero; uint dataSize = 0; if (!Interop.WinHttp.WinHttpQueryOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SERVER_CBT, IntPtr.Zero, ref dataSize)) { if (Marshal.GetLastWin32Error() == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { - data = Marshal.AllocHGlobal((int)dataSize); + IntPtr data = Marshal.AllocHGlobal((int)dataSize); if (Interop.WinHttp.WinHttpQueryOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SERVER_CBT, data, ref dataSize)) { diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs index 07133b2667c22..a081b7b4d0045 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs @@ -1442,7 +1442,7 @@ private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestH return; } - X509Certificate2? clientCertificate = null; + X509Certificate2? clientCertificate; if (_clientCertificateOption == ClientCertificateOption.Manual) { clientCertificate = CertificateHelper.GetEligibleClientCertificate(ClientCertificates); diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseHeaderReader.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseHeaderReader.cs index f2e3292321ced..bab82d3baa81c 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseHeaderReader.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseHeaderReader.cs @@ -78,9 +78,7 @@ public bool ReadHeader([NotNullWhen(true)] out string? name, [NotNullWhen(true)] /// true if the next line was read successfully, or false if all characters have been read. public bool ReadLine() { - int startIndex; - int length; - return ReadLine(out startIndex, out length); + return ReadLine(out _, out _); } /// diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AuthenticationHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AuthenticationHeaderValue.cs index a3197527d80a6..3ab1b98097020 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AuthenticationHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/AuthenticationHeaderValue.cs @@ -199,7 +199,7 @@ private static bool TrySkipFirstBlob(string input, ref int current, ref int para { if (input[current] == '"') { - int quotedStringLength = 0; + int quotedStringLength; if (HttpRuleParser.GetQuotedStringLength(input, current, out quotedStringLength) != HttpParseResult.Parsed) { @@ -241,8 +241,7 @@ private static bool TryGetParametersEndIndex(string input, ref int parseEndIndex { current++; // skip ',' delimiter - bool separatorFound = false; // ignore value returned by GetNextNonEmptyOrWhitespaceIndex() - current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound); + current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out _); if (current == input.Length) { return true; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/BaseHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/BaseHeaderParser.cs index e22e1c5800e56..1c8df35e50be8 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/BaseHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/BaseHeaderParser.cs @@ -41,7 +41,7 @@ public sealed override bool TryParseValue(string? value, object? storeValue, ref return SupportsMultipleValues; } - bool separatorFound = false; + bool separatorFound; int current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(value, index, SupportsMultipleValues, out separatorFound); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs index ca7d533532d9d..8eacd11d6691d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/CacheControlHeaderValue.cs @@ -545,12 +545,11 @@ private static bool TrySetOptionalTokenList(NameValueHeaderValue nameValue, ref // We have a quoted string. Now verify that the string contains a list of valid tokens separated by ','. int current = 1; // skip the initial '"' character. int maxLength = valueString.Length - 1; // -1 because we don't want to parse the final '"'. - bool separatorFound = false; int originalValueCount = destination == null ? 0 : destination.Count; while (current < maxLength) { current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(valueString, current, true, - out separatorFound); + out _); if (current == maxLength) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs index d94618a19d09c..074aedf91a1fe 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs @@ -384,7 +384,7 @@ private void SetName(string parameter, string? value) } else { - string processedValue = string.Empty; + string processedValue; if (parameter.EndsWith('*')) { processedValue = HeaderUtilities.Encode5987(value); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs index c9aab0f9346c4..97015936e8b5b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs @@ -236,9 +236,9 @@ internal static int GetContentRangeLength(string? input, int startIndex, out obj // Read range values and in ' -/' int fromStartIndex = current; - int fromLength = 0; - int toStartIndex = 0; - int toLength = 0; + int fromLength; + int toStartIndex; + int toLength; if (!TryGetRangeLength(input, ref current, out fromLength, out toStartIndex, out toLength)) { return 0; @@ -260,7 +260,7 @@ internal static int GetContentRangeLength(string? input, int startIndex, out obj // We may not have a length (e.g. 'bytes 1-2/*'). But if we do, parse the length now. int lengthStartIndex = current; - int lengthLength = 0; + int lengthLength; if (!TryGetLengthLength(input, ref current, out lengthLength)) { return 0; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/EntityTagHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/EntityTagHeaderValue.cs index 7725c0031861c..f3c1f07e1021f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/EntityTagHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/EntityTagHeaderValue.cs @@ -39,7 +39,7 @@ public EntityTagHeaderValue(string tag, bool isWeak) { throw new ArgumentException(SR.net_http_argument_empty_string, nameof(tag)); } - int length = 0; + int length; if ((HttpRuleParser.GetQuotedStringLength(tag, 0, out length) != HttpParseResult.Parsed) || (length != tag.Length)) { @@ -147,13 +147,12 @@ internal static int GetEntityTagLength(string? input, int startIndex, out Entity } int tagStartIndex = current; - int tagLength = 0; + int tagLength; if (HttpRuleParser.GetQuotedStringLength(input, current, out tagLength) != HttpParseResult.Parsed) { return 0; } - parsedValue = new EntityTagHeaderValue(); if (tagLength == input.Length) { // Most of the time we'll have strong ETags without leading/trailing whitespace. diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/GenericHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/GenericHeaderParser.cs index c6ec5e5b0b766..9e93c595f377e 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/GenericHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/GenericHeaderParser.cs @@ -133,9 +133,9 @@ private static int ParseWithoutValidation(string value, int startIndex, out obje private static int ParseHost(string value, int startIndex, out object? parsedValue) { - int hostLength = HttpRuleParser.GetHostLength(value, startIndex, false, out string? host); + int hostLength = HttpRuleParser.GetHostLength(value, startIndex, false); - parsedValue = host; + parsedValue = value.Substring(startIndex, hostLength); return hostLength; } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs index addd5ae321d04..6cc82433278f7 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs @@ -130,7 +130,7 @@ private static void AddHexEscaped(byte c, StringBuilder destination) { // Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal // separator is considered invalid (even if the current culture would allow it). - double qualityValue = 0; + double qualityValue; if (double.TryParse(qualityParameter.Value, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out qualityValue)) { @@ -162,7 +162,7 @@ internal static void CheckValidComment(string value, string parameterName) throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } - int length = 0; + int length; if ((HttpRuleParser.GetCommentLength(value, 0, out length) != HttpParseResult.Parsed) || (length != value.Length)) // no trailing spaces allowed { @@ -177,7 +177,7 @@ internal static void CheckValidQuotedString(string value, string parameterName) throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } - int length = 0; + int length; if ((HttpRuleParser.GetQuotedStringLength(value, 0, out length) != HttpParseResult.Parsed) || (length != value.Length)) // no trailing spaces allowed { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs index 684728b19c55b..9a278ff118319 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs @@ -113,7 +113,7 @@ public string? Host value = null; } - if ((value != null) && (HttpRuleParser.GetHostLength(value, 0, false, out string? _) != value.Length)) + if ((value != null) && (HttpRuleParser.GetHostLength(value, 0, false) != value.Length)) { throw new FormatException(SR.net_http_headers_invalid_host_header); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs index 2b052aca7be64..72ea43b3f5a84 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs @@ -40,7 +40,7 @@ protected override int GetParsedValueLength(string value, int startIndex, object return 0; } - int result = 0; + int result; if (!HeaderUtilities.TryParseInt32(value, startIndex, numberLength, out result)) { return 0; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs index 12768a73d03cb..771b9fa65d775 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs @@ -40,7 +40,7 @@ protected override int GetParsedValueLength(string value, int startIndex, object return 0; } - long result = 0; + long result; if (!HeaderUtilities.TryParseInt64(value, startIndex, numberLength, out result)) { return 0; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs index d04ac66156903..4c69dec3e8083 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ProductInfoHeaderValue.cs @@ -135,11 +135,11 @@ internal static int GetProductInfoLength(string? input, int startIndex, out Prod int current = startIndex; // Caller must remove leading whitespace. - string? comment = null; - ProductHeaderValue? product = null; + string? comment; + ProductHeaderValue? product; if (input[current] == '(') { - int commentLength = 0; + int commentLength; if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed) { return 0; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs index 91262983d8cdf..8c14da848b1d0 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs @@ -110,8 +110,7 @@ internal static int GetRangeItemListLength(string? input, int startIndex, } // Empty segments are allowed, so skip all delimiter-only segments (e.g. ", ,"). - bool separatorFound = false; - int current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out separatorFound); + int current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, startIndex, true, out _); // It's OK if we didn't find leading separator characters. Ignore 'separatorFound'. if (current == input.Length) @@ -132,7 +131,7 @@ internal static int GetRangeItemListLength(string? input, int startIndex, rangeCollection.Add(range!); current = current + rangeLength; - current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound); + current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out bool separatorFound); // If the string is not consumed, we must have a delimiter, otherwise the string is not a valid // range list. diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs index 1d5f56c8803d5..653f228ccdfe6 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs @@ -34,7 +34,7 @@ protected override int GetParsedValueLength(string value, int startIndex, object return 0; } - int result = 0; + int result; if (!HeaderUtilities.TryParseInt32(value, startIndex, numberLength, out result)) { return 0; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ViaHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ViaHeaderValue.cs index 6f7ebdd49482e..90f8a69292c70 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ViaHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ViaHeaderValue.cs @@ -176,21 +176,22 @@ internal static int GetViaLength(string? input, int startIndex, out object? pars Debug.Assert(protocolVersion != null); // Read in '[/] []' - int receivedByLength = HttpRuleParser.GetHostLength(input, current, true, out string? receivedBy); - + int receivedByLength = HttpRuleParser.GetHostLength(input, current, true); if (receivedByLength == 0) { return 0; } + string receivedBy = input.Substring(current, receivedByLength); current = current + receivedByLength; + current = current + HttpRuleParser.GetWhitespaceLength(input, current); string? comment = null; if ((current < input.Length) && (input[current] == '(')) { // We have a in '[/] []' - int commentLength = 0; + int commentLength; if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed) { return 0; // We found a '(' character but it wasn't a valid comment. Abort. @@ -281,7 +282,7 @@ private static void CheckReceivedBy(string receivedBy) // 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value // is a valid host.; - if (HttpRuleParser.GetHostLength(receivedBy, 0, true, out string? host) != receivedBy.Length) + if (HttpRuleParser.GetHostLength(receivedBy, 0, true) != receivedBy.Length) { throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, receivedBy)); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs index caa70684ec7df..6c358f1dc5865 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs @@ -172,13 +172,13 @@ internal static int GetWarningLength(string? input, int startIndex, out object? } // Read in ' [""]' - if (!TryReadAgent(input, current, ref current, out string? agent)) + if (!TryReadAgent(input, ref current, out string? agent)) { return 0; } // Read in ' [""]' - int textLength = 0; + int textLength; int textStartIndex = current; if (HttpRuleParser.GetQuotedStringLength(input, current, out textLength) != HttpParseResult.Parsed) { @@ -190,7 +190,7 @@ internal static int GetWarningLength(string? input, int startIndex, out object? current = current + textLength; // Read in ' [""]' - DateTimeOffset? date = null; + DateTimeOffset? date; if (!TryReadDate(input, ref current, out date)) { return 0; @@ -203,16 +203,19 @@ internal static int GetWarningLength(string? input, int startIndex, out object? return current - startIndex; } - private static bool TryReadAgent(string input, int startIndex, ref int current, [NotNullWhen(true)] out string? agent) + private static bool TryReadAgent(string input, ref int current, [NotNullWhen(true)] out string? agent) { - int agentLength = HttpRuleParser.GetHostLength(input, startIndex, true, out agent!); + agent = null; + int agentLength = HttpRuleParser.GetHostLength(input, current, true); if (agentLength == 0) { return false; } + agent = input.Substring(current, agentLength); current = current + agentLength; + int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current); current = current + whitespaceLength; @@ -328,7 +331,7 @@ private static void CheckAgent(string agent) // 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value // is a valid host. - if (HttpRuleParser.GetHostLength(agent, 0, true, out string? host) != agent.Length) + if (HttpRuleParser.GetHostLength(agent, 0, true) != agent.Length) { throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, agent)); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs index 90bd0ad0251bd..5c907ad6150b7 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpContent.cs @@ -606,7 +606,7 @@ protected virtual Task CreateContentReadStreamAsync(CancellationToken ca // again; just return null. if (_canCalculateLength) { - long length = 0; + long length; if (TryComputeLength(out length)) { return length; diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRuleParser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRuleParser.cs index 2e7390099282b..e64125f0fb5f2 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpRuleParser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpRuleParser.cs @@ -196,12 +196,11 @@ internal static int GetNumberLength(string input, int startIndex, bool allowDeci return current - startIndex; } - internal static int GetHostLength(string input, int startIndex, bool allowToken, out string? host) + internal static int GetHostLength(string input, int startIndex, bool allowToken) { Debug.Assert(input != null); Debug.Assert(startIndex >= 0); - host = null; if (startIndex >= input.Length) { return 0; @@ -236,13 +235,11 @@ internal static int GetHostLength(string input, int startIndex, bool allowToken, return 0; } - string result = input.Substring(startIndex, length); - if ((!allowToken || !isToken) && !IsValidHostName(result)) + if ((!allowToken || !isToken) && !IsValidHostName(input.AsSpan(startIndex, length))) { return 0; } - host = result; return length; } @@ -311,7 +308,7 @@ private static HttpParseResult GetExpressionLength(string input, int startIndex, { // Only check whether we have a quoted char, if we have at least 3 characters left to read (i.e. // quoted char + closing char). Otherwise the closing char may be considered part of the quoted char. - int quotedPairLength = 0; + int quotedPairLength; if ((current + 2 < input.Length) && (GetQuotedPairLength(input, current, out quotedPairLength) == HttpParseResult.Parsed)) { @@ -338,7 +335,7 @@ private static HttpParseResult GetExpressionLength(string input, int startIndex, return HttpParseResult.InvalidFormat; } - int nestedLength = 0; + int nestedLength; HttpParseResult nestedResult = GetExpressionLength(input, current, openChar, closeChar, supportsNesting, nestedCount + 1, out nestedLength); @@ -379,10 +376,10 @@ private static HttpParseResult GetExpressionLength(string input, int startIndex, return HttpParseResult.InvalidFormat; } - private static bool IsValidHostName(string host) + private static bool IsValidHostName(ReadOnlySpan host) { // Also add user info (u@) to make sure 'host' doesn't include user info. - return Uri.TryCreate("http://u@" + host + "/", UriKind.Absolute, out Uri? hostUri); + return Uri.TryCreate($"http://u@{host}/", UriKind.Absolute, out _); } } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs index 234ca135aa9bd..c754dff03e59d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs @@ -422,31 +422,25 @@ private void Parse(string challenge) internal static class StringBuilderExtensions { - // Characters that require escaping in quoted string - private static readonly char[] SpecialCharacters = new[] { '"', '\\' }; - public static void AppendKeyValue(this StringBuilder sb, string key, string value, bool includeQuotes = true, bool includeComma = true) { - sb.Append(key); - sb.Append('='); + sb.Append(key).Append('='); + if (includeQuotes) { + ReadOnlySpan valueSpan = value; sb.Append('"'); - int lastSpecialIndex = 0; - int specialIndex; while (true) { - specialIndex = value.IndexOfAny(SpecialCharacters, lastSpecialIndex); - if (specialIndex >= 0) + int i = valueSpan.IndexOfAny('"', '\\'); // Characters that require escaping in quoted string + if (i >= 0) { - sb.Append(value, lastSpecialIndex, specialIndex - lastSpecialIndex); - sb.Append('\\'); - sb.Append(value[specialIndex]); - lastSpecialIndex = specialIndex + 1; + sb.Append(valueSpan.Slice(0, i)).Append('\\').Append(valueSpan[i]); + valueSpan = valueSpan.Slice(i + 1); } else { - sb.Append(value, lastSpecialIndex, value.Length - lastSpecialIndex); + sb.Append(valueSpan); break; } } @@ -459,8 +453,7 @@ public static void AppendKeyValue(this StringBuilder sb, string key, string valu if (includeComma) { - sb.Append(','); - sb.Append(' '); + sb.Append(',').Append(' '); } } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpWindowsProxy.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpWindowsProxy.cs index 176b35c740196..bd7d03388c723 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpWindowsProxy.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpWindowsProxy.cs @@ -78,7 +78,6 @@ private HttpWindowsProxy(WinInetProxyHelper proxyHelper, SafeWinHttpHandle? sess if (!string.IsNullOrWhiteSpace(proxyHelper.ProxyBypass)) { int idx = 0; - int start = 0; string? tmp; // Process bypass list for manual setting. @@ -104,7 +103,7 @@ private HttpWindowsProxy(WinInetProxyHelper proxyHelper, SafeWinHttpHandle? sess idx += 1; } - start = idx; + int start = idx; while (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ' ' && proxyHelper.ProxyBypass[idx] != ';' && proxyHelper.ProxyBypass[idx] != ']') { idx += 1; }; if (idx == start) diff --git a/src/libraries/System.Net.Http/tests/UnitTests/HttpRuleParserTest.cs b/src/libraries/System.Net.Http/tests/UnitTests/HttpRuleParserTest.cs index 707ddae2f4658..35b3f60768087 100644 --- a/src/libraries/System.Net.Http/tests/UnitTests/HttpRuleParserTest.cs +++ b/src/libraries/System.Net.Http/tests/UnitTests/HttpRuleParserTest.cs @@ -377,9 +377,14 @@ private static void AssertGetCommentLength(string input, int startIndex, int exp private static void AssertGetHostLength(string input, int startIndex, int expectedLength, bool allowToken, string expectedResult) { - string result = null; - Assert.Equal(expectedLength, HttpRuleParser.GetHostLength(input, startIndex, allowToken, out result)); - Assert.Equal(expectedResult, result); + int length = HttpRuleParser.GetHostLength(input, startIndex, allowToken); + Assert.Equal(expectedLength, length); + + if (length != 0) + { + string result = input.Substring(startIndex, length); + Assert.Equal(expectedResult, result); + } } #endregion } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs index 640b7f6bde309..adad957f1321c 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs @@ -110,7 +110,7 @@ public HttpListenerPrefixCollection Prefixes internal void AddPrefix(string uriPrefix) { - string? registeredPrefix = null; + string? registeredPrefix; try { if (uriPrefix == null) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs index c070c93dfc680..5bfecb4453ef0 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs @@ -327,7 +327,7 @@ private static class Helpers return null; // parse the value - string? attrValue = null; + string? attrValue; int j; @@ -567,7 +567,7 @@ internal static void FillFromString(NameValueCollection nvc, string s, bool urle // extract the name / value pair string? name = null; - string? value = null; + string? value; if (ti >= 0) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs index f078b5bdbee6a..24bbe30b5937b 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs @@ -94,7 +94,7 @@ private void BuildRequestUriUsingCookedPath() private void BuildRequestUriUsingRawPath() { - bool isValid = false; + bool isValid; // Initialize 'rawPath' only if really needed; i.e. if we build the request Uri from the raw Uri. _rawPath = GetPath(_rawUri); @@ -172,7 +172,7 @@ private ParsingResult ParseRawPath(Encoding encoding) Debug.Assert(encoding != null, "'encoding' must be assigned."); int index = 0; - char current = '\0'; + char current; Debug.Assert(_rawPath != null); while (index < _rawPath.Length) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs index b81824bc4c0a3..1a9ab35dc0528 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs @@ -332,7 +332,7 @@ private State ReadCRLF(byte[] buffer, ref int offset, int size) private State ReadTrailer(byte[] buffer, ref int offset, int size) { - char c = '\0'; + char c; // short path if (_trailerState == 2 && (char)buffer[offset] == '\r' && _saved.Length == 0) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs index fe4fc17f851d4..58d9b2029bdf0 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs @@ -253,7 +253,7 @@ private static void OnRead(IAsyncResult ares) private void OnReadInternal(IAsyncResult ares) { _timer.Change(Timeout.Infinite, Timeout.Infinite); - int nread = -1; + int nread; try { nread = _stream.EndRead(ares); @@ -376,7 +376,6 @@ private bool ProcessInput(MemoryStream ms) if (_inputState == InputState.RequestLine) continue; _currentLine = null; - ms = null!; return true; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs index a0d62b816ec22..49b2b7318742a 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs @@ -134,7 +134,7 @@ private static HttpEndPointListener GetEPListener(string host, int port, HttpLis } } - Dictionary? p = null; + Dictionary? p; if (s_ipEndPoints.ContainsKey(addr)) { p = s_ipEndPoints[addr]; @@ -145,7 +145,7 @@ private static HttpEndPointListener GetEPListener(string host, int port, HttpLis s_ipEndPoints[addr] = p; } - HttpEndPointListener? epl = null; + HttpEndPointListener? epl; if (p.ContainsKey(port)) { epl = p[port]; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs index cddfa7e5b6670..c5cc376f02b0f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs @@ -46,7 +46,7 @@ internal void ParseAuthentication(AuthenticationSchemes expectedSchemes) } internal IPrincipal? ParseBasicAuthentication(string authData) => - TryParseBasicAuth(authData, out HttpStatusCode errorCode, out string? username, out string? password) ? + TryParseBasicAuth(authData, out _, out string? username, out string? password) ? new GenericPrincipal(new HttpListenerBasicIdentity(username, password), Array.Empty()) : null; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs index 13a9d26c9890c..5aa170f8b7403 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs @@ -55,7 +55,7 @@ internal HttpResponseStream(Stream stream, HttpListenerResponse response, bool i private void DisposeCore() { - byte[]? bytes = null; + byte[]? bytes; MemoryStream? ms = GetHeaders(true); bool chunked = _response.SendChunked; if (_stream.CanWrite) @@ -169,7 +169,7 @@ private void WriteCore(byte[] buffer, int offset, int size) if (size == 0) return; - byte[]? bytes = null; + byte[]? bytes; MemoryStream? ms = GetHeaders(false); bool chunked = _response.SendChunked; if (ms != null) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs index 7ccc90973af94..5284f810fca36 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs @@ -84,8 +84,7 @@ public ServiceNameStore() port = hostAndPort.Substring(colonIndex + 1); // Excludes colon // Loosely validate the port just to make sure it was a port and not something else - ushort portValue; - if (!ushort.TryParse(port, NumberStyles.Integer, CultureInfo.InvariantCulture, out portValue)) + if (!ushort.TryParse(port, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) { return inputServiceName; } @@ -281,10 +280,9 @@ public string[] BuildServiceNames(string uriPrefix) { string hostname = ExtractHostname(uriPrefix, true)!; - IPAddress? ipAddress = null; if (string.Equals(hostname, "*", StringComparison.OrdinalIgnoreCase) || string.Equals(hostname, "+", StringComparison.OrdinalIgnoreCase) || - IPAddress.TryParse(hostname, out ipAddress)) + IPAddress.TryParse(hostname, out _)) { // for a wildcard, register the machine name. If the caller doesn't have DNS permission // or the query fails for some reason, don't add an SPN. diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 48076f1b39a82..5e2dedd9fd78f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -96,15 +96,13 @@ public bool UnsafeConnectionNtlmAuthentication private void SetUrlGroupProperty(Interop.HttpApi.HTTP_SERVER_PROPERTY property, IntPtr info, uint infosize) { - uint statusCode = Interop.HttpApi.ERROR_SUCCESS; - Debug.Assert(_urlGroupId != 0, "SetUrlGroupProperty called with invalid url group id"); Debug.Assert(info != IntPtr.Zero, "SetUrlGroupProperty called with invalid pointer"); // // Set the url group property using Http Api. // - statusCode = Interop.HttpApi.HttpSetUrlGroupProperty( + uint statusCode = Interop.HttpApi.HttpSetUrlGroupProperty( _urlGroupId, property, info, infosize); if (statusCode != Interop.HttpApi.ERROR_SUCCESS) @@ -153,7 +151,6 @@ public HttpListenerTimeoutManager TimeoutManager private void SetupV2Config() { - uint statusCode = Interop.HttpApi.ERROR_SUCCESS; ulong id = 0; // @@ -175,7 +172,7 @@ private void SetupV2Config() try { - statusCode = Interop.HttpApi.HttpCreateServerSession( + uint statusCode = Interop.HttpApi.HttpCreateServerSession( Interop.HttpApi.s_version, &id, 0); if (statusCode != Interop.HttpApi.ERROR_SUCCESS) @@ -1288,9 +1285,8 @@ internal void SetAuthenticationHeaders(HttpListenerContext context) HttpListenerResponse response = context.Response; // We use the cached results from the delegates so that we don't have to call them again here. - NTAuthentication? newContext; ArrayList? challenges = BuildChallenge(context.AuthenticationSchemes, request._connectionId, - out newContext, context.ExtendedProtectionPolicy, request.IsSecureConnection); + out _, context.ExtendedProtectionPolicy, request.IsSecureConnection); // Setting 401 without setting WWW-Authenticate is a protocol violation // but throwing from HttpListener would be a breaking change. diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs index ecbadd5943c9f..214416962eba7 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs @@ -307,7 +307,7 @@ internal void IOCompleted(uint errorCode, uint numBytes) private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode:x8} numBytes: {numBytes}"); - object? result = null; + object? result; try { if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs index d41ff445938cd..6451497525053 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs @@ -186,7 +186,7 @@ internal void IOCompleted(uint errorCode, uint numBytes) private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:0x{errorCode:x8} numBytes: {numBytes}"); - object? result = null; + object? result; try { if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs index 67437df45f46e..d32841971016e 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs @@ -194,8 +194,7 @@ private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs) eventArgs.StartOperationCommon(this, _inputStream.InternalHttpContext.RequestQueueBoundHandle); eventArgs.StartOperationReceive(); - uint statusCode = 0; - bool completedAsynchronouslyOrWithError = false; + bool completedAsynchronouslyOrWithError; try { Debug.Assert(eventArgs.Buffer != null, "'BufferList' is not supported for read operations."); @@ -242,7 +241,7 @@ private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs) uint flags = 0; uint bytesReturned = 0; - statusCode = + uint statusCode = Interop.HttpApi.HttpReceiveRequestEntityBody( _inputStream.InternalHttpContext.RequestQueueHandle, _inputStream.InternalHttpContext.RequestId, @@ -445,7 +444,7 @@ private unsafe bool WriteAsyncFast(HttpListenerAsyncEventArgs eventArgs) eventArgs.StartOperationSend(); uint statusCode; - bool completedAsynchronouslyOrWithError = false; + bool completedAsynchronouslyOrWithError; try { if (_outputStream.Closed || diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs index 2402dd36c0f09..53da835ab8165 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs @@ -225,9 +225,6 @@ internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] pr HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } - IntPtr responseHeadersPtr; - uint responseHeaderCount; - // Currently the WSPC doesn't allow to initiate a data session // without also being involved in the http handshake // There is no information whatsoever, which is needed by the @@ -243,8 +240,8 @@ internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] pr 0, s_ServerFakeRequestHeaders!, (uint)s_ServerFakeRequestHeaders!.Length, - out responseHeadersPtr, - out responseHeaderCount); + out _, + out _); ThrowOnError(errorCode); @@ -421,9 +418,7 @@ private static void DrainActionQueue(SafeHandle webSocketHandle, ActionQueue act "'webSocketHandle' MUST NOT be NULL or INVALID."); IntPtr actionContext; - IntPtr dummy; Action action; - BufferType bufferType; while (true) { @@ -434,8 +429,8 @@ private static void DrainActionQueue(SafeHandle webSocketHandle, ActionQueue act dataBuffers, ref dataBufferCount, out action, - out bufferType, - out dummy, + out _, + out _, out actionContext); if (!Succeeded(errorCode)) diff --git a/src/libraries/System.Net.Mail/src/System/Net/BufferedReadStream.cs b/src/libraries/System.Net.Mail/src/System/Net/BufferedReadStream.cs index 8c8b778f74c79..da6c7eb2972ee 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/BufferedReadStream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/BufferedReadStream.cs @@ -74,7 +74,7 @@ public override int Read(byte[] buffer, int offset, int count) public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - int read = 0; + int read; if (_storedOffset >= _storedLength) { return base.ReadAsync(buffer, offset, count, cancellationToken); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs index 0ea9aa12af67e..aaca28f6a4c8c 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs @@ -12,7 +12,6 @@ public abstract class AttachmentBase : IDisposable { internal bool disposed; private readonly MimePart _part = new MimePart(); - private static readonly char[] s_contentCIDInvalidChars = new char[] { '<', '>' }; internal AttachmentBase() { @@ -248,7 +247,7 @@ public string ContentId } else { - if (value.IndexOfAny(s_contentCIDInvalidChars) != -1) + if (value.AsSpan().IndexOfAny('<', '>') >= 0) // invalid chars { throw new ArgumentException(SR.MailHeaderInvalidCID, nameof(value)); } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs index f5ea92bf4e837..1acfc449c5afd 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs @@ -284,7 +284,7 @@ public override int GetHashCode() // Encodes the full email address, folding as needed internal string Encode(int charsConsumed, bool allowUnicode) { - string encodedAddress = string.Empty; + string encodedAddress; IEncodableStream encoder; Debug.Assert(Address != null, "address was null"); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs index 67db9ed4c3956..4e7ad597cabf9 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs @@ -377,7 +377,7 @@ private void SetContent(bool allowUnicode) { // we should not unnecessarily use Multipart/Mixed // When there is no attachement and all the alternative views are of "Alternative" types. - MimeMultiPart? part = null; + MimeMultiPart? part; MimeMultiPart viewsPart = new MimeMultiPart(MimeMultiPartType.Alternative); if (!string.IsNullOrEmpty(_body)) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs index aed784ce95b50..53e41d8f86e6c 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs @@ -532,7 +532,7 @@ internal void EncodeHeaders(HeaderCollection headers, bool allowUnicode) } string[] values = headers.GetValues(headerName)!; - string encodedValue = string.Empty; + string encodedValue; for (int j = 0; j < values.Length; j++) { //encode if we need to diff --git a/src/libraries/System.Net.Mail/tests/Functional/SmtpClientTest.cs b/src/libraries/System.Net.Mail/tests/Functional/SmtpClientTest.cs index bd0fb5298432d..ecdbdede4315d 100644 --- a/src/libraries/System.Net.Mail/tests/Functional/SmtpClientTest.cs +++ b/src/libraries/System.Net.Mail/tests/Functional/SmtpClientTest.cs @@ -341,7 +341,7 @@ public void TestZeroTimeout() [InlineData("howdydoo")] [InlineData("")] [InlineData(null)] - [SkipOnCoreClr("System.Net.Tests are flaky and/or long running: https://github.com/dotnet/runtime/issues/131", RuntimeConfiguration.Checked)] + [SkipOnCoreClr("System.Net.Tests are flaky and/or long running: https://github.com/dotnet/runtime/issues/131", ~RuntimeConfiguration.Release)] [ActiveIssue("https://github.com/dotnet/runtime/issues/131", TestRuntimes.Mono)] // System.Net.Tests are flaky and/or long running public async Task TestMailDeliveryAsync(string body) { @@ -360,7 +360,7 @@ public async Task TestMailDeliveryAsync(string body) [Fact] [PlatformSpecific(TestPlatforms.Windows)] // NTLM support required, see https://github.com/dotnet/runtime/issues/25827 - [SkipOnCoreClr("System.Net.Tests are flaky and/or long running: https://github.com/dotnet/runtime/issues/131", RuntimeConfiguration.Checked)] + [SkipOnCoreClr("System.Net.Tests are flaky and/or long running: https://github.com/dotnet/runtime/issues/131", ~RuntimeConfiguration.Release)] [ActiveIssue("https://github.com/dotnet/runtime/issues/131", TestRuntimes.Mono)] // System.Net.Tests are flaky and/or long running public async Task TestCredentialsCopyInAsyncContext() { diff --git a/src/libraries/System.Net.NetworkInformation/ref/System.Net.NetworkInformation.cs b/src/libraries/System.Net.NetworkInformation/ref/System.Net.NetworkInformation.cs index b8d331ba9918c..66ab317a7d93d 100644 --- a/src/libraries/System.Net.NetworkInformation/ref/System.Net.NetworkInformation.cs +++ b/src/libraries/System.Net.NetworkInformation/ref/System.Net.NetworkInformation.cs @@ -123,9 +123,11 @@ public virtual void CopyTo(System.Net.NetworkInformation.IPAddressInformation[] public abstract partial class IPGlobalProperties { protected IPGlobalProperties() { } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract string DhcpScopeName { get; } public abstract string DomainName { get; } public abstract string HostName { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool IsWinsProxy { get; } public abstract System.Net.NetworkInformation.NetBiosNodeType NodeType { get; } public virtual System.IAsyncResult BeginGetUnicastAddresses(System.AsyncCallback? callback, object? state) { throw null; } @@ -136,16 +138,22 @@ protected IPGlobalProperties() { } public abstract System.Net.IPEndPoint[] GetActiveTcpListeners(); [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.IPEndPoint[] GetActiveUdpListeners(); + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics(); + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics(); [System.Runtime.Versioning.UnsupportedOSPlatform("illumos")] [System.Runtime.Versioning.UnsupportedOSPlatform("solaris")] public static System.Net.NetworkInformation.IPGlobalProperties GetIPGlobalProperties() { throw null; } public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics(); public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics(); + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics(); + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics(); + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics(); + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics(); public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection GetUnicastAddresses() { throw null; } public virtual System.Threading.Tasks.Task GetUnicastAddressesAsync() { throw null; } @@ -153,41 +161,69 @@ protected IPGlobalProperties() { } public abstract partial class IPGlobalStatistics { protected IPGlobalStatistics() { } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract int DefaultTtl { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool ForwardingEnabled { get; } public abstract int NumberOfInterfaces { get; } public abstract int NumberOfIPAddresses { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract int NumberOfRoutes { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long OutputPacketRequests { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long OutputPacketRoutingDiscards { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long OutputPacketsDiscarded { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long OutputPacketsWithNoRoute { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long PacketFragmentFailures { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long PacketReassembliesRequired { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long PacketReassemblyFailures { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long PacketReassemblyTimeout { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long PacketsFragmented { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long PacketsReassembled { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long ReceivedPackets { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsDelivered { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsDiscarded { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsForwarded { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsWithAddressErrors { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsWithHeadersErrors { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsWithUnknownProtocol { get; } } public abstract partial class IPInterfaceProperties { protected IPInterfaceProperties() { } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.IPAddressInformationCollection AnycastAddresses { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.IPAddressCollection DhcpServerAddresses { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.IPAddressCollection DnsAddresses { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract string DnsSuffix { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.GatewayIPAddressInformationCollection GatewayAddresses { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool IsDnsEnabled { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool IsDynamicDnsEnabled { get; } public abstract System.Net.NetworkInformation.MulticastIPAddressInformationCollection MulticastAddresses { get; } public abstract System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastAddresses { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract System.Net.NetworkInformation.IPAddressCollection WinsServersAddresses { get; } public abstract System.Net.NetworkInformation.IPv4InterfaceProperties GetIPv4Properties(); public abstract System.Net.NetworkInformation.IPv6InterfaceProperties GetIPv6Properties(); @@ -212,11 +248,16 @@ public abstract partial class IPv4InterfaceProperties { protected IPv4InterfaceProperties() { } public abstract int Index { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool IsAutomaticPrivateAddressingActive { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool IsAutomaticPrivateAddressingEnabled { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool IsDhcpEnabled { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool IsForwardingEnabled { get; } public abstract int Mtu { get; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public abstract bool UsesWins { get; } } public abstract partial class IPv4InterfaceStatistics @@ -316,7 +357,9 @@ protected NetworkInterface() { } [System.Runtime.Versioning.UnsupportedOSPlatform("solaris")] public static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces() { throw null; } public virtual System.Net.NetworkInformation.IPInterfaceProperties GetIPProperties() { throw null; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public virtual System.Net.NetworkInformation.IPInterfaceStatistics GetIPStatistics() { throw null; } + [System.Runtime.Versioning.UnsupportedOSPlatform("android")] public virtual System.Net.NetworkInformation.IPv4InterfaceStatistics GetIPv4Statistics() { throw null; } [System.Runtime.Versioning.UnsupportedOSPlatform("illumos")] [System.Runtime.Versioning.UnsupportedOSPlatform("solaris")] diff --git a/src/libraries/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj b/src/libraries/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj index dc251f9c75dc4..13a17550284e0 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj +++ b/src/libraries/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj @@ -1,7 +1,7 @@ true - $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Linux;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-tvOS;$(NetCoreAppCurrent)-FreeBSD;$(NetCoreAppCurrent)-illumos;$(NetCoreAppCurrent)-Solaris;$(NetCoreAppCurrent) + $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Linux;$(NetCoreAppCurrent)-Android;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-iOS;$(NetCoreAppCurrent)-tvOS;$(NetCoreAppCurrent)-FreeBSD;$(NetCoreAppCurrent)-illumos;$(NetCoreAppCurrent)-Solaris;$(NetCoreAppCurrent) enable @@ -26,7 +26,7 @@ - + @@ -118,8 +118,8 @@ - - + + @@ -144,6 +144,17 @@ + + + + + + + + + + + diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPGlobalProperties.cs new file mode 100644 index 0000000000000..4cebb2c55efa9 --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPGlobalProperties.cs @@ -0,0 +1,32 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Net.NetworkInformation +{ + internal sealed class AndroidIPGlobalProperties : UnixIPGlobalProperties + { + public override TcpConnectionInformation[] GetActiveTcpConnections() => throw new PlatformNotSupportedException(); + + public override IPEndPoint[] GetActiveTcpListeners() => throw new PlatformNotSupportedException(); + + public override IPEndPoint[] GetActiveUdpListeners() => throw new PlatformNotSupportedException(); + + public override IcmpV4Statistics GetIcmpV4Statistics() => throw new PlatformNotSupportedException(); + + public override IcmpV6Statistics GetIcmpV6Statistics() => throw new PlatformNotSupportedException(); + + public override IPGlobalStatistics GetIPv4GlobalStatistics() + => new AndroidIPGlobalStatistics(ipv4: true); + + public override IPGlobalStatistics GetIPv6GlobalStatistics() + => new AndroidIPGlobalStatistics(ipv4: false); + + public override TcpStatistics GetTcpIPv4Statistics() => throw new PlatformNotSupportedException(); + + public override TcpStatistics GetTcpIPv6Statistics() => throw new PlatformNotSupportedException(); + + public override UdpStatistics GetUdpIPv4Statistics() => throw new PlatformNotSupportedException(); + + public override UdpStatistics GetUdpIPv6Statistics() => throw new PlatformNotSupportedException(); + } +} diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPGlobalStatistics.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPGlobalStatistics.cs new file mode 100644 index 0000000000000..de57e068a1ddb --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPGlobalStatistics.cs @@ -0,0 +1,73 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; +using System.Net.Sockets; + +namespace System.Net.NetworkInformation +{ + internal sealed class AndroidIPGlobalStatistics : IPGlobalStatistics + { + public AndroidIPGlobalStatistics(bool ipv4) + { + AndroidNetworkInterface[] networkInterfaces = NetworkInterfacePal.GetAndroidNetworkInterfaces(); + + foreach (var networkInterface in networkInterfaces) + { + var component = ipv4 ? NetworkInterfaceComponent.IPv4 : NetworkInterfaceComponent.IPv6; + if (networkInterface.Supports(component)) + { + NumberOfInterfaces++; + } + + foreach (UnixUnicastIPAddressInformation addressInformation in networkInterface.UnicastAddress) + { + bool isIPv4 = addressInformation.Address.AddressFamily == AddressFamily.InterNetwork; + if (isIPv4 == ipv4) + { + NumberOfIPAddresses++; + } + } + + if (networkInterface.MulticastAddresess != null) + { + foreach (IPAddress address in networkInterface.MulticastAddresess) + { + bool isIPv4 = address.AddressFamily == AddressFamily.InterNetwork; + if (isIPv4 == ipv4) + { + NumberOfIPAddresses++; + } + } + } + } + } + + public override int NumberOfInterfaces { get; } + public override int NumberOfIPAddresses { get; } + + public override int DefaultTtl => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override bool ForwardingEnabled => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override int NumberOfRoutes => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long OutputPacketRequests => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long OutputPacketRoutingDiscards => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long OutputPacketsDiscarded => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long OutputPacketsWithNoRoute => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long PacketFragmentFailures => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long PacketReassembliesRequired => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long PacketReassemblyFailures => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long PacketReassemblyTimeout => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long PacketsFragmented => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long PacketsReassembled => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long ReceivedPackets => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long ReceivedPacketsDelivered => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long ReceivedPacketsDiscarded => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long ReceivedPacketsForwarded => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long ReceivedPacketsWithAddressErrors => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long ReceivedPacketsWithHeadersErrors => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override long ReceivedPacketsWithUnknownProtocol => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + } +} diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPInterfaceProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPInterfaceProperties.cs new file mode 100644 index 0000000000000..cee58c47d8447 --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPInterfaceProperties.cs @@ -0,0 +1,30 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Generic; +using System.IO; + +namespace System.Net.NetworkInformation +{ + internal sealed class AndroidIPInterfaceProperties : UnixIPInterfaceProperties + { + private readonly AndroidIPv4InterfaceProperties _ipv4Properties; + private readonly AndroidIPv6InterfaceProperties _ipv6Properties; + + public AndroidIPInterfaceProperties(AndroidNetworkInterface ani) + : base(ani, globalConfig: true) + { + _ipv4Properties = new AndroidIPv4InterfaceProperties(ani); + _ipv6Properties = new AndroidIPv6InterfaceProperties(ani); + } + + public override IPv4InterfaceProperties GetIPv4Properties() => _ipv4Properties; + public override IPv6InterfaceProperties GetIPv6Properties() => _ipv6Properties; + + public override bool IsDynamicDnsEnabled => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override IPAddressInformationCollection AnycastAddresses => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override GatewayIPAddressInformationCollection GatewayAddresses => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override IPAddressCollection DhcpServerAddresses => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override IPAddressCollection WinsServersAddresses => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + } +} diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPv4InterfaceProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPv4InterfaceProperties.cs new file mode 100644 index 0000000000000..cc12cf7f35745 --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPv4InterfaceProperties.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.IO; + +namespace System.Net.NetworkInformation +{ + internal sealed class AndroidIPv4InterfaceProperties : UnixIPv4InterfaceProperties + { + public AndroidIPv4InterfaceProperties(AndroidNetworkInterface androidNetworkInterface) + : base(androidNetworkInterface) + { + Mtu = androidNetworkInterface._mtu; + } + + public override int Mtu { get; } + + public override bool IsAutomaticPrivateAddressingActive => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override bool IsAutomaticPrivateAddressingEnabled => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override bool IsDhcpEnabled => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override bool IsForwardingEnabled => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override bool UsesWins => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + } +} diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPv6InterfaceProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPv6InterfaceProperties.cs new file mode 100644 index 0000000000000..9a5f872231efd --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidIPv6InterfaceProperties.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.IO; + +namespace System.Net.NetworkInformation +{ + internal sealed class AndroidIPv6InterfaceProperties : UnixIPv6InterfaceProperties + { + private readonly AndroidNetworkInterface _androidNetworkInterface; + + public AndroidIPv6InterfaceProperties(AndroidNetworkInterface androidNetworkInterface) + : base(androidNetworkInterface) + { + _androidNetworkInterface = androidNetworkInterface; + } + + public override int Mtu => _androidNetworkInterface._mtu; + + public override long GetScopeId(ScopeLevel scopeLevel) + { + if (scopeLevel == ScopeLevel.None || scopeLevel == ScopeLevel.Interface || + scopeLevel == ScopeLevel.Link || scopeLevel == ScopeLevel.Subnet) + { + return _androidNetworkInterface.Index; + } + + return 0; + } + } +} diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidNetworkInterface.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidNetworkInterface.cs new file mode 100644 index 0000000000000..dcf66895aea7b --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/AndroidNetworkInterface.cs @@ -0,0 +1,54 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Net; + +namespace System.Net.NetworkInformation +{ + /// + /// Implements a NetworkInterface on Android. + /// + internal sealed class AndroidNetworkInterface : UnixNetworkInterface + { + internal readonly int _mtu; + private readonly AndroidIPInterfaceProperties _ipProperties; + + internal unsafe AndroidNetworkInterface(string name, Interop.Sys.NetworkInterfaceInfo *networkInterfaceInfo) + : base(name) + { + _index = networkInterfaceInfo->InterfaceIndex; + if (networkInterfaceInfo->NumAddressBytes > 0) + { + _physicalAddress = new PhysicalAddress(new ReadOnlySpan(networkInterfaceInfo->AddressBytes, networkInterfaceInfo->NumAddressBytes).ToArray()); + } + + _mtu = networkInterfaceInfo->Mtu; + _ipProperties = new AndroidIPInterfaceProperties(this); + + OperationalStatus = (OperationalStatus)networkInterfaceInfo->OperationalState; + Speed = networkInterfaceInfo->Speed; + SupportsMulticast = networkInterfaceInfo->SupportsMulticast != 0; + NetworkInterfaceType = (NetworkInterfaceType)networkInterfaceInfo->HardwareType; + } + + internal unsafe void AddAddress(Interop.Sys.IpAddressInfo *addressInfo) + { + var address = new IPAddress(new ReadOnlySpan(addressInfo->AddressBytes, addressInfo->NumAddressBytes)); + if (address.IsIPv6LinkLocal) + { + address.ScopeId = addressInfo->InterfaceIndex; + } + + AddAddress(address, addressInfo->PrefixLength); + } + + public override bool SupportsMulticast { get; } + public override IPInterfaceProperties GetIPProperties() => _ipProperties; + public override IPInterfaceStatistics GetIPStatistics() => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override IPv4InterfaceStatistics GetIPv4Statistics() => throw new PlatformNotSupportedException(SR.net_InformationUnavailableOnPlatform); + public override OperationalStatus OperationalStatus { get; } + public override NetworkInterfaceType NetworkInterfaceType { get; } + public override long Speed { get; } + public override bool IsReceiveOnly => false; + } +} diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalProperties.cs index d835ce2ecd65b..1371a47d3ed94 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalProperties.cs @@ -40,6 +40,7 @@ public static IPGlobalProperties GetIPGlobalProperties() /// /// Gets the Dynamic Host Configuration Protocol (DHCP) scope name. /// + [UnsupportedOSPlatform("android")] public abstract string DhcpScopeName { get; } /// @@ -55,6 +56,7 @@ public static IPGlobalProperties GetIPGlobalProperties() /// /// Gets a bool value that specifies whether the local computer is acting as a Windows Internet Name Service (WINS) proxy. /// + [UnsupportedOSPlatform("android")] public abstract bool IsWinsProxy { get; } /// @@ -72,25 +74,31 @@ public virtual UnicastIPAddressInformationCollection EndGetUnicastAddresses(IAsy throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); } + [UnsupportedOSPlatform("android")] public abstract TcpStatistics GetTcpIPv4Statistics(); + [UnsupportedOSPlatform("android")] public abstract TcpStatistics GetTcpIPv6Statistics(); /// /// Provides User Datagram Protocol (UDP) statistical data for the local computer. /// + [UnsupportedOSPlatform("android")] public abstract UdpStatistics GetUdpIPv4Statistics(); + [UnsupportedOSPlatform("android")] public abstract UdpStatistics GetUdpIPv6Statistics(); /// /// Provides Internet Control Message Protocol (ICMP) version 4 statistical data for the local computer. /// + [UnsupportedOSPlatform("android")] public abstract IcmpV4Statistics GetIcmpV4Statistics(); /// /// Provides Internet Control Message Protocol (ICMP) version 6 statistical data for the local computer. /// + [UnsupportedOSPlatform("android")] public abstract IcmpV6Statistics GetIcmpV6Statistics(); /// diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalPropertiesPal.Android.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalPropertiesPal.Android.cs new file mode 100644 index 0000000000000..33e09ece17c69 --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalPropertiesPal.Android.cs @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace System.Net.NetworkInformation +{ + internal static class IPGlobalPropertiesPal + { + public static IPGlobalProperties GetIPGlobalProperties() + { + return new AndroidIPGlobalProperties(); + } + } +} diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalStatistics.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalStatistics.cs index a8103f867e83d..04b9f14f1eab2 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalStatistics.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPGlobalStatistics.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Runtime.Versioning; + namespace System.Net.NetworkInformation { /// @@ -11,11 +13,13 @@ public abstract class IPGlobalStatistics /// /// Gets the default time-to-live (TTL) value for Internet Protocol (IP) packets. /// + [UnsupportedOSPlatform("android")] public abstract int DefaultTtl { get; } /// /// Gets a bool value that specifies whether Internet Protocol (IP) packet forwarding is enabled. /// + [UnsupportedOSPlatform("android")] public abstract bool ForwardingEnabled { get; } /// @@ -31,91 +35,109 @@ public abstract class IPGlobalStatistics /// /// Gets the number of outbound Internet Protocol (IP) packets. /// + [UnsupportedOSPlatform("android")] public abstract long OutputPacketRequests { get; } /// /// Gets the number of routes in the routing table that have been discarded. /// + [UnsupportedOSPlatform("android")] public abstract long OutputPacketRoutingDiscards { get; } /// /// Gets the number of transmitted Internet Protocol (IP) packets that have been discarded. /// + [UnsupportedOSPlatform("android")] public abstract long OutputPacketsDiscarded { get; } /// /// Gets the number of Internet Protocol (IP) packets for which the local computer could not determine a route to the destination address. /// + [UnsupportedOSPlatform("android")] public abstract long OutputPacketsWithNoRoute { get; } /// /// Gets the number of Internet Protocol (IP) packets that could not be fragmented. /// + [UnsupportedOSPlatform("android")] public abstract long PacketFragmentFailures { get; } /// /// Gets the number of Internet Protocol (IP) packets that required reassembly. /// + [UnsupportedOSPlatform("android")] public abstract long PacketReassembliesRequired { get; } /// /// Gets the number of Internet Protocol (IP) packets that were not successfully reassembled. /// + [UnsupportedOSPlatform("android")] public abstract long PacketReassemblyFailures { get; } /// /// Gets the maximum amount of time within which all fragments of an Internet Protocol (IP) packet must arrive. /// + [UnsupportedOSPlatform("android")] public abstract long PacketReassemblyTimeout { get; } /// /// Gets the number of Internet Protocol (IP) packets fragmented. /// + [UnsupportedOSPlatform("android")] public abstract long PacketsFragmented { get; } /// /// Gets the number of Internet Protocol (IP) packets reassembled. /// + [UnsupportedOSPlatform("android")] public abstract long PacketsReassembled { get; } /// /// Gets the number of Internet Protocol (IP) packets received. /// + [UnsupportedOSPlatform("android")] public abstract long ReceivedPackets { get; } /// /// Gets the number of Internet Protocol(IP) packets received and delivered. /// + [UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsDelivered { get; } /// /// Gets the number of Internet Protocol (IP) packets that have been received and discarded. /// + [UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsDiscarded { get; } /// /// Gets the number of Internet Protocol (IP) packets forwarded. /// + [UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsForwarded { get; } /// /// Gets the number of Internet Protocol (IP) packets with address errors that were received. /// + [UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsWithAddressErrors { get; } /// /// Gets the number of Internet Protocol (IP) packets with header errors that were received. /// + [UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsWithHeadersErrors { get; } /// /// Gets the number of Internet Protocol (IP) packets received on the local machine with an unknown protocol in the header. /// + [UnsupportedOSPlatform("android")] public abstract long ReceivedPacketsWithUnknownProtocol { get; } /// /// Gets the number of routes in the Internet Protocol (IP) routing table. /// + [UnsupportedOSPlatform("android")] public abstract int NumberOfRoutes { get; } } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPInterfaceProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPInterfaceProperties.cs index e659598f5e4f4..863737ce18f6d 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPInterfaceProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPInterfaceProperties.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Runtime.Versioning; + namespace System.Net.NetworkInformation { /// @@ -12,16 +14,19 @@ public abstract class IPInterfaceProperties /// /// Gets a bool value that indicates whether this interface is configured to send name resolution queries to a Domain Name System (DNS) server. /// + [UnsupportedOSPlatform("android")] public abstract bool IsDnsEnabled { get; } /// /// Gets the Domain Name System (DNS) suffix associated with this interface. /// + [UnsupportedOSPlatform("android")] public abstract string DnsSuffix { get; } /// /// Gets a bool value that indicates whether this interface is configured to automatically register its IP address information with the Domain Name System (DNS). /// + [UnsupportedOSPlatform("android")] public abstract bool IsDynamicDnsEnabled { get; } /// @@ -37,26 +42,31 @@ public abstract class IPInterfaceProperties /// /// The address identifies multiple computers. Packets sent to an anycast address are sent to one of the computers identified by the address. /// + [UnsupportedOSPlatform("android")] public abstract IPAddressInformationCollection AnycastAddresses { get; } /// /// The address is that of a Domain Name Service (DNS) server for the local computer. /// + [UnsupportedOSPlatform("android")] public abstract IPAddressCollection DnsAddresses { get; } /// /// Gets the network gateway addresses. /// + [UnsupportedOSPlatform("android")] public abstract GatewayIPAddressInformationCollection GatewayAddresses { get; } /// /// Gets the addresses for Dynamic Host Configuration Protocol (DHCP) servers. /// + [UnsupportedOSPlatform("android")] public abstract IPAddressCollection DhcpServerAddresses { get; } /// /// Gets the list of Wins Servers registered with this interface /// + [UnsupportedOSPlatform("android")] public abstract IPAddressCollection WinsServersAddresses { get; } /// diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPv4InterfaceProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPv4InterfaceProperties.cs index 0f104e3fce8fc..9f9d0b1e3766d 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPv4InterfaceProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/IPv4InterfaceProperties.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Runtime.Versioning; + namespace System.Net.NetworkInformation { /// @@ -11,21 +13,25 @@ public abstract class IPv4InterfaceProperties /// /// Gets a bool value that indicates whether an interface uses Windows Internet Name Service (WINS). /// + [UnsupportedOSPlatform("android")] public abstract bool UsesWins { get; } /// /// Gets a bool value that indicates whether the interface is configured to use a dynamic host configuration protocol (DHCP) server to obtain an IP address. /// + [UnsupportedOSPlatform("android")] public abstract bool IsDhcpEnabled { get; } /// /// Gets a bool value that indicates whether this interface has an automatic private IP addressing (APIPA) address. /// + [UnsupportedOSPlatform("android")] public abstract bool IsAutomaticPrivateAddressingActive { get; } /// /// Gets a bool value that indicates whether this interface has automatic private IP addressing (APIPA) enabled. /// + [UnsupportedOSPlatform("android")] public abstract bool IsAutomaticPrivateAddressingEnabled { get; } /// @@ -36,6 +42,7 @@ public abstract class IPv4InterfaceProperties /// /// Gets a bool value that indicates whether this interface can route packets. /// + [UnsupportedOSPlatform("android")] public abstract bool IsForwardingEnabled { get; } /// diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.UnknownUnix.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.UnknownUnix.cs index 5fe320ac241f4..84482c14f7b56 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.UnknownUnix.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.UnknownUnix.cs @@ -9,15 +9,6 @@ namespace System.Net.NetworkInformation { public partial class NetworkChange { - static NetworkChange() - { - // fake usage of static readonly fields to avoid getting CA1823 warning when we are compiling this partial. - var addressChangedSubscribers = new Dictionary(s_addressChangedSubscribers); - var availabilityChangedSubscribers = new Dictionary(s_availabilityChangedSubscribers); - NetworkAvailabilityEventArgs args = addressChangedSubscribers.Count > 0 ? s_availableEventArgs : s_notAvailableEventArgs; - ContextCallback callbackContext = s_runAddressChangedHandler != null ? s_runHandlerAvailable : s_runHandlerNotAvailable; - } - [UnsupportedOSPlatform("illumos")] [UnsupportedOSPlatform("solaris")] public static event NetworkAddressChangedEventHandler? NetworkAddressChanged @@ -33,5 +24,8 @@ public static event NetworkAvailabilityChangedEventHandler? NetworkAvailabilityC add { throw new PlatformNotSupportedException(); } remove { throw new PlatformNotSupportedException(); } } + + [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] + public static void RegisterNetworkChange(NetworkChange nc) { } } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkInterface.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkInterface.cs index 94cb8fb0b9d81..24f02186c3dc3 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkInterface.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkInterface.cs @@ -70,6 +70,7 @@ public virtual IPInterfaceProperties GetIPProperties() /// Provides Internet Protocol (IP) statistical data for this network interface. /// /// The interface's IP statistics. + [UnsupportedOSPlatform("android")] public virtual IPInterfaceStatistics GetIPStatistics() { throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); @@ -81,6 +82,7 @@ public virtual IPInterfaceStatistics GetIPStatistics() /// Do not use this method, use GetIPStatistics instead. /// /// The interface's IP statistics. + [UnsupportedOSPlatform("android")] public virtual IPv4InterfaceStatistics GetIPv4Statistics() { throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException); diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkInterfacePal.Android.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkInterfacePal.Android.cs new file mode 100644 index 0000000000000..3b68b90e5a5fc --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkInterfacePal.Android.cs @@ -0,0 +1,110 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Runtime.InteropServices; + +namespace System.Net.NetworkInformation +{ + internal static class NetworkInterfacePal + { + /// Returns objects that describe the network interfaces on the local computer. + public static NetworkInterface[] GetAllNetworkInterfaces() => GetAndroidNetworkInterfaces(); + public static bool GetIsNetworkAvailable() => TransformNetworkInterfacess(IsSomeNetworkUp); + public static int IPv6LoopbackInterfaceIndex => LoopbackInterfaceIndex; + public static int LoopbackInterfaceIndex => TransformNetworkInterfacess(FindLoopbackInterfaceIndex); + + internal static unsafe AndroidNetworkInterface[] GetAndroidNetworkInterfaces() + => TransformNetworkInterfacess(ToAndroidNetworkInterfaceArray); + + private static unsafe T TransformNetworkInterfacess(Func transform) + { + int interfaceCount = 0; + int addressCount = 0; + Interop.Sys.NetworkInterfaceInfo *networkInterfaceInfo = null; + Interop.Sys.IpAddressInfo *addressInfo = null; + + if (Interop.Sys.GetNetworkInterfaces(&interfaceCount, &networkInterfaceInfo, &addressCount, &addressInfo) != 0) + { + string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage(); + throw new NetworkInformationException(message); + } + + // the native implementation of Interop.Sys.GetNetworkInterfaces allocates one block of memory + // for both networkInterfaceInfo and addressInfo so we only need to call free once pointing at + // the start of the network itnerfaces list + var globalMemory = (IntPtr)networkInterfaceInfo; + + try + { + return transform(interfaceCount, (IntPtr)networkInterfaceInfo, addressCount, (IntPtr)addressInfo); + } + finally + { + Marshal.FreeHGlobal(globalMemory); + } + } + + private static unsafe AndroidNetworkInterface[] ToAndroidNetworkInterfaceArray(int interfaceCount, IntPtr networkInterfacesPtr, int addressCount, IntPtr addressPtr) + { + var networkInterfaces = new AndroidNetworkInterface[interfaceCount]; + + var networkInterfaceInfo = (Interop.Sys.NetworkInterfaceInfo*)networkInterfacesPtr; + for (int i = 0; i < interfaceCount; i++, networkInterfaceInfo++) + { + var name = Marshal.PtrToStringAnsi((IntPtr)networkInterfaceInfo->Name); + networkInterfaces[i] = new AndroidNetworkInterface(name!, networkInterfaceInfo); + } + + var addressInfo = (Interop.Sys.IpAddressInfo*)addressPtr; + for (int i = 0; i < addressCount; i++, addressInfo++) + { + // there is usually just a handful of few network interfaces on Android devices + // and this linear search does not have any impact on performance + foreach (var networkInterface in networkInterfaces) + { + if (networkInterface.Index == addressInfo->InterfaceIndex) + { + networkInterface.AddAddress(addressInfo); + break; + } + } + } + + return networkInterfaces; + } + + private static unsafe int FindLoopbackInterfaceIndex(int interfaceCount, IntPtr networkInterfacesPtr, int addressCount, IntPtr addressPtr) + { + var networkInterfaceInfo = (Interop.Sys.NetworkInterfaceInfo*)networkInterfacesPtr; + for (int i = 0; i < interfaceCount; i++, networkInterfaceInfo++) + { + if (networkInterfaceInfo->HardwareType == (int)NetworkInterfaceType.Loopback) + { + return networkInterfaceInfo->InterfaceIndex; + } + } + + throw new NetworkInformationException(SR.net_NoLoopback); + } + + private static unsafe bool IsSomeNetworkUp(int interfaceCount, IntPtr networkInterfacesPtr, int addressCount, IntPtr addressPtr) + { + var networkInterfaceInfo = (Interop.Sys.NetworkInterfaceInfo*)networkInterfacesPtr; + for (int i = 0; i < interfaceCount; i++, networkInterfaceInfo++) + { + if (networkInterfaceInfo->HardwareType == (int)NetworkInterfaceType.Loopback + || networkInterfaceInfo->HardwareType == (int)NetworkInterfaceType.Tunnel) + { + continue; + } + + if (networkInterfaceInfo->OperationalState == (int)OperationalStatus.Up) + { + return true; + } + } + + return false; + } + } +} diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs index 7a65e6e7a16c8..ef5fb68547fc7 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs @@ -105,7 +105,7 @@ public override IPEndPoint[] GetActiveTcpListeners() private unsafe List GetAllTcpConnections() { uint size = 0; - uint result = 0; + uint result; List tcpConnections = new List(); // Check if it supports IPv4 for IPv6 only modes. @@ -214,7 +214,7 @@ private unsafe List GetAllTcpConnections() public unsafe override IPEndPoint[] GetActiveUdpListeners() { uint size = 0; - uint result = 0; + uint result; List udpListeners = new List(); // Check if it support IPv4 for IPv6 only modes. diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs index cca949a317a6f..eafa42ff3fec1 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixIPGlobalProperties.cs @@ -13,6 +13,7 @@ namespace System.Net.NetworkInformation internal abstract class UnixIPGlobalProperties : IPGlobalProperties { [UnsupportedOSPlatform("linux")] + [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("osx")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] @@ -26,6 +27,7 @@ internal abstract class UnixIPGlobalProperties : IPGlobalProperties public override string HostName { get { return HostInformation.HostName; } } [UnsupportedOSPlatform("linux")] + [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("osx")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs index d248c72b6930c..00c5b3a9a3028 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/UnixNetworkInterface.cs @@ -60,7 +60,7 @@ public override bool Supports(NetworkInterfaceComponent networkInterfaceComponen public List UnicastAddress { get { return _unicastAddresses; } } /// - /// Returns a list of all Unicast addresses of the interface's IP Addresses. + /// Returns a list of all Multicast addresses of the interface's IP Addresses. /// public List? MulticastAddresess { get { return _multicastAddresses; } } diff --git a/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/IPGlobalPropertiesTest.cs b/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/IPGlobalPropertiesTest.cs index f9438935ffabd..70804e19499e2 100644 --- a/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/IPGlobalPropertiesTest.cs +++ b/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/IPGlobalPropertiesTest.cs @@ -26,6 +26,7 @@ public IPGlobalPropertiesTest(ITestOutputHelper output) } [Fact] + [SkipOnPlatform(TestPlatforms.Android, "Expected behavior is different on Android")] public void IPGlobalProperties_AccessAllMethods_NoErrors() { IPGlobalProperties gp = IPGlobalProperties.GetIPGlobalProperties(); @@ -49,8 +50,71 @@ public void IPGlobalProperties_AccessAllMethods_NoErrors() Assert.NotNull(gp.GetUdpIPv6Statistics()); } + [Fact] + [PlatformSpecific(TestPlatforms.Android)] + public void IPGlobalProperties_AccessAllMethods_NoErrors_Android() + { + IPGlobalProperties gp = IPGlobalProperties.GetIPGlobalProperties(); + + Assert.NotNull(gp.GetIPv4GlobalStatistics()); + Assert.NotNull(gp.GetIPv6GlobalStatistics()); + + Assert.Throws(() => gp.GetActiveTcpConnections()); + Assert.Throws(() => gp.GetActiveTcpListeners()); + Assert.Throws(() => gp.GetActiveUdpListeners()); + Assert.Throws(() => gp.GetIcmpV4Statistics()); + Assert.Throws(() => gp.GetIcmpV6Statistics()); + Assert.Throws(() => gp.GetTcpIPv4Statistics()); + Assert.Throws(() => gp.GetTcpIPv6Statistics()); + Assert.Throws(() => gp.GetUdpIPv4Statistics()); + Assert.Throws(() => gp.GetUdpIPv6Statistics()); + } + + [Theory] + [InlineData(4)] + [InlineData(6)] + [PlatformSpecific(TestPlatforms.Android)] + public void IPGlobalProperties_IPv4_IPv6_NoErrors_Android(int ipVersion) + { + IPGlobalProperties gp = IPGlobalProperties.GetIPGlobalProperties(); + IPGlobalStatistics statistics = ipVersion switch { + 4 => gp.GetIPv4GlobalStatistics(), + 6 => gp.GetIPv6GlobalStatistics(), + _ => throw new ArgumentOutOfRangeException() + }; + + _log.WriteLine($"- IPv{ipVersion} statistics: -"); + _log.WriteLine($"Number of interfaces: {statistics.NumberOfInterfaces}"); + _log.WriteLine($"Number of IP addresses: {statistics.NumberOfIPAddresses}"); + + Assert.InRange(statistics.NumberOfInterfaces, 1, int.MaxValue); + Assert.InRange(statistics.NumberOfIPAddresses, 1, int.MaxValue); + + Assert.Throws(() => statistics.DefaultTtl); + Assert.Throws(() => statistics.ForwardingEnabled); + Assert.Throws(() => statistics.OutputPacketRequests); + Assert.Throws(() => statistics.OutputPacketRoutingDiscards); + Assert.Throws(() => statistics.OutputPacketsDiscarded); + Assert.Throws(() => statistics.OutputPacketsWithNoRoute); + Assert.Throws(() => statistics.PacketFragmentFailures); + Assert.Throws(() => statistics.PacketReassembliesRequired); + Assert.Throws(() => statistics.PacketReassemblyFailures); + Assert.Throws(() => statistics.PacketReassemblyTimeout); + Assert.Throws(() => statistics.PacketsFragmented); + Assert.Throws(() => statistics.PacketsReassembled); + Assert.Throws(() => statistics.ReceivedPackets); + Assert.Throws(() => statistics.ReceivedPacketsDelivered); + Assert.Throws(() => statistics.ReceivedPacketsDiscarded); + Assert.Throws(() => statistics.ReceivedPacketsForwarded); + Assert.Throws(() => statistics.ReceivedPacketsWithAddressErrors); + Assert.Throws(() => statistics.ReceivedPacketsWithHeadersErrors); + Assert.Throws(() => statistics.ReceivedPacketsWithUnknownProtocol); + Assert.Throws(() => statistics.NumberOfRoutes); + } + [Theory] [MemberData(nameof(Loopbacks))] + [SkipOnPlatform(TestPlatforms.Android, "Unsupported on Android")] public void IPGlobalProperties_TcpListeners_Succeed(IPAddress address) { using (var server = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) @@ -76,7 +140,7 @@ public void IPGlobalProperties_TcpListeners_Succeed(IPAddress address) [Theory] [ActiveIssue("https://github.com/dotnet/runtime/issues/34690", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)] - [PlatformSpecific(~(TestPlatforms.iOS | TestPlatforms.tvOS))] + [PlatformSpecific(~(TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.Android))] [MemberData(nameof(Loopbacks))] public async Task IPGlobalProperties_TcpActiveConnections_Succeed(IPAddress address) { @@ -107,6 +171,7 @@ public async Task IPGlobalProperties_TcpActiveConnections_Succeed(IPAddress addr } [Fact] + [SkipOnPlatform(TestPlatforms.Android, "Unsupported on Android")] public void IPGlobalProperties_TcpActiveConnections_NotListening() { TcpConnectionInformation[] tcpCconnections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(); @@ -117,7 +182,6 @@ public void IPGlobalProperties_TcpActiveConnections_NotListening() } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50567", TestPlatforms.Android)] public async Task GetUnicastAddresses_NotEmpty() { IPGlobalProperties props = IPGlobalProperties.GetIPGlobalProperties(); diff --git a/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/IPInterfacePropertiesTest_Android.cs b/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/IPInterfacePropertiesTest_Android.cs new file mode 100644 index 0000000000000..61e57c854aa47 --- /dev/null +++ b/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/IPInterfacePropertiesTest_Android.cs @@ -0,0 +1,221 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Linq; +using System.Net.Http.Functional.Tests; +using System.Net.Sockets; +using System.Net.Test.Common; +using System.Threading.Tasks; + +using Xunit; +using Xunit.Abstractions; + +namespace System.Net.NetworkInformation.Tests +{ + [PlatformSpecific(TestPlatforms.Android)] + public class IPInterfacePropertiesTest_Android + { + private readonly ITestOutputHelper _log; + + public IPInterfacePropertiesTest_Android(ITestOutputHelper output) + { + _log = output; + } + + [Fact] + public async Task IPInfoTest_AccessAllProperties_NoErrors() + { + await Task.Run(() => + { + foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) + { + _log.WriteLine("Nic: " + nic.Name); + _log.WriteLine("- Speed:" + nic.Speed); + Assert.Equal(-1, nic.Speed); + _log.WriteLine("- Supports IPv4: " + nic.Supports(NetworkInterfaceComponent.IPv4)); + _log.WriteLine("- Supports IPv6: " + nic.Supports(NetworkInterfaceComponent.IPv6)); + Assert.False(nic.IsReceiveOnly); + + IPInterfaceProperties ipProperties = nic.GetIPProperties(); + + Assert.NotNull(ipProperties); + + Assert.Throws(() => ipProperties.AnycastAddresses); + Assert.Throws(() => ipProperties.DhcpServerAddresses); + Assert.Throws(() => ipProperties.DnsAddresses); + Assert.Throws(() => ipProperties.DnsSuffix); + Assert.Throws(() => ipProperties.GatewayAddresses); + Assert.Throws(() => ipProperties.IsDnsEnabled); + Assert.Throws(() => ipProperties.IsDynamicDnsEnabled); + + Assert.NotNull(ipProperties.MulticastAddresses); + _log.WriteLine("- Multicast Addresses: " + ipProperties.MulticastAddresses.Count); + foreach (IPAddressInformation multi in ipProperties.MulticastAddresses) + { + _log.WriteLine("-- " + multi.Address.ToString()); + Assert.Throws(() => multi.IsDnsEligible); + Assert.Throws(() => multi.IsTransient); + } + + Assert.NotNull(ipProperties.UnicastAddresses); + _log.WriteLine("- Unicast Addresses: " + ipProperties.UnicastAddresses.Count); + foreach (UnicastIPAddressInformation uni in ipProperties.UnicastAddresses) + { + _log.WriteLine("-- " + uni.Address.ToString()); + Assert.Throws(() => uni.AddressPreferredLifetime); + Assert.Throws(() => uni.AddressValidLifetime); + Assert.Throws(() => uni.DhcpLeaseLifetime); + Assert.Throws(() => uni.DuplicateAddressDetectionState); + + Assert.NotNull(uni.IPv4Mask); + _log.WriteLine("--- IPv4 Mask: " + uni.IPv4Mask); + Assert.Throws(() => uni.IsDnsEligible); + Assert.Throws(() => uni.IsTransient); + Assert.Throws(() => uni.PrefixOrigin); + Assert.Throws(() => uni.SuffixOrigin); + + // Prefix Length + _log.WriteLine("--- PrefixLength: " + uni.PrefixLength); + Assert.True(uni.PrefixLength > 0); + Assert.True((uni.Address.AddressFamily == AddressFamily.InterNetwork ? 33 : 129) > uni.PrefixLength); + } + + Assert.Throws(() => ipProperties.WinsServersAddresses); + } + }).WaitAsync(TestHelper.PassingTestTimeout); + } + + [Fact] + public async Task IPInfoTest_AccessAllIPv4Properties_NoErrors() + { + await Task.Run(() => + { + foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) + { + _log.WriteLine("Nic: " + nic.Name); + + IPInterfaceProperties ipProperties = nic.GetIPProperties(); + + _log.WriteLine("IPv4 Properties:"); + + IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties(); + + _log.WriteLine("Index: " + ipv4Properties.Index); + Assert.Throws(() => ipv4Properties.IsAutomaticPrivateAddressingActive); + Assert.Throws(() => ipv4Properties.IsAutomaticPrivateAddressingEnabled); + Assert.Throws(() => ipv4Properties.IsDhcpEnabled); + Assert.Throws(() => ipv4Properties.IsForwardingEnabled); + _log.WriteLine("Mtu: " + ipv4Properties.Mtu); + Assert.Throws(() => ipv4Properties.UsesWins); + } + }).WaitAsync(TestHelper.PassingTestTimeout); + } + + [Fact] + public async Task IPInfoTest_AccessAllIPv6Properties_NoErrors() + { + await Task.Run(() => + { + foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) + { + _log.WriteLine("Nic: " + nic.Name); + + IPInterfaceProperties ipProperties = nic.GetIPProperties(); + + _log.WriteLine("IPv6 Properties:"); + + IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); + + if (ipv6Properties == null) + { + _log.WriteLine("IPv6Properties is null"); + continue; + } + + _log.WriteLine("Index: " + ipv6Properties.Index); + _log.WriteLine("Mtu: " + ipv6Properties.Mtu); + _log.WriteLine("Scope: " + ipv6Properties.GetScopeId(ScopeLevel.Link)); + } + }).WaitAsync(TestHelper.PassingTestTimeout); + } + + [Fact] + [Trait("IPv6", "true")] + public async Task IPv6ScopeId_AccessAllValues_Success() + { + await Task.Run(() => + { + Assert.True(Capability.IPv6Support()); + + foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) + { + _log.WriteLine("Nic: " + nic.Name); + + if (!nic.Supports(NetworkInterfaceComponent.IPv6)) + { + continue; + } + + IPInterfaceProperties ipProperties = nic.GetIPProperties(); + + IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); + + Array values = Enum.GetValues(typeof(ScopeLevel)); + foreach (ScopeLevel level in values) + { + _log.WriteLine("-- Level: " + level + "; " + ipv6Properties.GetScopeId(level)); + } + } + }).WaitAsync(TestHelper.PassingTestTimeout); + } + + [Fact] + [Trait("IPv4", "true")] + public async Task IPInfoTest_IPv4Loopback_ProperAddress() + { + await Task.Run(() => + { + Assert.True(Capability.IPv4Support()); + + _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); + + NetworkInterface loopback = NetworkInterface.GetAllNetworkInterfaces().First(ni => ni.Name == "lo"); + Assert.NotNull(loopback); + + foreach (UnicastIPAddressInformation unicast in loopback.GetIPProperties().UnicastAddresses) + { + if (unicast.Address.Equals(IPAddress.Loopback)) + { + Assert.Equal(IPAddress.Parse("255.0.0.0"), unicast.IPv4Mask); + Assert.Equal(8, unicast.PrefixLength); + break; + } + } + }).WaitAsync(TestHelper.PassingTestTimeout); + } + + [Fact] + [Trait("IPv6", "true")] + public async Task IPInfoTest_IPv6Loopback_ProperAddress() + { + await Task.Run(() => + { + Assert.True(Capability.IPv6Support()); + + _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); + + NetworkInterface loopback = NetworkInterface.GetAllNetworkInterfaces().First(ni => ni.Name == "lo"); + Assert.NotNull(loopback); + + foreach (UnicastIPAddressInformation unicast in loopback.GetIPProperties().UnicastAddresses) + { + if (unicast.Address.Equals(IPAddress.IPv6Loopback)) + { + Assert.Equal(128, unicast.PrefixLength); + break; + } + } + }).WaitAsync(TestHelper.PassingTestTimeout); + } + } +} diff --git a/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceBasicTest.cs b/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceBasicTest.cs index 561cb687f3e75..c022f74b2c234 100644 --- a/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceBasicTest.cs +++ b/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceBasicTest.cs @@ -20,7 +20,6 @@ public NetworkInterfaceBasicTest(ITestOutputHelper output) } [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50567", TestPlatforms.Android)] public void BasicTest_GetNetworkInterfaces_AtLeastOne() { Assert.NotEqual(0, NetworkInterface.GetAllNetworkInterfaces().Length); @@ -57,7 +56,7 @@ public void BasicTest_AccessInstanceProperties_NoExceptions() } [Fact] - [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux + [PlatformSpecific(TestPlatforms.Linux|TestPlatforms.Android)] // Some APIs are not supported on Linux and Android public void BasicTest_AccessInstanceProperties_NoExceptions_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) @@ -132,7 +131,6 @@ public void BasicTest_AccessInstanceProperties_NoExceptions_Bsd() [Fact] [Trait("IPv4", "true")] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50567", TestPlatforms.Android)] public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv4Support()); @@ -156,7 +154,6 @@ public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() [Fact] [Trait("IPv4", "true")] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50567", TestPlatforms.Android)] public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() { Assert.True(Capability.IPv4Support()); @@ -166,7 +163,6 @@ public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() [Fact] [Trait("IPv6", "true")] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50567", TestPlatforms.Android)] public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv6Support()); @@ -191,7 +187,6 @@ public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() [Fact] [Trait("IPv6", "true")] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50567", TestPlatforms.Android)] public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported() { Assert.True(Capability.IPv6Support()); @@ -272,7 +267,6 @@ public void BasicTest_GetIPInterfaceStatistics_Success_Bsd() [Fact] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50567", TestPlatforms.Android)] public void BasicTest_GetIsNetworkAvailable_Success() { Assert.True(NetworkInterface.GetIsNetworkAvailable()); @@ -284,7 +278,6 @@ public void BasicTest_GetIsNetworkAvailable_Success() [SkipOnPlatform(TestPlatforms.iOS | TestPlatforms.MacCatalyst | TestPlatforms.tvOS, "Not supported on Browser, iOS, MacCatalyst, or tvOS.")] [InlineData(false)] [InlineData(true)] - [ActiveIssue("https://github.com/dotnet/runtime/issues/50567", TestPlatforms.Android)] public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6) { using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp)) diff --git a/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceIPv4Statistics.cs b/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceIPv4Statistics.cs index 52aceb0d3f9c1..9b73374e99b26 100644 --- a/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceIPv4Statistics.cs +++ b/src/libraries/System.Net.NetworkInformation/tests/FunctionalTests/NetworkInterfaceIPv4Statistics.cs @@ -69,6 +69,17 @@ public void BasicTest_GetIPv4InterfaceStatistics_Success_Linux() } } + [Fact] + [PlatformSpecific(TestPlatforms.Android)] // This API is not supported on Android + public void BasicTest_GetIPv4InterfaceStatistics_NotSupported_Android() + { + // This API is not actually IPv4 specific. + foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) + { + Assert.Throws(() => nic.GetIPv4Statistics()); + } + } + [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX public void BasicTest_GetIPv4InterfaceStatistics_Success_OSX() diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs index fa5712656fafe..0d81532f2bc14 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs @@ -128,7 +128,7 @@ private bool TryGetPingReply( // Skip IP header. IcmpHeader receivedHeader = MemoryMarshal.Read(receiveBuffer.AsSpan(icmpHeaderOffset)); - ushort identifier = 0; + ushort identifier; type = receivedHeader.Type; code = receivedHeader.Code; diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs index 4467d7d654f37..68229958f88a7 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -376,11 +376,11 @@ private bool AgeCookies(string? domain) DateTime tempUsed; CookieCollection? lruCc = null; - string? lruDomain = null; + string? lruDomain; string tempDomain; PathList pathList; - int domain_count = 0; + int domain_count; int itemp = 0; float remainingFraction = 1.0F; @@ -1021,8 +1021,7 @@ public string GetCookieHeader(Uri uri) throw new ArgumentNullException(nameof(uri)); } - string dummy; - return GetCookieHeader(uri, out dummy); + return GetCookieHeader(uri, out _); } internal string GetCookieHeader(Uri uri, out string optCookie2) diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs index bb7801cbebb82..f0e19c005ab7f 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CredentialCache.cs @@ -225,7 +225,7 @@ public void Remove(string? host, int port, string? authenticationType) var key = new CredentialHostKey(host, port, authenticationType); - NetworkCredential? match = null; + NetworkCredential? match; _cacheForHosts.TryGetValue(key, out match); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Returning {((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")}"); diff --git a/src/libraries/System.Net.Primitives/tests/FunctionalTests/SocketAddressTest.cs b/src/libraries/System.Net.Primitives/tests/FunctionalTests/SocketAddressTest.cs index 09938a1c15d61..70ef816d1d0af 100644 --- a/src/libraries/System.Net.Primitives/tests/FunctionalTests/SocketAddressTest.cs +++ b/src/libraries/System.Net.Primitives/tests/FunctionalTests/SocketAddressTest.cs @@ -98,7 +98,7 @@ public static void ToString_LegacyUnknownFamily_Success(AddressFamily family) [Theory] [InlineData(AddressFamily.Packet)] [InlineData(AddressFamily.ControllerAreaNetwork)] - [SkipOnPlatform(TestPlatforms.Android | TestPlatforms.Linux | TestPlatforms.Browser, "Expected behavior is different on Android, Linux, or Browser")] + [SkipOnPlatform(TestPlatforms.Android | TestPlatforms.Linux | TestPlatforms.Browser, "Expected behavior is different on Android, Linux, or Browser")] public static void ToString_UnsupportedFamily_Throws(AddressFamily family) { Assert.Throws(() => new SocketAddress(family)); diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Interop/SafeMsQuicConfigurationHandle.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Interop/SafeMsQuicConfigurationHandle.cs index 24200021ec054..d536dfa58dbdc 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Interop/SafeMsQuicConfigurationHandle.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Interop/SafeMsQuicConfigurationHandle.cs @@ -156,9 +156,13 @@ private static unsafe SafeMsQuicConfigurationHandle Create(QuicOptions options, ulong ms = (ulong)options.IdleTimeout.Ticks / TimeSpan.TicksPerMillisecond; if (ms > (1ul << 62) - 1) throw new Exception("IdleTimeout is too large (max 2^62-1 milliseconds)"); - settings.IsSetFlags |= QuicSettingsIsSetFlags.IdleTimeoutMs; settings.IdleTimeoutMs = (ulong)options.IdleTimeout.TotalMilliseconds; } + else + { + settings.IdleTimeoutMs = 0; + } + settings.IsSetFlags |= QuicSettingsIsSetFlags.IdleTimeoutMs; uint status; SafeMsQuicConfigurationHandle? configurationHandle; diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs index 54f0ed3f4ec85..d2130779a7b87 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/MsQuicStream.cs @@ -533,7 +533,7 @@ private static unsafe int CopyMsQuicBuffersToUserBuffer(ReadOnlySpan int originalDestinationLength = destinationBuffer.Length; QuicBuffer nativeBuffer; - int takeLength = 0; + int takeLength; int i = 0; do diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs index 51d8a0d657931..eb608a0456794 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs @@ -1184,7 +1184,7 @@ protected override bool CheckValid(ResponseDescription response, ref int validTh // If the line contained three other digits followed by the response, then this is a violation of the // FTP protocol for multiline responses. // All other cases indicate that the response is not yet complete. - int index = 0; + int index; while ((index = responseString.IndexOf("\r\n", validThrough, StringComparison.Ordinal)) != -1) // gets the end line. { int lineStart = validThrough; diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 74dde855abe7e..b0f8f6a7fb6c3 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -812,7 +812,7 @@ public override IAsyncResult BeginGetRequestStream(AsyncCallback? callback, obje public override Stream EndGetRequestStream(IAsyncResult asyncResult) { - Stream? requestStream = null; + Stream? requestStream; try { if (asyncResult == null) diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs index fd0f63ba3baf5..0c1b2de92ad38 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebResponse.cs @@ -47,7 +47,7 @@ internal void UpdateStatus(FtpStatusCode statusCode, string? statusLine, string? public override Stream GetResponseStream() { - Stream? responseStream = null; + Stream? responseStream; if (_responseStream != null) { diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs index f1fef45e08126..6e9455954c29a 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.OSX.cs @@ -128,6 +128,11 @@ internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext secu using (SafeCFArrayHandle dnArray = Interop.AppleCrypto.SslCopyCADistinguishedNames(sslContext)) { + if (dnArray.IsInvalid) + { + return Array.Empty(); + } + long size = Interop.CoreFoundation.CFArrayGetCount(dnArray); if (size == 0) diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs index a2ea5bf41ea55..10ba2f5c772a7 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs @@ -20,7 +20,7 @@ internal static partial class NegotiateStreamPal { internal static IIdentity GetIdentity(NTAuthentication context) { - IIdentity? result = null; + IIdentity? result; string name = context.IsServer ? context.AssociatedName! : context.Spn!; string protocol = context.ProtocolName; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs index b75ee2bee7475..3690837e33f67 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.OSX/SafeDeleteSslContext.cs @@ -316,7 +316,7 @@ private static void SetProtocols(SafeSslHandle sslContext, SslProtocols protocol Interop.AppleCrypto.SslSetMaxProtocolVersion(sslContext, maxProtocolId); } - private static void SetCertificate(SafeSslHandle sslContext, SslStreamCertificateContext context) + internal static void SetCertificate(SafeSslHandle sslContext, SslStreamCertificateContext context) { Debug.Assert(sslContext != null, "sslContext != null"); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs index 1cc4fecd5ef50..9e6ad7475d766 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Implementation.cs @@ -1361,7 +1361,7 @@ private Framing DetectFraming(ReadOnlySpan bytes) // Returns TLS Frame size. private int GetFrameSize(ReadOnlySpan buffer) { - int payloadSize = -1; + int payloadSize; switch (_framing) { case Framing.Unified: diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs index 0414082781c1e..7043b7afe19f4 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs @@ -246,6 +246,13 @@ private static SecurityStatusPal HandshakeInternal( Interop.AppleCrypto.SslSetTargetName(sslContext.SslContext, sslAuthenticationOptions.TargetHost); } + if (sslAuthenticationOptions.CertificateContext == null && sslAuthenticationOptions.CertSelectionDelegate != null) + { + // certificate was not provided but there is user callback. We can break handshake if server asks for certificate + // and we can try to get it based on remote certificate and trusted issuers. + Interop.AppleCrypto.SslBreakOnCertRequested(sslContext.SslContext, true); + } + if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired) { Interop.AppleCrypto.SslSetAcceptClientCert(sslContext.SslContext); @@ -259,6 +266,35 @@ private static SecurityStatusPal HandshakeInternal( SafeSslHandle sslHandle = sslContext!.SslContext; SecurityStatusPal status = PerformHandshake(sslHandle); + if (status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded) + { + // we should not be here if CertSelectionDelegate is null but better check before dereferencing.. + if (sslAuthenticationOptions.CertSelectionDelegate != null) + { + X509Certificate2? remoteCert = null; + try + { + string[] issuers = CertificateValidationPal.GetRequestCertificateAuthorities(context); + remoteCert = CertificateValidationPal.GetRemoteCertificate(context); + if (sslAuthenticationOptions.ClientCertificates == null) + { + sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection(); + } + X509Certificate2 clientCertificate = (X509Certificate2)sslAuthenticationOptions.CertSelectionDelegate(sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, remoteCert, issuers); + if (clientCertificate != null) + { + SafeDeleteSslContext.SetCertificate(sslContext.SslContext, SslStreamCertificateContext.Create(clientCertificate)); + } + } + finally + { + remoteCert?.Dispose(); + } + } + + // We either got certificate or we can proceed without it. It is up to the server to decide if either is OK. + status = PerformHandshake(sslHandle); + } outputBuffer = sslContext.ReadPendingWrites(); return status; @@ -290,6 +326,8 @@ private static SecurityStatusPal PerformHandshake(SafeSslHandle sslHandle) // So, call SslHandshake again to indicate to Secure Transport that we've // accepted this handshake and it should go into the ready state. break; + case PAL_TlsHandshakeState.ClientCertRequested: + return new SecurityStatusPal(SecurityStatusPalErrorCode.CredentialsNeeded); default: return new SecurityStatusPal( SecurityStatusPalErrorCode.InternalError, diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs index 78b6cf47405c3..63c4efc1edb65 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs @@ -87,6 +87,7 @@ private static SecurityStatusPal MapNativeErrorCode(Interop.Ssl.SslErrorCode err { Interop.Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE => new SecurityStatusPal(SecurityStatusPalErrorCode.Renegotiate), Interop.Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN => new SecurityStatusPal(SecurityStatusPalErrorCode.ContextExpired), + Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_X509_LOOKUP => new SecurityStatusPal(SecurityStatusPalErrorCode.CredentialsNeeded), Interop.Ssl.SslErrorCode.SSL_ERROR_NONE or Interop.Ssl.SslErrorCode.SSL_ERROR_WANT_READ => new SecurityStatusPal(SecurityStatusPalErrorCode.OK), _ => new SecurityStatusPal(SecurityStatusPalErrorCode.InternalError, new Interop.OpenSsl.SslException((int)errorCode)) @@ -118,7 +119,7 @@ Interop.Ssl.SslErrorCode.SSL_ERROR_NONE or public static SecurityStatusPal Renegotiate(ref SafeFreeCredentials? credentialsHandle, ref SafeDeleteSslContext? securityContext, SslAuthenticationOptions sslAuthenticationOptions, out byte[]? outputBuffer) { var sslContext = ((SafeDeleteSslContext)securityContext!).SslContext; - SecurityStatusPal status = Interop.OpenSsl.SslRenegotiate(sslContext, out outputBuffer); + SecurityStatusPal status = Interop.OpenSsl.SslRenegotiate(sslContext, out _); outputBuffer = Array.Empty(); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) @@ -138,11 +139,6 @@ public static void QueryContextConnectionInfo(SafeDeleteSslContext securityConte connectionInfo = new SslConnectionInfo(securityContext.SslContext); } - public static byte[] ConvertAlpnProtocolListToByteArray(List applicationProtocols) - { - return Interop.Ssl.ConvertAlpnProtocolListToByteArray(applicationProtocols); - } - private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credential, ref SafeDeleteSslContext? context, ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { @@ -158,12 +154,42 @@ private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credentia context = new SafeDeleteSslContext((credential as SafeFreeSslCredentials)!, sslAuthenticationOptions); } - bool done = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, inputBuffer, out output, out outputSize); + SecurityStatusPalErrorCode errorCode = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, inputBuffer, out output, out outputSize); + + if (errorCode == SecurityStatusPalErrorCode.CredentialsNeeded) + { + if (sslAuthenticationOptions.CertSelectionDelegate != null) + { + X509Certificate2? remoteCert = null; + string[] issuers = CertificateValidationPal.GetRequestCertificateAuthorities(context); + try + { + remoteCert = CertificateValidationPal.GetRemoteCertificate(context); + if (sslAuthenticationOptions.ClientCertificates == null) + { + sslAuthenticationOptions.ClientCertificates = new X509CertificateCollection(); + } + X509Certificate2 clientCertificate = (X509Certificate2)sslAuthenticationOptions.CertSelectionDelegate(sslAuthenticationOptions.TargetHost!, sslAuthenticationOptions.ClientCertificates, remoteCert, issuers); + if (clientCertificate != null && clientCertificate.HasPrivateKey) + { + sslAuthenticationOptions.CertificateContext = SslStreamCertificateContext.Create(clientCertificate); + } + } + finally + { + remoteCert?.Dispose(); + } + } + + Interop.OpenSsl.UpdateClientCertiticate(((SafeDeleteSslContext)context).SslContext, sslAuthenticationOptions); + errorCode = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, null, out output, out outputSize); + } + // sometimes during renegotiation processing messgae does not yield new output. // That seems to be flaw in OpenSSL state machine and we have workaround to peek it and try it again. if (outputSize == 0 && Interop.Ssl.IsSslRenegotiatePending(((SafeDeleteSslContext)context).SslContext)) { - done = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, ReadOnlySpan.Empty, out output, out outputSize); + errorCode = Interop.OpenSsl.DoSslHandshake(((SafeDeleteSslContext)context).SslContext, ReadOnlySpan.Empty, out output, out outputSize); } // When the handshake is done, and the context is server, check if the alpnHandle target was set to null during ALPN. @@ -171,7 +197,7 @@ private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credentia // We have this workaround, as openssl supports terminating handshake only from version 1.1.0, // whereas ALPN is supported from version 1.0.2. SafeSslHandle sslContext = context.SslContext; - if (done && sslAuthenticationOptions.IsServer + if (errorCode == SecurityStatusPalErrorCode.OK && sslAuthenticationOptions.IsServer && sslAuthenticationOptions.ApplicationProtocols != null && sslAuthenticationOptions.ApplicationProtocols.Count != 0 && sslContext.AlpnHandle.IsAllocated && sslContext.AlpnHandle.Target == null) { @@ -183,7 +209,7 @@ private static SecurityStatusPal HandshakeInternal(SafeFreeCredentials credentia outputSize == output!.Length ? output : new Span(output, 0, outputSize).ToArray(); - return new SecurityStatusPal(done ? SecurityStatusPalErrorCode.OK : SecurityStatusPalErrorCode.ContinueNeeded); + return new SecurityStatusPal(errorCode); } catch (Exception exc) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs index 139f77f83b517..2fb36e595b20d 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs @@ -196,11 +196,10 @@ public static unsafe SafeFreeCredentials AcquireCredentialsHandleSchannelCred(Ss protocolFlags, policy); - Interop.Crypt32.CERT_CONTEXT* certificateHandle = null; if (certificate != null) { secureCredential.cCreds = 1; - certificateHandle = (Interop.Crypt32.CERT_CONTEXT*)certificate.Handle; + Interop.Crypt32.CERT_CONTEXT* certificateHandle = (Interop.Crypt32.CERT_CONTEXT*)certificate.Handle; secureCredential.paCred = &certificateHandle; } @@ -253,11 +252,10 @@ public static unsafe SafeFreeCredentials AcquireCredentialsHandleSchCredentials( Interop.SspiCli.SCH_CREDENTIALS credential = default; credential.dwVersion = Interop.SspiCli.SCH_CREDENTIALS.CurrentVersion; credential.dwFlags = flags; - Interop.Crypt32.CERT_CONTEXT *certificateHandle = null; if (certificate != null) { credential.cCreds = 1; - certificateHandle = (Interop.Crypt32.CERT_CONTEXT *)certificate.Handle; + Interop.Crypt32.CERT_CONTEXT* certificateHandle = (Interop.Crypt32.CERT_CONTEXT*)certificate.Handle; credential.paCred = &certificateHandle; } diff --git a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs index 8797f31cf589e..43260e11d3e7d 100644 --- a/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs +++ b/src/libraries/System.Net.Security/src/System/Security/Authentication/ExtendedProtection/ServiceNameCollection.cs @@ -217,8 +217,7 @@ private static int GetCountOrOne(IEnumerable collection) port = hostAndPort.Substring(colonIndex + 1); // Excludes colon // Loosely validate the port just to make sure it was a port and not something else. - ushort portValue; - if (!ushort.TryParse(port, NumberStyles.Integer, CultureInfo.InvariantCulture, out portValue)) + if (!ushort.TryParse(port, NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) { return inputServiceName; } diff --git a/src/libraries/System.Net.Security/tests/FunctionalTests/CertificateValidationClientServer.cs b/src/libraries/System.Net.Security/tests/FunctionalTests/CertificateValidationClientServer.cs index a605c859b4051..5ca6a63e0d4ac 100644 --- a/src/libraries/System.Net.Security/tests/FunctionalTests/CertificateValidationClientServer.cs +++ b/src/libraries/System.Net.Security/tests/FunctionalTests/CertificateValidationClientServer.cs @@ -3,6 +3,7 @@ using System.Net.Sockets; using System.Net.Test.Common; +using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; @@ -34,6 +35,80 @@ public void Dispose() _clientCertificate.Dispose(); } + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindows7))] + [InlineData(true, true)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(false, false)] + public async Task CertificateSelectionCallback_DelayedCertificate_OK(bool delayCertificate, bool sendClientCertificate) + { + X509Certificate? remoteCertificate = null; + + (SslStream client, SslStream server) = TestHelper.GetConnectedSslStreams(); + using (client) + using (server) + { + int count = 0; + SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions(); + clientOptions.TargetHost = "localhost"; + // Force Tls 1.2 to avoid issues with certain OpenSSL versions and Tls 1.3 + // https://github.com/openssl/openssl/issues/7384 + clientOptions.EnabledSslProtocols = SslProtocols.Tls12; + clientOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; + clientOptions.LocalCertificateSelectionCallback = (sender, targetHost, localCertificates, certificate, acceptableIssuers) => + { + count++; + remoteCertificate = certificate; + if (delayCertificate && count == 1) + { + // wait until we get remote certificate from peer e.g. handshake started. + return null; + } + + return sendClientCertificate ? _clientCertificate : null; + }; + + SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions(); + serverOptions.ServerCertificate = _serverCertificate; + serverOptions.ClientCertificateRequired = true; + serverOptions.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => + { + if (sendClientCertificate) + { + Assert.NotNull(certificate); + // The client chain may be incomplete. + Assert.True(sslPolicyErrors == SslPolicyErrors.None || sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors); + } + else + { + Assert.Equal(SslPolicyErrors.RemoteCertificateNotAvailable, sslPolicyErrors); + } + + return true; + }; + + + await TestConfiguration.WhenAllOrAnyFailedWithTimeout( + client.AuthenticateAsClientAsync(clientOptions), + server.AuthenticateAsServerAsync(serverOptions)); + + // verify that the session is usable with or without client's certificate + await TestHelper.PingPong(client, server); + await TestHelper.PingPong(server, client); + + if (delayCertificate) + { + // LocalCertificateSelectionCallback should be called with real remote certificate. + if (!OperatingSystem.IsWindows()) + { + // remote certificate does not work on windows. + // https://github.com/dotnet/runtime/issues/63321 + Assert.NotNull(remoteCertificate); + } + } + } + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/DynamicWinsockMethods.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/DynamicWinsockMethods.cs index 789a1782172bf..923277fbb8220 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/DynamicWinsockMethods.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/DynamicWinsockMethods.cs @@ -57,8 +57,7 @@ private DynamicWinsockMethods(AddressFamily addressFamily, SocketType socketType private static T CreateDelegate([NotNull] ref T? cache, SafeSocketHandle socketHandle, string guidString) where T: Delegate { Guid guid = new Guid(guidString); - IntPtr ptr = IntPtr.Zero; - int length; + IntPtr ptr; SocketError errorCode; unsafe @@ -70,7 +69,7 @@ private static T CreateDelegate([NotNull] ref T? cache, SafeSocketHandle sock sizeof(Guid), out ptr, sizeof(IntPtr), - out length, + out _, IntPtr.Zero, IntPtr.Zero); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index 40b34ca83b2bc..f3ecb8e64a9f0 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -1169,7 +1169,6 @@ public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, ou ValidateBufferArguments(buffer, offset, size); - errorCode = SocketError.Success; ValidateBlockingMode(); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"SRC:{LocalEndPoint} DST:{RemoteEndPoint} size:{size}"); @@ -1886,7 +1885,7 @@ public int IOControl(int ioControlCode, byte[]? optionInValue, byte[]? optionOut { ThrowIfDisposed(); - int realOptionLength = 0; + int realOptionLength; // IOControl is used for Windows-specific IOCTL operations. If we need to add support for IOCTLs specific // to other platforms, we will likely need to add a new API, as the control codes may overlap with those @@ -2037,7 +2036,7 @@ public void SetRawSocketOption(int optionLevel, int optionName, ReadOnlySpan Narrow(System.Numerics.Vector low, System.Numerics.Vector high) { throw null; } public static System.Numerics.Vector Negate(System.Numerics.Vector value) where T : struct { throw null; } public static System.Numerics.Vector OnesComplement(System.Numerics.Vector value) where T : struct { throw null; } + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftLeft(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightArithmetic(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightArithmetic(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightArithmetic(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightArithmetic(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftRightArithmetic(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Numerics.Vector ShiftRightLogical(System.Numerics.Vector value, int shiftCount) { throw null; } public static System.Numerics.Vector SquareRoot(System.Numerics.Vector value) where T : struct { throw null; } public static System.Numerics.Vector Subtract(System.Numerics.Vector left, System.Numerics.Vector right) where T : struct { throw null; } [System.CLSCompliantAttribute(false)] diff --git a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs index 68eab6c5bbac6..e36440a56a822 100644 --- a/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs +++ b/src/libraries/System.Private.CoreLib/src/Internal/Win32/RegistryKey.cs @@ -252,7 +252,7 @@ public unsafe string[] GetValueNames() case Interop.Advapi32.RegistryValues.REG_BINARY: { byte[] blob = new byte[datasize]; - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); data = blob; } break; @@ -266,7 +266,7 @@ public unsafe string[] GetValueNames() long blob = 0; Debug.Assert(datasize == 8, "datasize==8"); // Here, datasize must be 8 when calling this - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); data = blob; } @@ -281,7 +281,7 @@ public unsafe string[] GetValueNames() int blob = 0; Debug.Assert(datasize == 4, "datasize==4"); // Here, datasize must be four when calling this - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); data = blob; } @@ -303,7 +303,7 @@ public unsafe string[] GetValueNames() } char[] blob = new char[datasize / 2]; - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[^1] == (char)0) { data = new string(blob, 0, blob.Length - 1); @@ -333,7 +333,7 @@ public unsafe string[] GetValueNames() } char[] blob = new char[datasize / 2]; - ret = Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); + Interop.Advapi32.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); if (blob.Length > 0 && blob[^1] == (char)0) { diff --git a/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs b/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs index 32e242e0d8e4c..6bfd650a0d2fc 100644 --- a/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs @@ -57,6 +57,10 @@ internal bool SupportsRandomAccess internal void EnsureThreadPoolBindingInitialized() { /* nop */ } + internal bool LengthCanBeCached => false; + + internal bool HasCachedFileLength => false; + private static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode, Func? createOpenException) { @@ -504,6 +508,13 @@ private bool GetCanSeek() return canSeek == NullableBool.True; } + internal long GetFileLength() + { + int result = Interop.Sys.FStat(this, out Interop.Sys.FileStatus status); + FileStreamHelpers.CheckFileCall(result, Path); + return status.Size; + } + private enum NullableBool { Undefined = 0, diff --git a/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs b/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs index 3352f0194e73b..a4ecc686513cb 100644 --- a/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics; using System.IO; -using System.IO.Strategies; using System.Runtime.InteropServices; using System.Threading; @@ -13,6 +12,8 @@ namespace Microsoft.Win32.SafeHandles public sealed partial class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid { internal const FileOptions NoBuffering = (FileOptions)0x20000000; + private long _length = -1; // negative means that hasn't been fetched. + private bool _lengthCanBeCached; // file has been opened for reading and not shared for writing. private volatile FileOptions _fileOptions = (FileOptions)(-1); private volatile int _fileType = -1; @@ -22,10 +23,16 @@ public SafeFileHandle() : base(true) public bool IsAsync => (GetFileOptions() & FileOptions.Asynchronous) != 0; + internal bool IsNoBuffering => (GetFileOptions() & NoBuffering) != 0; + internal bool CanSeek => !IsClosed && GetFileType() == Interop.Kernel32.FileTypes.FILE_TYPE_DISK; internal ThreadPoolBoundHandle? ThreadPoolBinding { get; set; } + internal bool LengthCanBeCached => _lengthCanBeCached; + + internal bool HasCachedFileLength => _lengthCanBeCached && _length >= 0; + internal static unsafe SafeFileHandle Open(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize) { using (DisableMediaInsertionPrompt.Create()) @@ -103,6 +110,7 @@ private static unsafe SafeFileHandle CreateFile(string fullPath, FileMode mode, fileHandle._path = fullPath; fileHandle._fileOptions = options; + fileHandle._lengthCanBeCached = (share & FileShare.Write) == 0 && (access & FileAccess.Write) == 0; return fileHandle; } @@ -252,5 +260,34 @@ internal int GetFileType() return fileType; } + + internal unsafe long GetFileLength() + { + if (!_lengthCanBeCached) + { + return GetFileLengthCore(); + } + + // On Windows, when the file is locked for writes we can cache file length + // in memory and avoid subsequent native calls which are expensive. + if (_length < 0) + { + _length = GetFileLengthCore(); + } + + return _length; + + long GetFileLengthCore() + { + Interop.Kernel32.FILE_STANDARD_INFO info; + + if (!Interop.Kernel32.GetFileInformationByHandleEx(this, Interop.Kernel32.FileStandardInfo, &info, (uint)sizeof(Interop.Kernel32.FILE_STANDARD_INFO))) + { + throw Win32Marshal.GetExceptionForLastWin32Error(Path); + } + + return info.EndOfFile; + } + } } } diff --git a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems index 5c3b0ad8ed3ae..59796633cc4db 100644 --- a/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems +++ b/src/libraries/System.Private.CoreLib/src/System.Private.CoreLib.Shared.projitems @@ -532,6 +532,7 @@ + @@ -1058,6 +1059,7 @@ + @@ -2186,12 +2188,13 @@ - + - + + @@ -2357,4 +2360,4 @@ - + \ No newline at end of file diff --git a/src/libraries/System.Private.CoreLib/src/System/ArraySegment.cs b/src/libraries/System.Private.CoreLib/src/System/ArraySegment.cs index f2acaca5d0dbe..06c31c4d6e009 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ArraySegment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ArraySegment.cs @@ -197,7 +197,7 @@ int IList.IndexOf(T item) int index = System.Array.IndexOf(_array!, item, _offset, _count); - Debug.Assert(index == -1 || + Debug.Assert(index < 0 || (index >= _offset && index < _offset + _count)); return index >= 0 ? index - _offset : -1; @@ -238,7 +238,7 @@ bool ICollection.Contains(T item) int index = System.Array.IndexOf(_array!, item, _offset, _count); - Debug.Assert(index == -1 || + Debug.Assert(index < 0 || (index >= _offset && index < _offset + _count)); return index >= 0; diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs index e5e201301b385..cc79cb9ab8e56 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/List.cs @@ -318,7 +318,7 @@ public bool Contains(T item) // via EqualityComparer.Default.Equals, we // only make one virtual call to EqualityComparer.IndexOf. - return _size != 0 && IndexOf(item) != -1; + return _size != 0 && IndexOf(item) >= 0; } bool IList.Contains(object? item) diff --git a/src/libraries/System.Private.CoreLib/src/System/Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Enum.cs index 3af9ab2a2bcfa..7267c82a7449c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Enum.cs @@ -951,7 +951,7 @@ private static bool TryParseByName(RuntimeType enumType, ReadOnlySpan valu // Find the next separator. ReadOnlySpan subvalue; int endIndex = value.IndexOf(EnumSeparatorChar); - if (endIndex == -1) + if (endIndex < 0) { // No next separator; use the remainder as the next value. subvalue = value.Trim(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs index 97295b79c7342..50393d6b1e37c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs @@ -20,7 +20,7 @@ public static string MachineName { string hostName = Interop.Sys.GetHostName(); int dotPos = hostName.IndexOf('.'); - return dotPos == -1 ? hostName : hostName.Substring(0, dotPos); + return dotPos < 0 ? hostName : hostName.Substring(0, dotPos); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs index a4d6468084f09..0f190d79f2ee6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Win32.cs @@ -123,7 +123,7 @@ public static string UserName ReadOnlySpan name = builder.AsSpan(); int index = name.IndexOf('\\'); - if (index != -1) + if (index >= 0) { // In the form of DOMAIN\User, cut off DOMAIN\ name = name.Slice(index + 1); @@ -164,7 +164,7 @@ public static string UserDomainName ReadOnlySpan name = builder.AsSpan(); int index = name.IndexOf('\\'); - if (index != -1) + if (index >= 0) { // In the form of DOMAIN\User, cut off \User and return builder.Length = index; diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.cs index 49a214ff7d06d..5a05ee1f33c71 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.cs @@ -195,7 +195,7 @@ public static Version Version // Strip optional suffixes int separatorIndex = versionSpan.IndexOfAny('-', '+', ' '); - if (separatorIndex != -1) + if (separatorIndex >= 0) versionSpan = versionSpan.Slice(0, separatorIndex); // Return zeros rather then failing if the version string fails to parse diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.iOS.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.iOS.cs new file mode 100644 index 0000000000000..90512ca598bd8 --- /dev/null +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.iOS.cs @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Runtime.InteropServices; + +namespace System +{ + public static partial class Environment + { + // iOS/tvOS aren't allowed to call libproc APIs so return 0 here, this also matches what we returned in earlier releases + public static long WorkingSet => 0; + } +} diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs index efece6f4d571a..f5d5b0061f06d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Icu.cs @@ -305,7 +305,7 @@ private static string NormalizeDatePattern(string input) break; case 'G': // 'G' in ICU is the era, which maps to 'g' in .NET - occurrences = CountOccurrences(input, 'G', ref index); + CountOccurrences(input, 'G', ref index); // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they // have the same meaning diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs index d92419490f16f..bdee108ba076f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs @@ -2094,7 +2094,7 @@ private static string GetSeparator(string format, string timeParts) private static int IndexOfTimePart(string format, int startIndex, string timeParts) { Debug.Assert(startIndex >= 0, "startIndex cannot be negative"); - Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters"); + Debug.Assert(timeParts.AsSpan().IndexOfAny('\'', '\\') < 0, "timeParts cannot include quote characters"); bool inQuote = false; for (int i = startIndex; i < format.Length; ++i) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs index a7ebe4c496f64..6020e84411bf3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeParse.cs @@ -5461,7 +5461,7 @@ internal bool MatchSpecifiedWords(string target, bool checkWordBoundary, ref int int targetPosition = 0; // Where we are in the target string int thisPosition = Index; // Where we are in this string int wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition); - if (wsIndex == -1) + if (wsIndex < 0) { return false; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Guid.cs b/src/libraries/System.Private.CoreLib/src/System/Guid.cs index 50123b8d0be36..a5ba1f6c870b2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Guid.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Guid.cs @@ -434,7 +434,7 @@ private static bool TryParseExactD(ReadOnlySpan guidString, ref GuidResult // We continue to support these but expect them to be incredibly rare. As such, we // optimize for correctly formed strings where all the digits are valid hex, and only // fall back to supporting these other forms if parsing fails. - if (guidString.IndexOfAny('X', 'x', '+') != -1 && TryCompatParsing(guidString, ref result)) + if (guidString.IndexOfAny('X', 'x', '+') >= 0 && TryCompatParsing(guidString, ref result)) { return true; } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs index c7c1434d69cba..5c25031957d45 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BufferedStream.cs @@ -48,16 +48,14 @@ public sealed class BufferedStream : Stream private const int MaxShadowBufferSize = 81920; // Make sure not to get to the Large Object Heap. private const int DefaultBufferSize = 4096; - private Stream? _stream; // Underlying stream. Close sets _stream to null. - private byte[]? _buffer; // Shared read/write buffer. Alloc on first use. - private readonly int _bufferSize; // Length of internal buffer (not counting the shadow buffer). - private int _readPos; // Read pointer within shared buffer. - private int _readLen; // Number of bytes read in buffer from _stream. - private int _writePos; // Write pointer within shared buffer. - private Task? _lastSyncCompletedReadTask; // The last successful Task returned from ReadAsync - // (perf optimization for successive reads of the same size) - // Removing a private default constructor is a breaking change for the DataDebugSerializer. - // Because this ctor was here previously we need to keep it around. + private Stream? _stream; // Underlying stream. Close sets _stream to null. + private byte[]? _buffer; // Shared read/write buffer. Alloc on first use. + private readonly int _bufferSize; // Length of internal buffer (not counting the shadow buffer). + private int _readPos; // Read pointer within shared buffer. + private int _readLen; // Number of bytes read in buffer from _stream. + private int _writePos; // Write pointer within shared buffer. + private CachedCompletedInt32Task _lastSyncCompletedReadTask; // The last successful Task returned from ReadAsync + // (perf optimization for successive reads of the same size) public BufferedStream(Stream stream) : this(stream, DefaultBufferSize) @@ -571,19 +569,6 @@ public override int Read(Span destination) } } - private Task LastSyncCompletedReadTask(int val) - { - Task? t = _lastSyncCompletedReadTask; - Debug.Assert(t == null || t.IsCompletedSuccessfully); - - if (t != null && t.Result == val) - return t; - - t = Task.FromResult(val); - _lastSyncCompletedReadTask = t; - return t; - } - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { ValidateBufferArguments(buffer, offset, count); @@ -622,7 +607,7 @@ public override Task ReadAsync(byte[] buffer, int offset, int count, Cancel { return (error == null) - ? LastSyncCompletedReadTask(bytesFromBuffer) + ? _lastSyncCompletedReadTask.GetTask(bytesFromBuffer) : Task.FromException(error); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEntry.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEntry.Unix.cs index 1be3942011b2f..89c38584eea32 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEntry.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEntry.Unix.cs @@ -145,7 +145,7 @@ public FileAttributes Attributes public DateTimeOffset CreationTimeUtc => _status.GetCreationTime(FullPath, continueOnError: true); public DateTimeOffset LastAccessTimeUtc => _status.GetLastAccessTime(FullPath, continueOnError: true); public DateTimeOffset LastWriteTimeUtc => _status.GetLastWriteTime(FullPath, continueOnError: true); - public bool IsHidden => _status.IsHidden(FullPath, FileName, continueOnError: true); + public bool IsHidden => _status.IsFileSystemEntryHidden(FullPath, FileName); internal bool IsReadOnly => _status.IsReadOnly(FullPath, continueOnError: true); public bool IsDirectory => _status.InitiallyDirectory; diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerableFactory.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerableFactory.cs index 00868756b91d1..33b8c92a32ff3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerableFactory.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerableFactory.cs @@ -76,7 +76,7 @@ internal static bool NormalizeInputs(ref string directory, ref string expression } else { - if (Path.DirectorySeparatorChar != '\\' && expression.IndexOfAny(s_unixEscapeChars) != -1) + if (Path.DirectorySeparatorChar != '\\' && expression.IndexOfAny(s_unixEscapeChars) >= 0) { // Backslash isn't the default separator, need to escape (e.g. Unix) expression = expression.Replace("\\", "\\\\"); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemName.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemName.cs index 6ee823c5739db..92e977b4c5896 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemName.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemName.cs @@ -161,7 +161,7 @@ private static bool MatchPattern(ReadOnlySpan expression, ReadOnlySpan expressionEnd = expression.Slice(1); - if (expressionEnd.IndexOfAny(useExtendedWildcards ? s_wildcardChars : s_simpleWildcardChars) == -1) + if (expressionEnd.IndexOfAny(useExtendedWildcards ? s_wildcardChars : s_simpleWildcardChars) < 0) { // Handle the special case of a single starting *, which essentially means "ends with" diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/File.cs b/src/libraries/System.Private.CoreLib/src/System/IO/File.cs index aa0bb62be57dc..2b4c61f1eb0ba 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/File.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/File.cs @@ -256,7 +256,7 @@ public static byte[] ReadAllBytes(string path) using (SafeFileHandle sfh = OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read, options)) { long fileLength = 0; - if (sfh.CanSeek && (fileLength = RandomAccess.GetFileLength(sfh)) > Array.MaxLength) + if (sfh.CanSeek && (fileLength = sfh.GetFileLength()) > Array.MaxLength) { throw new IOException(SR.IO_FileTooLong2GB); } @@ -530,7 +530,7 @@ private static async Task InternalReadAllTextAsync(string path, Encoding SafeFileHandle sfh = OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read, options); long fileLength = 0L; - if (sfh.CanSeek && (fileLength = RandomAccess.GetFileLength(sfh)) > Array.MaxLength) + if (sfh.CanSeek && (fileLength = sfh.GetFileLength()) > Array.MaxLength) { sfh.Dispose(); return Task.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new IOException(SR.IO_FileTooLong2GB))); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs index 05b4bbcff6a2a..20961a8fbbc2e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs @@ -145,14 +145,20 @@ internal bool IsReadOnly(ReadOnlySpan path, bool continueOnError = false) return HasReadOnlyFlag; } - internal bool IsHidden(ReadOnlySpan path, ReadOnlySpan fileName, bool continueOnError = false) + internal bool IsFileSystemEntryHidden(ReadOnlySpan path, ReadOnlySpan fileName) { - // Avoid disk hit first + // Because this is called for FileSystemEntry we can assume the entry exists and + // avoid initialization in some cases. if (IsNameHidden(fileName)) { return true; } - EnsureCachesInitialized(path, continueOnError); + if (!Interop.Sys.SupportsHiddenFlag) + { + return false; + } + + EnsureCachesInitialized(path, continueOnError: true); return HasHiddenFlag; } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs index 3436a7f1428f6..d554994b9d100 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs @@ -456,7 +456,6 @@ public static string[] GetLogicalDrives() internal static void CreateSymbolicLink(string path, string pathToTarget, bool isDirectory) { - string pathToTargetFullPath = PathInternal.GetLinkTargetFullPath(path, pathToTarget); Interop.Kernel32.CreateSymbolicLink(path, pathToTarget, isDirectory); } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs index 9677f82426a84..0c1739873f403 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/MemoryStream.cs @@ -32,7 +32,7 @@ public class MemoryStream : Stream private readonly bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? - private Task? _lastReadTask; // The last successful task returned from ReadAsync + private CachedCompletedInt32Task _lastReadTask; // The last successful task returned from ReadAsync private const int MemStreamMaxLength = int.MaxValue; @@ -127,7 +127,7 @@ protected override void Dispose(bool disposing) _writable = false; _expandable = false; // Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work. - _lastReadTask = null; + _lastReadTask = default; } } finally @@ -389,10 +389,7 @@ public override Task ReadAsync(byte[] buffer, int offset, int count, Cancel try { int n = Read(buffer, offset, count); - Task? t = _lastReadTask; - Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion, - "Expected that a stored last task completed successfully"); - return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult(n)); + return _lastReadTask.GetTask(n); } catch (OperationCanceledException oce) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs index 3732397f17ba0..b2887383294eb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Path.cs @@ -226,7 +226,7 @@ public static ReadOnlySpan GetFileNameWithoutExtension(ReadOnlySpan { ReadOnlySpan fileName = GetFileName(path); int lastPeriod = fileName.LastIndexOf('.'); - return lastPeriod == -1 ? + return lastPeriod < 0 ? fileName : // No extension was found fileName.Slice(0, lastPeriod); } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.Unix.cs index d922e89c13de5..d9739e3082dfd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.Unix.cs @@ -19,13 +19,6 @@ public static partial class RandomAccess // that get stackalloced in the Linux kernel. private const int IovStackThreshold = 8; - internal static long GetFileLength(SafeFileHandle handle) - { - int result = Interop.Sys.FStat(handle, out Interop.Sys.FileStatus status); - FileStreamHelpers.CheckFileCall(result, handle.Path); - return status.Size; - } - internal static unsafe int ReadAtOffset(SafeFileHandle handle, Span buffer, long fileOffset) { fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer)) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.Windows.cs index 348b0bf4f15a5..4e79f02de4081 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.Windows.cs @@ -18,18 +18,6 @@ public static partial class RandomAccess { private static readonly IOCompletionCallback s_callback = AllocateCallback(); - internal static unsafe long GetFileLength(SafeFileHandle handle) - { - Interop.Kernel32.FILE_STANDARD_INFO info; - - if (!Interop.Kernel32.GetFileInformationByHandleEx(handle, Interop.Kernel32.FileStandardInfo, &info, (uint)sizeof(Interop.Kernel32.FILE_STANDARD_INFO))) - { - throw Win32Marshal.GetExceptionForLastWin32Error(handle.Path); - } - - return info.EndOfFile; - } - internal static unsafe int ReadAtOffset(SafeFileHandle handle, Span buffer, long fileOffset) { if (handle.IsAsync) @@ -53,8 +41,8 @@ internal static unsafe int ReadAtOffset(SafeFileHandle handle, Span buffer // "If lpOverlapped is not NULL, then when a synchronous read operation reaches the end of a file, // ReadFile returns FALSE and GetLastError returns ERROR_HANDLE_EOF" return numBytesRead; - case Interop.Errors.ERROR_BROKEN_PIPE: - // For pipes, ERROR_BROKEN_PIPE is the normal end of the pipe. + case Interop.Errors.ERROR_BROKEN_PIPE: // For pipes, ERROR_BROKEN_PIPE is the normal end of the pipe. + case Interop.Errors.ERROR_INVALID_PARAMETER when IsEndOfFileForNoBuffering(handle, fileOffset): return 0; default: throw Win32Marshal.GetExceptionForWin32Error(errorCode, handle.Path); @@ -100,6 +88,7 @@ private static unsafe int ReadSyncUsingAsyncHandle(SafeFileHandle handle, Span fileHandle.IsNoBuffering && fileHandle.CanSeek && fileOffset >= fileHandle.GetFileLength(); + // We need to store the reference count (see the comment in FreeNativeOverlappedIfItIsSafe) and an EventHandle to signal the completion. // We could keep these two things separate, but since ManualResetEvent is sealed and we want to avoid any extra allocations, this type has been created. // It's basically ManualResetEvent with reference count. diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.cs b/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.cs index 04b59ae472a76..5c4ede7ff408b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/RandomAccess.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO.Strategies; -using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; @@ -25,7 +24,7 @@ public static long GetLength(SafeFileHandle handle) { ValidateInput(handle, fileOffset: 0); - return GetFileLength(handle); + return handle.GetFileLength(); } /// diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/BufferedFileStreamStrategy.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/BufferedFileStreamStrategy.cs index 9de42145c00de..c1f62e92e4b25 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/BufferedFileStreamStrategy.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/BufferedFileStreamStrategy.cs @@ -21,7 +21,7 @@ internal sealed class BufferedFileStreamStrategy : FileStreamStrategy private int _readPos; private int _readLen; // The last successful Task returned from ReadAsync (perf optimization for successive reads of the same size) - private Task? _lastSyncCompletedReadTask; + private CachedCompletedInt32Task _lastSyncCompletedReadTask; internal BufferedFileStreamStrategy(FileStreamStrategy strategy, int bufferSize) { @@ -310,21 +310,8 @@ public override Task ReadAsync(byte[] buffer, int offset, int count, Cancel ValueTask readResult = ReadAsync(new Memory(buffer, offset, count), cancellationToken); return readResult.IsCompletedSuccessfully - ? LastSyncCompletedReadTask(readResult.Result) + ? _lastSyncCompletedReadTask.GetTask(readResult.Result) : readResult.AsTask(); - - Task LastSyncCompletedReadTask(int val) - { - Task? t = _lastSyncCompletedReadTask; - Debug.Assert(t == null || t.IsCompletedSuccessfully); - - if (t != null && t.Result == val) - return t; - - t = Task.FromResult(val); - _lastSyncCompletedReadTask = t; - return t; - } } public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/OSFileStreamStrategy.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/OSFileStreamStrategy.cs index 0386dfa78d563..662945c0941e9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/OSFileStreamStrategy.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/OSFileStreamStrategy.cs @@ -4,7 +4,6 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; -using System.Threading.Tasks.Sources; using Microsoft.Win32.SafeHandles; namespace System.IO.Strategies @@ -16,9 +15,7 @@ internal abstract class OSFileStreamStrategy : FileStreamStrategy private readonly FileAccess _access; // What file was opened for. protected long _filePosition; - private long _length = -1; // negative means that hasn't been fetched. private long _appendStart; // When appending, prevent overwriting file. - private bool _lengthCanBeCached; // SafeFileHandle hasn't been exposed, file has been opened for reading and not shared for writing. internal OSFileStreamStrategy(SafeFileHandle handle, FileAccess access) { @@ -45,7 +42,6 @@ internal OSFileStreamStrategy(string path, FileMode mode, FileAccess access, Fil string fullPath = Path.GetFullPath(path); _access = access; - _lengthCanBeCached = (share & FileShare.Write) == 0 && (access & FileAccess.Write) == 0; _fileHandle = SafeFileHandle.Open(fullPath, mode, access, share, options, preallocationSize); @@ -78,34 +74,13 @@ internal OSFileStreamStrategy(string path, FileMode mode, FileAccess access, Fil public sealed override bool CanWrite => !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; - public unsafe sealed override long Length - { - get - { - if (!LengthCachingSupported) - { - return RandomAccess.GetFileLength(_fileHandle); - } - - // On Windows, when the file is locked for writes we can cache file length - // in memory and avoid subsequent native calls which are expensive. - - if (_length < 0) - { - _length = RandomAccess.GetFileLength(_fileHandle); - } - - return _length; - } - } + public unsafe sealed override long Length => _fileHandle.GetFileLength(); // in case of concurrent incomplete reads, there can be multiple threads trying to update the position // at the same time. That is why we are using Interlocked here. internal void OnIncompleteOperation(int expectedBytesTransferred, int actualBytesTransferred) => Interlocked.Add(ref _filePosition, actualBytesTransferred - expectedBytesTransferred); - private bool LengthCachingSupported => OperatingSystem.IsWindows() && _lengthCanBeCached; - /// Gets or sets the position within the current stream public sealed override long Position { @@ -129,9 +104,6 @@ internal sealed override SafeFileHandle SafeFileHandle FileStreamHelpers.Seek(_fileHandle, _filePosition, SeekOrigin.Begin); } - _lengthCanBeCached = false; - _length = -1; // invalidate cached length - return _fileHandle; } } @@ -224,10 +196,7 @@ protected unsafe void SetLengthCore(long value) Debug.Assert(value >= 0, "value >= 0"); FileStreamHelpers.SetFileLength(_fileHandle, value); - if (LengthCachingSupported) - { - _length = value; - } + Debug.Assert(!_fileHandle.LengthCanBeCached, "If length can be cached (file opened for reading, not shared for writing), it should be impossible to modify file length"); if (_filePosition > value) { @@ -314,7 +283,7 @@ public sealed override ValueTask ReadAsync(Memory destination, Cancel return RandomAccess.ReadAtOffsetAsync(_fileHandle, destination, fileOffset: -1, cancellationToken); } - if (LengthCachingSupported && _length >= 0 && Volatile.Read(ref _filePosition) >= _length) + if (_fileHandle.HasCachedFileLength && Volatile.Read(ref _filePosition) >= _fileHandle.GetFileLength()) { // We know for sure that the file length can be safely cached and it has already been obtained. // If we have reached EOF we just return here and avoid a sys-call. diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs index c116c17e69ad8..47b190dde4b49 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs @@ -46,7 +46,7 @@ public class UnmanagedMemoryStream : Stream private long _offset; private FileAccess _access; private bool _isOpen; - private Task? _lastReadTask; // The last successful task returned from ReadAsync + private CachedCompletedInt32Task _lastReadTask; // The last successful task returned from ReadAsync /// /// Creates a closed stream. @@ -437,12 +437,11 @@ public override Task ReadAsync(byte[] buffer, int offset, int count, Cancel try { int n = Read(buffer, offset, count); - Task? t = _lastReadTask; - return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult(n)); + return _lastReadTask.GetTask(n); } catch (Exception ex) { - Debug.Assert(!(ex is OperationCanceledException)); + Debug.Assert(ex is not OperationCanceledException); return Task.FromException(ex); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Math.cs b/src/libraries/System.Private.CoreLib/src/System/Math.cs index f242b825fb170..a929322173585 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Math.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Math.cs @@ -49,9 +49,9 @@ public static partial class Math private const double SCALEB_C3 = 9007199254740992; // 0x1p53 - private const int ILogB_NaN = 0x7fffffff; + private const int ILogB_NaN = 0x7FFFFFFF; - private const int ILogB_Zero = (-1 - 0x7fffffff); + private const int ILogB_Zero = (-1 - 0x7FFFFFFF); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short Abs(short value) @@ -133,6 +133,26 @@ public static decimal Abs(decimal value) return decimal.Abs(value); } + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static double Abs(double value) + { + const ulong mask = 0x7FFFFFFFFFFFFFFF; + ulong raw = BitConverter.DoubleToUInt64Bits(value); + + return BitConverter.UInt64BitsToDouble(raw & mask); + } + + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float Abs(float value) + { + const uint mask = 0x7FFFFFFF; + uint raw = BitConverter.SingleToUInt32Bits(value); + + return BitConverter.UInt32BitsToSingle(raw & mask); + } + [DoesNotReturn] [StackTraceHidden] private static void ThrowAbsOverflow() diff --git a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs index d3c0039fbef62..b49dea6f3638a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs @@ -281,13 +281,13 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length); if (Unsafe.SizeOf() == sizeof(int)) - return -1 != SpanHelpers.IndexOfValueType( + return 0 <= SpanHelpers.IndexOfValueType( ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); if (Unsafe.SizeOf() == sizeof(long)) - return -1 != SpanHelpers.IndexOfValueType( + return 0 <= SpanHelpers.IndexOfValueType( ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); @@ -320,13 +320,13 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length); if (Unsafe.SizeOf() == sizeof(int)) - return -1 != SpanHelpers.IndexOfValueType( + return 0 <= SpanHelpers.IndexOfValueType( ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); if (Unsafe.SizeOf() == sizeof(long)) - return -1 != SpanHelpers.IndexOfValueType( + return 0 <= SpanHelpers.IndexOfValueType( ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); @@ -755,56 +755,55 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), if (Unsafe.SizeOf() == sizeof(char)) { + ref char spanRef = ref Unsafe.As(ref MemoryMarshal.GetReference(span)); ref char valueRef = ref Unsafe.As(ref MemoryMarshal.GetReference(values)); - if (values.Length == 5) + switch (values.Length) { - // Length 5 is a common length for FileSystemName expression (", <, >, *, ?) and in preference to 2 as it has an explicit overload - return SpanHelpers.IndexOfAny( - ref Unsafe.As(ref MemoryMarshal.GetReference(span)), - valueRef, - Unsafe.Add(ref valueRef, 1), - Unsafe.Add(ref valueRef, 2), - Unsafe.Add(ref valueRef, 3), - Unsafe.Add(ref valueRef, 4), - span.Length); - } - else if (values.Length == 2) - { - // Length 2 is a common length for simple wildcards (*, ?), directory separators (/, \), quotes (", '), brackets, etc - return SpanHelpers.IndexOfAny( - ref Unsafe.As(ref MemoryMarshal.GetReference(span)), - valueRef, - Unsafe.Add(ref valueRef, 1), - span.Length); - } - else if (values.Length == 4) - { - // Length 4 before 3 as 3 has an explicit overload - return SpanHelpers.IndexOfAny( - ref Unsafe.As(ref MemoryMarshal.GetReference(span)), - valueRef, - Unsafe.Add(ref valueRef, 1), - Unsafe.Add(ref valueRef, 2), - Unsafe.Add(ref valueRef, 3), - span.Length); - } - else if (values.Length == 3) - { - return SpanHelpers.IndexOfAny( - ref Unsafe.As(ref MemoryMarshal.GetReference(span)), - valueRef, - Unsafe.Add(ref valueRef, 1), - Unsafe.Add(ref valueRef, 2), - span.Length); - } - else if (values.Length == 1) - { - // Length 1 last, as ctoring a ReadOnlySpan to call this overload for a single value - // is already throwing away a bunch of performance vs just calling IndexOf - return SpanHelpers.IndexOf( - ref Unsafe.As(ref MemoryMarshal.GetReference(span)), - valueRef, - span.Length); + case 0: + return -1; + + case 1: + return SpanHelpers.IndexOf( + ref spanRef, + valueRef, + span.Length); + + case 2: + return SpanHelpers.IndexOfAny( + ref spanRef, + valueRef, + Unsafe.Add(ref valueRef, 1), + span.Length); + + case 3: + return SpanHelpers.IndexOfAny( + ref spanRef, + valueRef, + Unsafe.Add(ref valueRef, 1), + Unsafe.Add(ref valueRef, 2), + span.Length); + + case 4: + return SpanHelpers.IndexOfAny( + ref spanRef, + valueRef, + Unsafe.Add(ref valueRef, 1), + Unsafe.Add(ref valueRef, 2), + Unsafe.Add(ref valueRef, 3), + span.Length); + + case 5: + return SpanHelpers.IndexOfAny( + ref spanRef, + valueRef, + Unsafe.Add(ref valueRef, 1), + Unsafe.Add(ref valueRef, 2), + Unsafe.Add(ref valueRef, 3), + Unsafe.Add(ref valueRef, 4), + span.Length); + + default: + return IndexOfAnyProbabilistic(ref spanRef, span.Length, ref valueRef, values.Length); } } } @@ -812,6 +811,36 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), return SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } + /// Searches for the first index of any of the specified values using a . + private static unsafe int IndexOfAnyProbabilistic(ref char searchSpace, int searchSpaceLength, ref char values, int valuesLength) + { + Debug.Assert(searchSpaceLength >= 0); + Debug.Assert(valuesLength >= 0); + + ReadOnlySpan valuesSpan = new ReadOnlySpan(ref values, valuesLength); + ProbabilisticMap map = default; + + uint* charMap = (uint*)↦ + ProbabilisticMap.Initialize(charMap, valuesSpan); + + ref char cur = ref searchSpace; + while (searchSpaceLength != 0) + { + int ch = cur; + if (ProbabilisticMap.IsCharBitSet(charMap, (byte)ch) && + ProbabilisticMap.IsCharBitSet(charMap, (byte)(ch >> 8)) && + ProbabilisticMap.SpanContains(valuesSpan, (char)ch)) + { + return (int)((nint)Unsafe.ByteOffset(ref searchSpace, ref cur) / sizeof(char)); + } + + searchSpaceLength--; + cur = ref Unsafe.Add(ref cur, 1); + } + + return -1; + } + /// /// Searches for the last index of any of the specified values similar to calling LastIndexOf several times with the logical OR operator. If not found, returns -1. /// @@ -918,9 +947,67 @@ ref Unsafe.As(ref MemoryMarshal.GetReference(span)), [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this ReadOnlySpan span, ReadOnlySpan values) where T : IEquatable { + if (RuntimeHelpers.IsBitwiseEquatable()) + { + if (Unsafe.SizeOf() == sizeof(char)) + { + switch (values.Length) + { + case 0: + return -1; + + case 1: + return LastIndexOf(span, values[0]); + + case 2: + return LastIndexOfAny(span, values[0], values[1]); + + case 3: + return LastIndexOfAny(span, values[0], values[1], values[2]); + + default: + return LastIndexOfAnyProbabilistic( + ref Unsafe.As(ref MemoryMarshal.GetReference(span)), + span.Length, + ref Unsafe.As(ref MemoryMarshal.GetReference(values)), + values.Length); + } + } + } + return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } + /// Searches for the last index of any of the specified values using a . + private static unsafe int LastIndexOfAnyProbabilistic(ref char searchSpace, int searchSpaceLength, ref char values, int valuesLength) + { + Debug.Assert(searchSpaceLength >= 0); + Debug.Assert(valuesLength >= 0); + + var valuesSpan = new ReadOnlySpan(ref values, valuesLength); + ProbabilisticMap map = default; + + uint* charMap = (uint*)↦ + ProbabilisticMap.Initialize(charMap, valuesSpan); + + ref char cur = ref Unsafe.Add(ref searchSpace, searchSpaceLength - 1); + while (searchSpaceLength != 0) + { + int ch = cur; + if (ProbabilisticMap.IsCharBitSet(charMap, (byte)ch) && + ProbabilisticMap.IsCharBitSet(charMap, (byte)(ch >> 8)) && + ProbabilisticMap.SpanContains(valuesSpan, (char)ch)) + { + return (int)((nint)Unsafe.ByteOffset(ref searchSpace, ref cur) / sizeof(char)); + } + + searchSpaceLength--; + cur = ref Unsafe.Add(ref cur, -1); + } + + return -1; + } + /// /// Determines whether two sequences are equal by comparing the elements using IEquatable{T}.Equals(T). /// diff --git a/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs b/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs index ca06d6c6e9b27..f5b55e491352e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Net/WebUtility.cs @@ -42,7 +42,7 @@ public static class WebUtility // Don't create ValueStringBuilder if we don't have anything to encode int index = IndexOfHtmlEncodingChars(valueSpan); - if (index == -1) + if (index < 0) { return value; } @@ -78,7 +78,7 @@ public static void HtmlEncode(string? value, TextWriter output) // Don't create ValueStringBuilder if we don't have anything to encode int index = IndexOfHtmlEncodingChars(valueSpan); - if (index == -1) + if (index < 0) { output.Write(value); return; @@ -188,7 +188,7 @@ private static void HtmlEncode(ReadOnlySpan input, ref ValueStringBuilder ReadOnlySpan valueSpan = value.AsSpan(); int index = IndexOfHtmlDecodingChars(valueSpan); - if (index == -1) + if (index < 0) { return value; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix3x2.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix3x2.cs index 6f25a12981031..7c9120de9d1be 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix3x2.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix3x2.cs @@ -77,7 +77,7 @@ public static Matrix3x2 Identity if ((uint)row >= 3) ThrowHelper.ThrowArgumentOutOfRangeException(); - var vrow = Unsafe.Add(ref Unsafe.As(ref M11), row); + Vector2 vrow = Unsafe.Add(ref Unsafe.As(ref M11), row); return vrow[column]; } set @@ -85,7 +85,7 @@ public static Matrix3x2 Identity if ((uint)row >= 3) ThrowHelper.ThrowArgumentOutOfRangeException(); - ref var vrow = ref Unsafe.Add(ref Unsafe.As(ref M11), row); + ref Vector2 vrow = ref Unsafe.Add(ref Unsafe.As(ref M11), row); var tmp = Vector2.WithElement(vrow, column, value); vrow = tmp; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix4x4.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix4x4.cs index 39a379af997a7..30b2e4e013f88 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix4x4.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Matrix4x4.cs @@ -161,7 +161,7 @@ public static Matrix4x4 Identity if ((uint)row >= 4) ThrowHelper.ThrowArgumentOutOfRangeException(); - var vrow = Unsafe.Add(ref Unsafe.As(ref M11), row); + Vector4 vrow = Unsafe.Add(ref Unsafe.As(ref M11), row); return vrow[column]; } set @@ -169,7 +169,7 @@ public static Matrix4x4 Identity if ((uint)row >= 4) ThrowHelper.ThrowArgumentOutOfRangeException(); - ref var vrow = ref Unsafe.Add(ref Unsafe.As(ref M11), row); + ref Vector4 vrow = ref Unsafe.Add(ref Unsafe.As(ref M11), row); var tmp = Vector4.WithElement(vrow, column, value); vrow = tmp; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Quaternion.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Quaternion.cs index 7ed2d7bb098fb..125de94f17722 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Quaternion.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Quaternion.cs @@ -88,8 +88,7 @@ internal static float GetElement(Quaternion quaternion, int index) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } - var result = quaternion; - return GetElementUnsafe(ref result, index); + return GetElementUnsafe(ref quaternion, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -112,7 +111,7 @@ internal static Quaternion WithElement(Quaternion quaternion, int index, float v ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } - var result = quaternion; + Quaternion result = quaternion; SetElementUnsafe(ref result, index, value); return result; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs index 86ad06f841e37..667ec0740b278 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs @@ -63,7 +63,7 @@ static Vector SoftwareFallback(Vector value) for (int index = 0; index < Vector.Count; index++) { - var element = Scalar.Abs(value.GetElementUnsafe(index)); + T element = Scalar.Abs(value.GetElementUnsafe(index)); result.SetElementUnsafe(index, element); } @@ -251,7 +251,7 @@ public static Vector Ceiling(Vector value) for (int index = 0; index < Vector.Count; index++) { - var element = Scalar.Ceiling(value.GetElementUnsafe(index)); + double element = Scalar.Ceiling(value.GetElementUnsafe(index)); result.SetElementUnsafe(index, element); } @@ -270,7 +270,7 @@ public static Vector Ceiling(Vector value) for (int index = 0; index < Vector.Count; index++) { - var element = Scalar.Ceiling(value.GetElementUnsafe(index)); + float element = Scalar.Ceiling(value.GetElementUnsafe(index)); result.SetElementUnsafe(index, element); } @@ -357,7 +357,7 @@ public static unsafe Vector ConvertToInt32(Vector value) for (int i = 0; i < Vector.Count; i++) { - var element = (int)value.GetElementUnsafe(i); + int element = (int)value.GetElementUnsafe(i); result.SetElementUnsafe(i, element); } @@ -374,7 +374,7 @@ public static unsafe Vector ConvertToInt64(Vector value) for (int i = 0; i < Vector.Count; i++) { - var element = (long)value.GetElementUnsafe(i); + long element = (long)value.GetElementUnsafe(i); result.SetElementUnsafe(i, element); } @@ -391,7 +391,7 @@ public static unsafe Vector ConvertToSingle(Vector value) for (int i = 0; i < Vector.Count; i++) { - var element = (float)value.GetElementUnsafe(i); + float element = value.GetElementUnsafe(i); result.SetElementUnsafe(i, element); } @@ -429,7 +429,7 @@ public static unsafe Vector ConvertToUInt32(Vector value) for (int i = 0; i < Vector.Count; i++) { - var element = (uint)value.GetElementUnsafe(i); + uint element = (uint)value.GetElementUnsafe(i); result.SetElementUnsafe(i, element); } @@ -447,7 +447,7 @@ public static unsafe Vector ConvertToUInt64(Vector value) for (int i = 0; i < Vector.Count; i++) { - var element = (ulong)value.GetElementUnsafe(i); + ulong element = (ulong)value.GetElementUnsafe(i); result.SetElementUnsafe(i, element); } @@ -477,7 +477,7 @@ public static T Dot(Vector left, Vector right) for (int index = 0; index < Vector.Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result = Scalar.Add(result, value); } @@ -498,7 +498,7 @@ public static Vector Equals(Vector left, Vector right) for (int index = 0; index < Vector.Count; index++) { - var value = Scalar.Equals(left.GetElementUnsafe(index), right.GetElementUnsafe(index)) ? Scalar.AllBitsSet : default; + T value = Scalar.Equals(left.GetElementUnsafe(index), right.GetElementUnsafe(index)) ? Scalar.AllBitsSet : default; result.SetElementUnsafe(index, value); } @@ -572,7 +572,7 @@ public static Vector Floor(Vector value) for (int index = 0; index < Vector.Count; index++) { - var element = Scalar.Floor(value.GetElementUnsafe(index)); + double element = Scalar.Floor(value.GetElementUnsafe(index)); result.SetElementUnsafe(index, element); } @@ -591,7 +591,7 @@ public static Vector Floor(Vector value) for (int index = 0; index < Vector.Count; index++) { - var element = Scalar.Floor(value.GetElementUnsafe(index)); + float element = Scalar.Floor(value.GetElementUnsafe(index)); result.SetElementUnsafe(index, element); } @@ -977,13 +977,13 @@ public static unsafe Vector Narrow(Vector low, Vector hig for (int i = 0; i < Vector.Count; i++) { - var value = (float)low.GetElementUnsafe(i); + float value = (float)low.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (float)high.GetElementUnsafe(i - Vector.Count); + float value = (float)high.GetElementUnsafe(i - Vector.Count); result.SetElementUnsafe(i, value); } @@ -1002,13 +1002,13 @@ public static unsafe Vector Narrow(Vector low, Vector high) for (int i = 0; i < Vector.Count; i++) { - var value = (sbyte)low.GetElementUnsafe(i); + sbyte value = (sbyte)low.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (sbyte)high.GetElementUnsafe(i - Vector.Count); + sbyte value = (sbyte)high.GetElementUnsafe(i - Vector.Count); result.SetElementUnsafe(i, value); } @@ -1026,13 +1026,13 @@ public static unsafe Vector Narrow(Vector low, Vector high) for (int i = 0; i < Vector.Count; i++) { - var value = (short)low.GetElementUnsafe(i); + short value = (short)low.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (short)high.GetElementUnsafe(i - Vector.Count); + short value = (short)high.GetElementUnsafe(i - Vector.Count); result.SetElementUnsafe(i, value); } @@ -1050,13 +1050,13 @@ public static unsafe Vector Narrow(Vector low, Vector high) for (int i = 0; i < Vector.Count; i++) { - var value = (int)low.GetElementUnsafe(i); + int value = (int)low.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (int)high.GetElementUnsafe(i - Vector.Count); + int value = (int)high.GetElementUnsafe(i - Vector.Count); result.SetElementUnsafe(i, value); } @@ -1075,13 +1075,13 @@ public static unsafe Vector Narrow(Vector low, Vector high for (int i = 0; i < Vector.Count; i++) { - var value = (byte)low.GetElementUnsafe(i); + byte value = (byte)low.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (byte)high.GetElementUnsafe(i - Vector.Count); + byte value = (byte)high.GetElementUnsafe(i - Vector.Count); result.SetElementUnsafe(i, value); } @@ -1100,13 +1100,13 @@ public static unsafe Vector Narrow(Vector low, Vector high) for (int i = 0; i < Vector.Count; i++) { - var value = (ushort)low.GetElementUnsafe(i); + ushort value = (ushort)low.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (ushort)high.GetElementUnsafe(i - Vector.Count); + ushort value = (ushort)high.GetElementUnsafe(i - Vector.Count); result.SetElementUnsafe(i, value); } @@ -1125,13 +1125,13 @@ public static unsafe Vector Narrow(Vector low, Vector high) for (int i = 0; i < Vector.Count; i++) { - var value = (uint)low.GetElementUnsafe(i); + uint value = (uint)low.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (uint)high.GetElementUnsafe(i - Vector.Count); + uint value = (uint)high.GetElementUnsafe(i - Vector.Count); result.SetElementUnsafe(i, value); } @@ -1154,6 +1154,492 @@ public static Vector Negate(Vector value) public static Vector OnesComplement(Vector value) where T : struct => ~value; + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + byte element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + short element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + int element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + long element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + nint element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + nuint element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + sbyte element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + ushort element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + uint element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftLeft(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + ulong element = Scalar.ShiftLeft(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightArithmetic(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + short element = Scalar.ShiftRightArithmetic(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightArithmetic(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + int element = Scalar.ShiftRightArithmetic(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightArithmetic(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + long element = Scalar.ShiftRightArithmetic(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightArithmetic(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + nint element = Scalar.ShiftRightArithmetic(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightArithmetic(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + sbyte element = Scalar.ShiftRightArithmetic(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + byte element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + short element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + int element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + long element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + nint element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + nuint element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + sbyte element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + ushort element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + uint element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector ShiftRightLogical(Vector value, int shiftCount) + { + Unsafe.SkipInit(out Vector result); + + for (int index = 0; index < Vector.Count; index++) + { + ulong element = Scalar.ShiftRightLogical(value.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + /// Computes the square root of a vector on a per-element basis. /// The vector whose square root is to be computed. /// The type of the elements in the vector. @@ -1167,7 +1653,7 @@ public static Vector SquareRoot(Vector value) for (int index = 0; index < Vector.Count; index++) { - var element = Scalar.Sqrt(value.GetElementUnsafe(index)); + T element = Scalar.Sqrt(value.GetElementUnsafe(index)); result.SetElementUnsafe(index, element); } @@ -1290,7 +1776,7 @@ internal static Vector WidenLower(Vector source) for (int i = 0; i < Vector.Count; i++) { - var value = (ushort)source.GetElementUnsafe(i); + ushort value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -1304,7 +1790,7 @@ internal static unsafe Vector WidenLower(Vector source) for (int i = 0; i < Vector.Count; i++) { - var value = (int)source.GetElementUnsafe(i); + int value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -1318,7 +1804,7 @@ internal static unsafe Vector WidenLower(Vector source) for (int i = 0; i < Vector.Count; i++) { - var value = (long)source.GetElementUnsafe(i); + long value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -1332,7 +1818,7 @@ internal static unsafe Vector WidenLower(Vector source) for (int i = 0; i < Vector.Count; i++) { - var value = (short)source.GetElementUnsafe(i); + short value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -1346,7 +1832,7 @@ internal static unsafe Vector WidenLower(Vector source) for (int i = 0; i < Vector.Count; i++) { - var value = (double)source.GetElementUnsafe(i); + double value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -1360,7 +1846,7 @@ internal static unsafe Vector WidenLower(Vector source) for (int i = 0; i < Vector.Count; i++) { - var value = (uint)source.GetElementUnsafe(i); + uint value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -1374,7 +1860,7 @@ internal static unsafe Vector WidenLower(Vector source) for (int i = 0; i < Vector.Count; i++) { - var value = (ulong)source.GetElementUnsafe(i); + ulong value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -1388,7 +1874,7 @@ internal static Vector WidenUpper(Vector source) for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (ushort)source.GetElementUnsafe(i); + ushort value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector.Count, value); } @@ -1402,7 +1888,7 @@ internal static unsafe Vector WidenUpper(Vector source) for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (int)source.GetElementUnsafe(i); + int value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector.Count, value); } @@ -1416,7 +1902,7 @@ internal static unsafe Vector WidenUpper(Vector source) for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (long)source.GetElementUnsafe(i); + long value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector.Count, value); } @@ -1430,7 +1916,7 @@ internal static unsafe Vector WidenUpper(Vector source) for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (short)source.GetElementUnsafe(i); + short value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector.Count, value); } @@ -1444,7 +1930,7 @@ internal static unsafe Vector WidenUpper(Vector source) for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (double)source.GetElementUnsafe(i); + double value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector.Count, value); } @@ -1458,7 +1944,7 @@ internal static unsafe Vector WidenUpper(Vector source) for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (uint)source.GetElementUnsafe(i); + uint value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector.Count, value); } @@ -1472,7 +1958,7 @@ internal static unsafe Vector WidenUpper(Vector source) for (int i = Vector.Count; i < Vector.Count; i++) { - var value = (ulong)source.GetElementUnsafe(i); + ulong value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector.Count, value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector2.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector2.cs index 7c1dc8312bd08..ea463e9c09d17 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector2.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector2.cs @@ -105,8 +105,7 @@ internal static float GetElement(Vector2 vector, int index) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } - var result = vector; - return GetElementUnsafe(ref result, index); + return GetElementUnsafe(ref vector, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -129,9 +128,9 @@ internal static Vector2 WithElement(Vector2 vector, int index, float value) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } - var newVector = vector; - SetElementUnsafe(ref newVector, index, value); - return newVector; + Vector2 result = vector; + SetElementUnsafe(ref result, index, value); + return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector3.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector3.cs index 8debbc0b27c31..6bee6d783e0f6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector3.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector3.cs @@ -125,8 +125,7 @@ internal static float GetElement(Vector3 vector, int index) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } - var result = vector; - return GetElementUnsafe(ref result, index); + return GetElementUnsafe(ref vector, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -149,9 +148,9 @@ internal static Vector3 WithElement(Vector3 vector, int index, float value) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } - var newVector = vector; - SetElementUnsafe(ref newVector, index, value); - return newVector; + Vector3 result = vector; + SetElementUnsafe(ref result, index, value); + return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector4.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector4.cs index 5e00892bf9c89..246a3abe60178 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector4.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector4.cs @@ -6,7 +6,6 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Intrinsics; using System.Text; using Internal.Runtime.CompilerServices; @@ -148,8 +147,7 @@ internal static float GetElement(Vector4 vector, int index) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } - var result = vector; - return GetElementUnsafe(ref result, index); + return GetElementUnsafe(ref vector, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -172,9 +170,9 @@ internal static Vector4 WithElement(Vector4 vector, int index, float value) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } - var newVector = vector; - SetElementUnsafe(ref newVector, index, value); - return newVector; + Vector4 result = vector; + SetElementUnsafe(ref result, index, value); + return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector_1.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector_1.cs index bb446c55b3585..756e6314bcd84 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector_1.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector_1.cs @@ -237,7 +237,7 @@ public unsafe T this[int index] for (int index = 0; index < Count; index++) { - var value = Scalar.Add(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Add(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -287,7 +287,7 @@ public unsafe T this[int index] for (int index = 0; index < Count; index++) { - var value = Scalar.Divide(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Divide(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -449,7 +449,7 @@ public static explicit operator Vector(Vector value) for (int index = 0; index < Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -467,7 +467,7 @@ public static explicit operator Vector(Vector value) for (int index = 0; index < Count; index++) { - var element = Scalar.Multiply(value.GetElementUnsafe(index), factor); + T element = Scalar.Multiply(value.GetElementUnsafe(index), factor); result.SetElementUnsafe(index, element); } @@ -500,7 +500,7 @@ public static explicit operator Vector(Vector value) for (int index = 0; index < Count; index++) { - var value = Scalar.Subtract(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Subtract(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -601,7 +601,7 @@ public override int GetHashCode() for (int index = 0; index < Count; index++) { - var value = this.GetElementUnsafe(index); + T value = this.GetElementUnsafe(index); hashCode.Add(value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/ProbabilisticMap.cs b/src/libraries/System.Private.CoreLib/src/System/ProbabilisticMap.cs new file mode 100644 index 0000000000000..b3f4a30a63529 --- /dev/null +++ b/src/libraries/System.Private.CoreLib/src/System/ProbabilisticMap.cs @@ -0,0 +1,94 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System +{ + /// Data structure used to optimize checks for whether a char is in a set of chars. + /// + /// Like a Bloom filter, the idea is to create a bit map of the characters we are + /// searching for and use this map as a "cheap" check to decide if the current + /// character in the string exists in the array of input characters. There are + /// 256 bits in the map, with each character mapped to 2 bits. Every character is + /// divided into 2 bytes, and then every byte is mapped to 1 bit. The character map + /// is an array of 8 integers acting as map blocks. The 3 lsb in each byte in the + /// character is used to index into this map to get the right block, the value of + /// the remaining 5 msb are used as the bit position inside this block. + /// + [StructLayout(LayoutKind.Explicit, Size = Size * sizeof(uint))] + internal struct ProbabilisticMap + { + private const int Size = 0x8; + private const int IndexMask = 0x7; + private const int IndexShift = 0x3; + + /// Initializes the map based on the specified values. + /// A pointer to the beginning of a . + /// The values to set in the map. + public static unsafe void Initialize(uint* charMap, ReadOnlySpan values) + { +#if DEBUG + for (int i = 0; i < Size; i++) + { + Debug.Assert(charMap[i] == 0, "Expected charMap to be zero-initialized."); + } +#endif + bool hasAscii = false; + uint* charMapLocal = charMap; // https://github.com/dotnet/runtime/issues/9040 + + for (int i = 0; i < values.Length; ++i) + { + int c = values[i]; + + // Map low bit + SetCharBit(charMapLocal, (byte)c); + + // Map high bit + c >>= 8; + + if (c == 0) + { + hasAscii = true; + } + else + { + SetCharBit(charMapLocal, (byte)c); + } + } + + if (hasAscii) + { + // Common to search for ASCII symbols. Just set the high value once. + charMapLocal[0] |= 1u; + } + } + + public static unsafe bool IsCharBitSet(uint* charMap, byte value) => + (charMap[(uint)value & IndexMask] & (1u << (value >> IndexShift))) != 0; + + private static unsafe void SetCharBit(uint* charMap, byte value) => + charMap[(uint)value & IndexMask] |= 1u << (value >> IndexShift); + + /// Determines whether is in . + /// + /// could be used, but it's optimized + /// for longer spans, whereas typical usage here expects a relatively small number of items in the span. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool SpanContains(ReadOnlySpan span, char searchChar) + { + for (int i = 0; i < span.Length; i++) + { + if (span[i] == searchChar) + { + return true; + } + } + + return false; + } + } +} diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs index b09bb83a5a687..b58e03aeb6e44 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs @@ -341,10 +341,13 @@ private NotAnnotatedStatus PopulateAnnotationInfo(IList cus return NotAnnotatedStatus.None; } - private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, IList customAttributes) => - GetNullabilityInfo(memberInfo, type, customAttributes, 0); + private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, IList customAttributes) + { + int index = 0; + return GetNullabilityInfo(memberInfo, type, customAttributes, ref index); + } - private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, IList customAttributes, int index) + private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, IList customAttributes, ref int index) { NullabilityState state = NullabilityState.Unknown; NullabilityInfo? elementState = null; @@ -364,17 +367,22 @@ private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, ILi underlyingType = type; state = NullabilityState.NotNull; } + + if (underlyingType.IsGenericType) + { + index++; + } } else { - if (!ParseNullableState(customAttributes, index, ref state)) + if (!ParseNullableState(customAttributes, index++, ref state)) { state = GetNullableContext(memberInfo); } if (type.IsArray) { - elementState = GetNullabilityInfo(memberInfo, type.GetElementType()!, customAttributes, index + 1); + elementState = GetNullabilityInfo(memberInfo, type.GetElementType()!, customAttributes, ref index); } } @@ -383,16 +391,9 @@ private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, ILi Type[] genericArguments = underlyingType.GetGenericArguments(); genericArgumentsState = new NullabilityInfo[genericArguments.Length]; - for (int i = 0, offset = 0; i < genericArguments.Length; i++) + for (int i = 0; i < genericArguments.Length; i++) { - Type t = Nullable.GetUnderlyingType(genericArguments[i]) ?? genericArguments[i]; - - if (!t.IsValueType || t.IsGenericType) - { - offset++; - } - - genericArgumentsState[i] = GetNullabilityInfo(memberInfo, genericArguments[i], customAttributes, index + offset); + genericArgumentsState[i] = GetNullabilityInfo(memberInfo, genericArguments[i], customAttributes, ref index); } } @@ -500,7 +501,8 @@ private void CheckGenericParameters(NullabilityInfo nullability, MemberInfo meta { if (genericArguments[i].IsGenericParameter) { - NullabilityInfo n = GetNullabilityInfo(metaMember, genericArguments[i], genericArguments[i].GetCustomAttributesData(), i + 1); + int index = i + 1; + NullabilityInfo n = GetNullabilityInfo(metaMember, genericArguments[i], genericArguments[i].GetCustomAttributesData(), ref index); nullability.GenericTypeArguments[i].ReadState = n.ReadState; nullability.GenericTypeArguments[i].WriteState = n.WriteState; } @@ -523,7 +525,8 @@ private void UpdateGenericArrayElements(NullabilityInfo? elementState, MemberInf && metaType.GetElementType()!.IsGenericParameter) { Type elementType = metaType.GetElementType()!; - NullabilityInfo n = GetNullabilityInfo(metaMember, elementType, elementType.GetCustomAttributesData(), 0); + int index = 0; + NullabilityInfo n = GetNullabilityInfo(metaMember, elementType, elementType.GetCustomAttributesData(), ref index); elementState.ReadState = n.ReadState; elementState.WriteState = n.WriteState; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs index 328baf6150a28..e928bcd21ea59 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -566,7 +566,7 @@ internal static bool IsDefaultType(string asmTypeName, // First, compare type names int comma = asmTypeName.IndexOf(','); - if (((comma == -1) ? asmTypeName.Length : comma) != typeName.Length) + if (((comma < 0) ? asmTypeName.Length : comma) != typeName.Length) return false; // case sensitive diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index 8187320ec9768..498055ad6a1c5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -117,5 +117,15 @@ internal static bool IsPrimitiveType(this CorElementType et) /// This method is intended for compiler use rather than use directly in code. T must be one of byte, sbyte, char, short, ushort, int, long, ulong, float, or double. [Intrinsic] public static unsafe ReadOnlySpan CreateSpan(RuntimeFieldHandle fldHandle) => new ReadOnlySpan(GetSpanDataFrom(fldHandle, typeof(T).TypeHandle, out int length), length); + + + // The following intrinsics return true if input is a compile-time constant + // Feel free to add more overloads on demand + + [Intrinsic] + internal static bool IsKnownConstant(string? t) => false; + + [Intrinsic] + internal static bool IsKnownConstant(char t) => false; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/RuntimeInformation.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/RuntimeInformation.cs index 6e892ce520482..46f80f2dfc16d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/RuntimeInformation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/RuntimeInformation.cs @@ -21,7 +21,7 @@ public static string FrameworkDescription // Strip the git hash if there is one int plusIndex = versionString.IndexOf('+'); - if (plusIndex != -1) + if (plusIndex >= 0) { versionString = versionString.Slice(0, plusIndex); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs index 3e7f204573ca0..7fe55f25b34d6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/SafeBuffer.cs @@ -153,7 +153,9 @@ public void AcquirePointer(ref byte* pointer) if (_numBytes == Uninitialized) throw NotInitialized(); +#pragma warning disable IDE0059 // https://github.com/dotnet/roslyn/issues/42761 pointer = null; +#pragma warning restore IDE0059 bool junk = false; DangerousAddRef(ref junk); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Scalar.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Scalar.cs index db5d684f5e692..b7a5ba890c1a1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Scalar.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Scalar.cs @@ -355,6 +355,85 @@ public static bool Equals(T left, T right) } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint ExtractMostSignificantBit(T value) + { + if (typeof(T) == typeof(byte)) + { + uint bits = (byte)(object)value; + return bits >> 7; + } + else if (typeof(T) == typeof(double)) + { + ulong bits = BitConverter.DoubleToUInt64Bits((double)(object)value); + return (uint)(bits >> 63); + } + else if (typeof(T) == typeof(short)) + { + uint bits = (ushort)(short)(object)value; + return bits >> 15; + } + else if (typeof(T) == typeof(int)) + { + uint bits = (uint)(int)(object)value; + return bits >> 31; + } + else if (typeof(T) == typeof(long)) + { + ulong bits = (ulong)(long)(object)value; + return (uint)(bits >> 63); + } + else if (typeof(T) == typeof(nint)) + { +#if TARGET_64BIT + ulong bits = (ulong)(nint)(object)value; + return (uint)(bits >> 63); +#else + uint bits = (uint)(nint)(object)value; + return bits >> 31; +#endif + } + else if (typeof(T) == typeof(nuint)) + { +#if TARGET_64BIT + ulong bits = (ulong)(nuint)(object)value; + return (uint)(bits >> 63); +#else + uint bits = (uint)(nuint)(object)value; + return bits >> 31; +#endif + } + else if (typeof(T) == typeof(sbyte)) + { + uint bits = (byte)(sbyte)(object)value; + return bits >> 7; + } + else if (typeof(T) == typeof(float)) + { + uint bits = BitConverter.SingleToUInt32Bits((float)(object)value); + return bits >> 31; + } + else if (typeof(T) == typeof(ushort)) + { + uint bits = (ushort)(object)value; + return bits >> 15; + } + else if (typeof(T) == typeof(uint)) + { + uint bits = (uint)(object)value; + return bits >> 31; + } + else if (typeof(T) == typeof(ulong)) + { + ulong bits = (ulong)(object)value; + return (uint)(bits >> 63); + } + else + { + throw new NotSupportedException(SR.Arg_TypeNotSupported); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Floor(T value) { @@ -657,6 +736,133 @@ public static T Multiply(T left, T right) } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ShiftLeft(T value, int shiftCount) + { + if (typeof(T) == typeof(byte)) + { + return (T)(object)(byte)((byte)(object)value << (shiftCount & 7)); + } + else if (typeof(T) == typeof(short)) + { + return (T)(object)(short)((short)(object)value << (shiftCount & 15)); + } + else if (typeof(T) == typeof(int)) + { + return (T)(object)(int)((int)(object)value << shiftCount); + } + else if (typeof(T) == typeof(long)) + { + return (T)(object)(long)((long)(object)value << shiftCount); + } + else if (typeof(T) == typeof(nint)) + { + return (T)(object)(nint)((nint)(object)value << shiftCount); + } + else if (typeof(T) == typeof(nuint)) + { + return (T)(object)(nuint)((nuint)(object)value << shiftCount); + } + else if (typeof(T) == typeof(sbyte)) + { + return (T)(object)(sbyte)((sbyte)(object)value << (shiftCount & 7)); + } + else if (typeof(T) == typeof(ushort)) + { + return (T)(object)(ushort)((ushort)(object)value << (shiftCount & 15)); + } + else if (typeof(T) == typeof(uint)) + { + return (T)(object)(uint)((uint)(object)value << shiftCount); + } + else if (typeof(T) == typeof(ulong)) + { + return (T)(object)(ulong)((ulong)(object)value << shiftCount); + } + else + { + throw new NotSupportedException(SR.Arg_TypeNotSupported); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ShiftRightArithmetic(T value, int shiftCount) + { + if (typeof(T) == typeof(short)) + { + return (T)(object)(short)((short)(object)value >> (shiftCount & 15)); + } + else if (typeof(T) == typeof(int)) + { + return (T)(object)(int)((int)(object)value >> shiftCount); + } + else if (typeof(T) == typeof(long)) + { + return (T)(object)(long)((long)(object)value >> shiftCount); + } + else if (typeof(T) == typeof(nint)) + { + return (T)(object)(nint)((nint)(object)value >> shiftCount); + } + else if (typeof(T) == typeof(sbyte)) + { + return (T)(object)(sbyte)((sbyte)(object)value >> (shiftCount & 7)); + } + else + { + throw new NotSupportedException(SR.Arg_TypeNotSupported); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T ShiftRightLogical(T value, int shiftCount) + { + if (typeof(T) == typeof(byte)) + { + return (T)(object)(byte)((byte)(object)value >> (shiftCount & 7)); + } + else if (typeof(T) == typeof(short)) + { + return (T)(object)(short)((ushort)(short)(object)value >> (shiftCount & 15)); + } + else if (typeof(T) == typeof(int)) + { + return (T)(object)(int)((uint)(int)(object)value >> shiftCount); + } + else if (typeof(T) == typeof(long)) + { + return (T)(object)(long)((ulong)(long)(object)value >> shiftCount); + } + else if (typeof(T) == typeof(nint)) + { + return (T)(object)(nint)((nuint)(nint)(object)value >> shiftCount); + } + else if (typeof(T) == typeof(nuint)) + { + return (T)(object)(nuint)((nuint)(object)value >> shiftCount); + } + else if (typeof(T) == typeof(sbyte)) + { + return (T)(object)(sbyte)((byte)(sbyte)(object)value >> (shiftCount & 7)); + } + else if (typeof(T) == typeof(ushort)) + { + return (T)(object)(ushort)((ushort)(object)value >> (shiftCount & 15)); + } + else if (typeof(T) == typeof(uint)) + { + return (T)(object)(uint)((uint)(object)value >> shiftCount); + } + else if (typeof(T) == typeof(ulong)) + { + return (T)(object)(ulong)((ulong)(object)value >> shiftCount); + } + else + { + throw new NotSupportedException(SR.Arg_TypeNotSupported); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Sqrt(T value) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector128.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector128.cs index 1acc80f5be335..1f9b95fb73299 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector128.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector128.cs @@ -34,6 +34,12 @@ public static class Vector128 { internal const int Size = 16; +#if TARGET_ARM + internal const int Alignment = 8; +#else + internal const int Alignment = 16; +#endif + /// Gets a value that indicates whether 128-bit vector operations are subject to hardware acceleration through JIT intrinsic support. /// if 128-bit vector operations are subject to hardware acceleration; otherwise, . /// 128-bit vector operations are subject to hardware acceleration on systems that support Single Instruction, Multiple Data (SIMD) instructions for 128-bit vectors and the RyuJIT just-in-time compiler is used to compile managed code. @@ -79,7 +85,7 @@ static Vector128 SoftwareFallback(Vector128 vector) for (int index = 0; index < Vector128.Count; index++) { - var value = Scalar.Abs(vector.GetElementUnsafe(index)); + T value = Scalar.Abs(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -338,7 +344,7 @@ public static Vector128 Ceiling(Vector128 vector) for (int index = 0; index < Vector128.Count; index++) { - var value = Scalar.Ceiling(vector.GetElementUnsafe(index)); + float value = Scalar.Ceiling(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -356,7 +362,7 @@ public static Vector128 Ceiling(Vector128 vector) for (int index = 0; index < Vector128.Count; index++) { - var value = Scalar.Ceiling(vector.GetElementUnsafe(index)); + double value = Scalar.Ceiling(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -399,10 +405,10 @@ public static unsafe Vector128 ConvertToDouble(Vector128 vector) lowerBits = Sse2.Or(lowerBits, Create(0x43300000_00000000).AsInt32()); } - var upperBits = Sse2.ShiftRightLogical(vector, 32); // Extract the 32 most significant bits of vector + Vector128 upperBits = Sse2.ShiftRightLogical(vector, 32); // Extract the 32 most significant bits of vector upperBits = Sse2.Xor(upperBits, Create(0x45300000_80000000)); // Flip the msb of upperBits and blend with the bit representation of double(2^84 + 2^63) - var result = Sse2.Subtract(upperBits.AsDouble(), Create(0x45300000_80100000).AsDouble()); // Compute in double precision: (upper - (2^84 + 2^63 + 2^52)) + lower + Vector128 result = Sse2.Subtract(upperBits.AsDouble(), Create(0x45300000_80100000).AsDouble()); // Compute in double precision: (upper - (2^84 + 2^63 + 2^52)) + lower return Sse2.Add(result, lowerBits.AsDouble()); } else @@ -416,7 +422,7 @@ static Vector128 SoftwareFallback(Vector128 vector) for (int i = 0; i < Vector128.Count; i++) { - var value = (double)vector.GetElementUnsafe(i); + double value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -450,10 +456,10 @@ public static unsafe Vector128 ConvertToDouble(Vector128 vector) lowerBits = Sse2.Or(lowerBits, Create(0x43300000_00000000UL).AsUInt32()); } - var upperBits = Sse2.ShiftRightLogical(vector, 32); // Extract the 32 most significant bits of vector + Vector128 upperBits = Sse2.ShiftRightLogical(vector, 32); // Extract the 32 most significant bits of vector upperBits = Sse2.Xor(upperBits, Create(0x45300000_00000000UL)); // Blend upperBits with the bit representation of double(2^84) - var result = Sse2.Subtract(upperBits.AsDouble(), Create(0x45300000_00100000UL).AsDouble()); // Compute in double precision: (upper - (2^84 + 2^52)) + lower + Vector128 result = Sse2.Subtract(upperBits.AsDouble(), Create(0x45300000_00100000UL).AsDouble()); // Compute in double precision: (upper - (2^84 + 2^52)) + lower return Sse2.Add(result, lowerBits.AsDouble()); } else @@ -467,7 +473,7 @@ static Vector128 SoftwareFallback(Vector128 vector) for (int i = 0; i < Vector128.Count; i++) { - var value = (double)vector.GetElementUnsafe(i); + double value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -485,7 +491,7 @@ public static unsafe Vector128 ConvertToInt32(Vector128 vector) for (int i = 0; i < Vector128.Count; i++) { - var value = (int)vector.GetElementUnsafe(i); + int value = (int)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -502,7 +508,7 @@ public static unsafe Vector128 ConvertToInt64(Vector128 vector) for (int i = 0; i < Vector128.Count; i++) { - var value = (long)vector.GetElementUnsafe(i); + long value = (long)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -519,7 +525,7 @@ public static unsafe Vector128 ConvertToSingle(Vector128 vector) for (int i = 0; i < Vector128.Count; i++) { - var value = (float)vector.GetElementUnsafe(i); + float value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -541,11 +547,11 @@ public static unsafe Vector128 ConvertToSingle(Vector128 vector) // This means everything between 0 and 2^16 (ushort.MaxValue + 1) are exact and so // converting each of the upper and lower halves will give an exact result - var lowerBits = Sse2.And(vector, Create(0x0000FFFFU)).AsInt32(); - var upperBits = Sse2.ShiftRightLogical(vector, 16).AsInt32(); + Vector128 lowerBits = Sse2.And(vector, Create(0x0000FFFFU)).AsInt32(); + Vector128 upperBits = Sse2.ShiftRightLogical(vector, 16).AsInt32(); - var lower = Sse2.ConvertToVector128Single(lowerBits); - var upper = Sse2.ConvertToVector128Single(upperBits); + Vector128 lower = Sse2.ConvertToVector128Single(lowerBits); + Vector128 upper = Sse2.ConvertToVector128Single(upperBits); // This next bit of magic works because all multiples of 65536, at least up to 65535 // are likewise exactly representable @@ -560,7 +566,7 @@ public static unsafe Vector128 ConvertToSingle(Vector128 vector) } else { - var result = Sse.Multiply(upper, Vector128.Create(65536.0f)); + Vector128 result = Sse.Multiply(upper, Vector128.Create(65536.0f)); return Sse.Add(result, lower); } } @@ -575,7 +581,7 @@ static Vector128 SoftwareFallback(Vector128 vector) for (int i = 0; i < Vector128.Count; i++) { - var value = (float)vector.GetElementUnsafe(i); + float value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -594,7 +600,7 @@ public static unsafe Vector128 ConvertToUInt32(Vector128 vector) for (int i = 0; i < Vector128.Count; i++) { - var value = (uint)vector.GetElementUnsafe(i); + uint value = (uint)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -612,7 +618,7 @@ public static unsafe Vector128 ConvertToUInt64(Vector128 vector) for (int i = 0; i < Vector128.Count; i++) { - var value = (ulong)vector.GetElementUnsafe(i); + ulong value = (ulong)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -898,14 +904,11 @@ public static unsafe Vector128 Create(nint value) static Vector128 SoftwareFallback(nint value) { - if (Environment.Is64BitProcess) - { - return Create((long)value).AsNInt(); - } - else - { - return Create((int)value).AsNInt(); - } +#if TARGET_64BIT + return Create((long)value).AsNInt(); +#else + return Create((int)value).AsNInt(); +#endif } } @@ -925,14 +928,11 @@ public static unsafe Vector128 Create(nuint value) static Vector128 SoftwareFallback(nuint value) { - if (Environment.Is64BitProcess) - { - return Create((ulong)value).AsNUInt(); - } - else - { - return Create((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return Create((ulong)value).AsNUInt(); +#else + return Create((uint)value).AsNUInt(); +#endif } } @@ -1800,7 +1800,7 @@ public static unsafe Vector128 CreateScalar(byte value) static Vector128 SoftwareFallback(byte value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1826,7 +1826,7 @@ public static unsafe Vector128 CreateScalar(double value) static Vector128 SoftwareFallback(double value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1854,7 +1854,7 @@ public static unsafe Vector128 CreateScalar(short value) static Vector128 SoftwareFallback(short value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1880,7 +1880,7 @@ public static unsafe Vector128 CreateScalar(int value) static Vector128 SoftwareFallback(int value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1906,7 +1906,7 @@ public static unsafe Vector128 CreateScalar(long value) static Vector128 SoftwareFallback(long value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1918,14 +1918,11 @@ static Vector128 SoftwareFallback(long value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe Vector128 CreateScalar(nint value) { - if (Environment.Is64BitProcess) - { - return CreateScalar((long)value).AsNInt(); - } - else - { - return CreateScalar((int)value).AsNInt(); - } +#if TARGET_64BIT + return CreateScalar((long)value).AsNInt(); +#else + return CreateScalar((int)value).AsNInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements initialized to zero. @@ -1935,14 +1932,11 @@ public static unsafe Vector128 CreateScalar(nint value) [CLSCompliant(false)] public static unsafe Vector128 CreateScalar(nuint value) { - if (Environment.Is64BitProcess) - { - return CreateScalar((ulong)value).AsNUInt(); - } - else - { - return CreateScalar((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return CreateScalar((ulong)value).AsNUInt(); +#else + return CreateScalar((uint)value).AsNUInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements initialized to zero. @@ -1968,7 +1962,7 @@ public static unsafe Vector128 CreateScalar(sbyte value) static Vector128 SoftwareFallback(sbyte value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1994,7 +1988,7 @@ public static unsafe Vector128 CreateScalar(float value) static Vector128 SoftwareFallback(float value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2023,7 +2017,7 @@ public static unsafe Vector128 CreateScalar(ushort value) static Vector128 SoftwareFallback(ushort value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2050,7 +2044,7 @@ public static unsafe Vector128 CreateScalar(uint value) static Vector128 SoftwareFallback(uint value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2077,7 +2071,7 @@ public static unsafe Vector128 CreateScalar(ulong value) static Vector128 SoftwareFallback(ulong value) { - var result = Vector128.Zero; + Vector128 result = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2159,14 +2153,11 @@ public static unsafe Vector128 CreateScalarUnsafe(long value) [Intrinsic] public static unsafe Vector128 CreateScalarUnsafe(nint value) { - if (Environment.Is64BitProcess) - { - return CreateScalarUnsafe((long)value).AsNInt(); - } - else - { - return CreateScalarUnsafe((int)value).AsNInt(); - } +#if TARGET_64BIT + return CreateScalarUnsafe((long)value).AsNInt(); +#else + return CreateScalarUnsafe((int)value).AsNInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements left uninitialized. @@ -2176,14 +2167,11 @@ public static unsafe Vector128 CreateScalarUnsafe(nint value) [CLSCompliant(false)] public static unsafe Vector128 CreateScalarUnsafe(nuint value) { - if (Environment.Is64BitProcess) - { - return CreateScalarUnsafe((ulong)value).AsNUInt(); - } - else - { - return CreateScalarUnsafe((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return CreateScalarUnsafe((ulong)value).AsNUInt(); +#else + return CreateScalarUnsafe((uint)value).AsNUInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements left uninitialized. @@ -2283,7 +2271,7 @@ public static T Dot(Vector128 left, Vector128 right) for (int index = 0; index < Vector128.Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result = Scalar.Add(result, value); } @@ -2303,7 +2291,7 @@ public static Vector128 Equals(Vector128 left, Vector128 right) for (int index = 0; index < Vector128.Count; index++) { - var value = Scalar.Equals(left.GetElementUnsafe(index), right.GetElementUnsafe(index)) ? Scalar.AllBitsSet : default; + T value = Scalar.Equals(left.GetElementUnsafe(index), right.GetElementUnsafe(index)) ? Scalar.AllBitsSet : default; result.SetElementUnsafe(index, value); } @@ -2330,6 +2318,28 @@ public static bool EqualsAll(Vector128 left, Vector128 right) public static bool EqualsAny(Vector128 left, Vector128 right) where T : struct => Equals(left, right).As() != Vector128.Zero; + /// Extracts the most significant bit from each element in a vector. + /// The vector whose elements should have their most significant bit extracted. + /// The type of the elements in the vector. + /// The packed most significant bits extracted from the elements in . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint ExtractMostSignificantBits(this Vector128 vector) + where T : struct + { + uint result = 0; + + for (int index = 0; index < Vector128.Count; index++) + { + uint value = Scalar.ExtractMostSignificantBit(vector.GetElementUnsafe(index)); + value <<= index; + result |= value; + } + + return result; + } + /// Computes the floor of each element in a vector. /// The vector that will have its floor computed. /// A vector whose elements are the floor of the elements in . @@ -2341,7 +2351,7 @@ public static Vector128 Floor(Vector128 vector) for (int index = 0; index < Vector128.Count; index++) { - var value = Scalar.Floor(vector.GetElementUnsafe(index)); + float value = Scalar.Floor(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -2359,7 +2369,7 @@ public static Vector128 Floor(Vector128 vector) for (int index = 0; index < Vector128.Count; index++) { - var value = Scalar.Floor(vector.GetElementUnsafe(index)); + double value = Scalar.Floor(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -2575,6 +2585,89 @@ public static bool LessThanOrEqualAll(Vector128 left, Vector128 right) public static bool LessThanOrEqualAny(Vector128 left, Vector128 right) where T : struct => LessThanOrEqual(left, right).As() != Vector128.Zero; + /// Loads a vector from the given source. + /// The source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector128 Load(T* source) + where T : unmanaged + { + return *(Vector128*)source; + } + + /// Loads a vector from the given aligned source. + /// The aligned source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector128 LoadAligned(T* source) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector128BaseType(); + + if (((nuint)source % Alignment) != 0) + { + throw new AccessViolationException(); + } + + return *(Vector128*)source; + } + + /// Loads a vector from the given aligned source. + /// The aligned source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + /// This method may bypass the cache on certain platforms. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector128 LoadAlignedNonTemporal(T* source) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector128BaseType(); + + if (((nuint)source % Alignment) != 0) + { + throw new AccessViolationException(); + } + + return *(Vector128*)source; + } + + /// Loads a vector from the given source. + /// The source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 LoadUnsafe(ref T source) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector128BaseType(); + return Unsafe.ReadUnaligned>(ref Unsafe.As(ref source)); + } + + /// Loads a vector from the given source and element offset. + /// The source to which will be added before loading the vector. + /// The element offset from from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from plus . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 LoadUnsafe(ref T source, nuint elementOffset) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector128BaseType(); + source = ref Unsafe.Add(ref source, (nint)elementOffset); + return Unsafe.ReadUnaligned>(ref Unsafe.As(ref source)); + } + /// Computes the maximum of two vectors on a per-element basis. /// The vector to compare with . /// The vector to compare with . @@ -2656,13 +2749,13 @@ public static unsafe Vector128 Narrow(Vector128 lower, Vector128< for (int i = 0; i < Vector128.Count; i++) { - var value = (float)lower.GetElementUnsafe(i); + float value = (float)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (float)upper.GetElementUnsafe(i - Vector128.Count); + float value = (float)upper.GetElementUnsafe(i - Vector128.Count); result.SetElementUnsafe(i, value); } @@ -2681,13 +2774,13 @@ public static unsafe Vector128 Narrow(Vector128 lower, Vector128.Count; i++) { - var value = (sbyte)lower.GetElementUnsafe(i); + sbyte value = (sbyte)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (sbyte)upper.GetElementUnsafe(i - Vector128.Count); + sbyte value = (sbyte)upper.GetElementUnsafe(i - Vector128.Count); result.SetElementUnsafe(i, value); } @@ -2705,13 +2798,13 @@ public static unsafe Vector128 Narrow(Vector128 lower, Vector128.Count; i++) { - var value = (short)lower.GetElementUnsafe(i); + short value = (short)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (short)upper.GetElementUnsafe(i - Vector128.Count); + short value = (short)upper.GetElementUnsafe(i - Vector128.Count); result.SetElementUnsafe(i, value); } @@ -2729,13 +2822,13 @@ public static unsafe Vector128 Narrow(Vector128 lower, Vector128.Count; i++) { - var value = (int)lower.GetElementUnsafe(i); + int value = (int)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (int)upper.GetElementUnsafe(i - Vector128.Count); + int value = (int)upper.GetElementUnsafe(i - Vector128.Count); result.SetElementUnsafe(i, value); } @@ -2754,13 +2847,13 @@ public static unsafe Vector128 Narrow(Vector128 lower, Vector128.Count; i++) { - var value = (byte)lower.GetElementUnsafe(i); + byte value = (byte)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (byte)upper.GetElementUnsafe(i - Vector128.Count); + byte value = (byte)upper.GetElementUnsafe(i - Vector128.Count); result.SetElementUnsafe(i, value); } @@ -2779,13 +2872,13 @@ public static unsafe Vector128 Narrow(Vector128 lower, Vector128.Count; i++) { - var value = (ushort)lower.GetElementUnsafe(i); + ushort value = (ushort)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (ushort)upper.GetElementUnsafe(i - Vector128.Count); + ushort value = (ushort)upper.GetElementUnsafe(i - Vector128.Count); result.SetElementUnsafe(i, value); } @@ -2804,13 +2897,13 @@ public static unsafe Vector128 Narrow(Vector128 lower, Vector128
    .Count; i++) { - var value = (uint)lower.GetElementUnsafe(i); + uint value = (uint)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (uint)upper.GetElementUnsafe(i - Vector128.Count); + uint value = (uint)upper.GetElementUnsafe(i - Vector128.Count); result.SetElementUnsafe(i, value); } @@ -2835,6 +2928,492 @@ public static Vector128 Negate(Vector128 vector) public static Vector128 OnesComplement(Vector128 vector) where T : struct => ~vector; + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + byte element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + short element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + int element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + long element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + nint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + nuint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + sbyte element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + ushort element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + uint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftLeft(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + ulong element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightArithmetic(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + short element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightArithmetic(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + int element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightArithmetic(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + long element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightArithmetic(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + nint element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightArithmetic(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + sbyte element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + byte element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + short element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + int element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + long element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + nint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + nuint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + sbyte element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + ushort element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + uint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector128 ShiftRightLogical(Vector128 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector128 result); + + for (int index = 0; index < Vector128.Count; index++) + { + ulong element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + /// Computes the square root of a vector on a per-element basis. /// The vector whose square root is to be computed. /// The type of the elements in the vector. @@ -2847,13 +3426,96 @@ public static Vector128 Sqrt(Vector128 vector) for (int index = 0; index < Vector128.Count; index++) { - var value = Scalar.Sqrt(vector.GetElementUnsafe(index)); + T value = Scalar.Sqrt(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } return result; } + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void Store(this Vector128 source, T* destination) + where T : unmanaged + { + *(Vector128*)destination = source; + } + + /// Stores a vector at the given aligned destination. + /// The vector that will be stored. + /// The aligned destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void StoreAligned(this Vector128 source, T* destination) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector128BaseType(); + + if (((nuint)destination % Alignment) != 0) + { + throw new AccessViolationException(); + } + + *(Vector128*)destination = source; + } + + /// Stores a vector at the given aligned destination. + /// The vector that will be stored. + /// The aligned destination at which will be stored. + /// The type of the elements in the vector. + /// This method may bypass the cache on certain platforms. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void StoreAlignedNonTemporal(this Vector128 source, T* destination) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector128BaseType(); + + if (((nuint)destination % Alignment) != 0) + { + throw new AccessViolationException(); + } + + *(Vector128*)destination = source; + } + + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StoreUnsafe(this Vector128 source, ref T destination) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector128BaseType(); + Unsafe.WriteUnaligned(ref Unsafe.As(ref destination), source); + } + + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination to which will be added before the vector will be stored. + /// The element offset from from which the vector will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StoreUnsafe(this Vector128 source, ref T destination, nuint elementOffset) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector128BaseType(); + destination = ref Unsafe.Add(ref destination, (nint)elementOffset); + Unsafe.WriteUnaligned(ref Unsafe.As(ref destination), source); + } + /// Subtracts two vectors to compute their difference. /// The vector from which will be subtracted. /// The vector to subtract from . @@ -2864,6 +3526,24 @@ public static Vector128 Sqrt(Vector128 vector) public static Vector128 Subtract(Vector128 left, Vector128 right) where T : struct => left - right; + /// Computes the sum of all elements in a vector. + /// The vector whose elements will be summed. + /// The type of the elements in the vector. + /// The sum of all elements in . + [Intrinsic] + public static T Sum(Vector128 vector) + where T : struct + { + T sum = default; + + for (int index = 0; index < Vector128.Count; index++) + { + sum = Scalar.Add(sum, vector.GetElementUnsafe(index)); + } + + return sum; + } + /// Converts the given vector to a scalar containing the value of the first element. /// The type of the input vector. /// The vector to get the first element from. @@ -3088,7 +3768,7 @@ internal static Vector128 WidenLower(Vector128 source) for (int i = 0; i < Vector128.Count; i++) { - var value = (ushort)source.GetElementUnsafe(i); + ushort value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3102,7 +3782,7 @@ internal static unsafe Vector128 WidenLower(Vector128 source) for (int i = 0; i < Vector128.Count; i++) { - var value = (int)source.GetElementUnsafe(i); + int value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3116,7 +3796,7 @@ internal static unsafe Vector128 WidenLower(Vector128 source) for (int i = 0; i < Vector128.Count; i++) { - var value = (long)source.GetElementUnsafe(i); + long value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3130,7 +3810,7 @@ internal static unsafe Vector128 WidenLower(Vector128 source) for (int i = 0; i < Vector128.Count; i++) { - var value = (short)source.GetElementUnsafe(i); + short value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3144,7 +3824,7 @@ internal static unsafe Vector128 WidenLower(Vector128 source) for (int i = 0; i < Vector128.Count; i++) { - var value = (double)source.GetElementUnsafe(i); + double value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3158,7 +3838,7 @@ internal static unsafe Vector128 WidenLower(Vector128 source) for (int i = 0; i < Vector128.Count; i++) { - var value = (uint)source.GetElementUnsafe(i); + uint value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3172,7 +3852,7 @@ internal static unsafe Vector128 WidenLower(Vector128 source) for (int i = 0; i < Vector128.Count; i++) { - var value = (ulong)source.GetElementUnsafe(i); + ulong value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3186,7 +3866,7 @@ internal static Vector128 WidenUpper(Vector128 source) for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (ushort)source.GetElementUnsafe(i); + ushort value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector128.Count, value); } @@ -3200,7 +3880,7 @@ internal static unsafe Vector128 WidenUpper(Vector128 source) for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (int)source.GetElementUnsafe(i); + int value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector128.Count, value); } @@ -3214,7 +3894,7 @@ internal static unsafe Vector128 WidenUpper(Vector128 source) for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (long)source.GetElementUnsafe(i); + long value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector128.Count, value); } @@ -3228,7 +3908,7 @@ internal static unsafe Vector128 WidenUpper(Vector128 source) for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (short)source.GetElementUnsafe(i); + short value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector128.Count, value); } @@ -3242,7 +3922,7 @@ internal static unsafe Vector128 WidenUpper(Vector128 source) for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (double)source.GetElementUnsafe(i); + double value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector128.Count, value); } @@ -3256,7 +3936,7 @@ internal static unsafe Vector128 WidenUpper(Vector128 source) for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (uint)source.GetElementUnsafe(i); + uint value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector128.Count, value); } @@ -3270,7 +3950,7 @@ internal static unsafe Vector128 WidenUpper(Vector128 source) for (int i = Vector128.Count; i < Vector128.Count; i++) { - var value = (ulong)source.GetElementUnsafe(i); + ulong value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector128.Count, value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector128_1.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector128_1.cs index c1f81ef2605bc..d98a05f96359c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector128_1.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector128_1.cs @@ -69,6 +69,8 @@ internal static bool IsTypeSupported (typeof(T) == typeof(short)) || (typeof(T) == typeof(int)) || (typeof(T) == typeof(long)) || + (typeof(T) == typeof(nint)) || + (typeof(T) == typeof(nuint)) || (typeof(T) == typeof(sbyte)) || (typeof(T) == typeof(float)) || (typeof(T) == typeof(ushort)) || @@ -116,7 +118,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Add(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Add(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -166,7 +168,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Divide(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Divide(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -226,7 +228,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -244,7 +246,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right); result.SetElementUnsafe(index, value); } @@ -278,7 +280,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Subtract(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Subtract(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -371,7 +373,7 @@ public override int GetHashCode() for (int i = 0; i < Count; i++) { - var value = this.GetElement(i); + T value = this.GetElement(i); hashCode.Add(value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector256.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector256.cs index f51cea7305f6d..6d82ccc8aad53 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector256.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector256.cs @@ -33,6 +33,14 @@ public static class Vector256 { internal const int Size = 32; +#if TARGET_ARM + internal const int Alignment = 8; +#elif TARGET_ARM64 + internal const int Alignment = 16; +#else + internal const int Alignment = 32; +#endif + /// Gets a value that indicates whether 256-bit vector operations are subject to hardware acceleration through JIT intrinsic support. /// if 256-bit vector operations are subject to hardware acceleration; otherwise, . /// 256-bit vector operations are subject to hardware acceleration on systems that support Single Instruction, Multiple Data (SIMD) instructions for 256-bit vectors and the RyuJIT just-in-time compiler is used to compile managed code. @@ -78,7 +86,7 @@ static Vector256 SoftwareFallback(Vector256 vector) for (int index = 0; index < Vector256.Count; index++) { - var value = Scalar.Abs(vector.GetElementUnsafe(index)); + T value = Scalar.Abs(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -299,7 +307,7 @@ public static Vector256 Ceiling(Vector256 vector) for (int index = 0; index < Vector256.Count; index++) { - var value = Scalar.Ceiling(vector.GetElementUnsafe(index)); + float value = Scalar.Ceiling(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -317,7 +325,7 @@ public static Vector256 Ceiling(Vector256 vector) for (int index = 0; index < Vector256.Count; index++) { - var value = Scalar.Ceiling(vector.GetElementUnsafe(index)); + double value = Scalar.Ceiling(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -352,10 +360,10 @@ public static unsafe Vector256 ConvertToDouble(Vector256 vector) lowerBits = vector.AsInt32(); lowerBits = Avx2.Blend(lowerBits, Create(0x43300000_00000000).AsInt32(), 0b10101010); // Blend the 32 lowest significant bits of vector with the bit representation of double(2^52) - var upperBits = Avx2.ShiftRightLogical(vector, 32); // Extract the 32 most significant bits of vector + Vector256 upperBits = Avx2.ShiftRightLogical(vector, 32); // Extract the 32 most significant bits of vector upperBits = Avx2.Xor(upperBits, Create(0x45300000_80000000)); // Flip the msb of upperBits and blend with the bit representation of double(2^84 + 2^63) - var result = Avx.Subtract(upperBits.AsDouble(), Create(0x45300000_80100000).AsDouble()); // Compute in double precision: (upper - (2^84 + 2^63 + 2^52)) + lower + Vector256 result = Avx.Subtract(upperBits.AsDouble(), Create(0x45300000_80100000).AsDouble()); // Compute in double precision: (upper - (2^84 + 2^63 + 2^52)) + lower return Avx.Add(result, lowerBits.AsDouble()); } else @@ -369,7 +377,7 @@ static Vector256 SoftwareFallback(Vector256 vector) for (int i = 0; i < Vector256.Count; i++) { - var value = (double)vector.GetElementUnsafe(i); + double value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -395,10 +403,10 @@ public static unsafe Vector256 ConvertToDouble(Vector256 vector) lowerBits = vector.AsUInt32(); lowerBits = Avx2.Blend(lowerBits, Create(0x43300000_00000000UL).AsUInt32(), 0b10101010); // Blend the 32 lowest significant bits of vector with the bit representation of double(2^52) */ - var upperBits = Avx2.ShiftRightLogical(vector, 32); // Extract the 32 most significant bits of vector + Vector256 upperBits = Avx2.ShiftRightLogical(vector, 32); // Extract the 32 most significant bits of vector upperBits = Avx2.Xor(upperBits, Create(0x45300000_00000000UL)); // Blend upperBits with the bit representation of double(2^84) - var result = Avx.Subtract(upperBits.AsDouble(), Create(0x45300000_00100000UL).AsDouble()); // Compute in double precision: (upper - (2^84 + 2^52)) + lower + Vector256 result = Avx.Subtract(upperBits.AsDouble(), Create(0x45300000_00100000UL).AsDouble()); // Compute in double precision: (upper - (2^84 + 2^52)) + lower return Avx.Add(result, lowerBits.AsDouble()); } else @@ -412,7 +420,7 @@ static Vector256 SoftwareFallback(Vector256 vector) for (int i = 0; i < Vector256.Count; i++) { - var value = (double)vector.GetElementUnsafe(i); + double value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -430,7 +438,7 @@ public static unsafe Vector256 ConvertToInt32(Vector256 vector) for (int i = 0; i < Vector256.Count; i++) { - var value = (int)vector.GetElementUnsafe(i); + int value = (int)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -447,7 +455,7 @@ public static unsafe Vector256 ConvertToInt64(Vector256 vector) for (int i = 0; i < Vector256.Count; i++) { - var value = (long)vector.GetElementUnsafe(i); + long value = (long)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -464,7 +472,7 @@ public static unsafe Vector256 ConvertToSingle(Vector256 vector) for (int i = 0; i < Vector256.Count; i++) { - var value = (float)vector.GetElementUnsafe(i); + float value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -486,11 +494,11 @@ public static unsafe Vector256 ConvertToSingle(Vector256 vector) // This means everything between 0 and 2^16 (ushort.MaxValue + 1) are exact and so // converting each of the upper and lower halves will give an exact result - var lowerBits = Avx2.And(vector, Create(0x0000FFFFU)).AsInt32(); - var upperBits = Avx2.ShiftRightLogical(vector, 16).AsInt32(); + Vector256 lowerBits = Avx2.And(vector, Create(0x0000FFFFU)).AsInt32(); + Vector256 upperBits = Avx2.ShiftRightLogical(vector, 16).AsInt32(); - var lower = Avx.ConvertToVector256Single(lowerBits); - var upper = Avx.ConvertToVector256Single(upperBits); + Vector256 lower = Avx.ConvertToVector256Single(lowerBits); + Vector256 upper = Avx.ConvertToVector256Single(upperBits); // This next bit of magic works because all multiples of 65536, at least up to 65535 // are likewise exactly representable @@ -505,7 +513,7 @@ public static unsafe Vector256 ConvertToSingle(Vector256 vector) } else { - var result = Avx.Multiply(upper, Vector256.Create(65536.0f)); + Vector256 result = Avx.Multiply(upper, Vector256.Create(65536.0f)); return Avx.Add(result, lower); } } @@ -520,7 +528,7 @@ static Vector256 SoftwareFallback(Vector256 vector) for (int i = 0; i < Vector256.Count; i++) { - var value = (float)vector.GetElementUnsafe(i); + float value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -539,7 +547,7 @@ public static unsafe Vector256 ConvertToUInt32(Vector256 vector) for (int i = 0; i < Vector256.Count; i++) { - var value = (uint)vector.GetElementUnsafe(i); + uint value = (uint)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -557,7 +565,7 @@ public static unsafe Vector256 ConvertToUInt64(Vector256 vector) for (int i = 0; i < Vector256.Count; i++) { - var value = (ulong)vector.GetElementUnsafe(i); + ulong value = (ulong)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -876,14 +884,11 @@ public static unsafe Vector256 Create(nint value) static Vector256 SoftwareFallback(nint value) { - if (Environment.Is64BitProcess) - { - return Create((long)value).AsNInt(); - } - else - { - return Create((int)value).AsNInt(); - } +#if TARGET_64BIT + return Create((long)value).AsNInt(); +#else + return Create((int)value).AsNInt(); +#endif } } @@ -903,14 +908,11 @@ public static unsafe Vector256 Create(nuint value) static Vector256 SoftwareFallback(nuint value) { - if (Environment.Is64BitProcess) - { - return Create((ulong)value).AsNUInt(); - } - else - { - return Create((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return Create((ulong)value).AsNUInt(); +#else + return Create((uint)value).AsNUInt(); +#endif } } @@ -1949,7 +1951,7 @@ public static unsafe Vector256 CreateScalar(byte value) static Vector256 SoftwareFallback(byte value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1970,7 +1972,7 @@ public static unsafe Vector256 CreateScalar(double value) static Vector256 SoftwareFallback(double value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1991,7 +1993,7 @@ public static unsafe Vector256 CreateScalar(short value) static Vector256 SoftwareFallback(short value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2012,7 +2014,7 @@ public static unsafe Vector256 CreateScalar(int value) static Vector256 SoftwareFallback(int value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2033,7 +2035,7 @@ public static unsafe Vector256 CreateScalar(long value) static Vector256 SoftwareFallback(long value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2054,14 +2056,11 @@ public static unsafe Vector256 CreateScalar(nint value) static Vector256 SoftwareFallback(nint value) { - if (Environment.Is64BitProcess) - { - return CreateScalar((long)value).AsNInt(); - } - else - { - return CreateScalar((int)value).AsNInt(); - } +#if TARGET_64BIT + return CreateScalar((long)value).AsNInt(); +#else + return CreateScalar((int)value).AsNInt(); +#endif } } @@ -2081,14 +2080,11 @@ public static unsafe Vector256 CreateScalar(nuint value) static Vector256 SoftwareFallback(nuint value) { - if (Environment.Is64BitProcess) - { - return CreateScalar((ulong)value).AsNUInt(); - } - else - { - return CreateScalar((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return CreateScalar((ulong)value).AsNUInt(); +#else + return CreateScalar((uint)value).AsNUInt(); +#endif } } @@ -2108,7 +2104,7 @@ public static unsafe Vector256 CreateScalar(sbyte value) static Vector256 SoftwareFallback(sbyte value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2129,7 +2125,7 @@ public static unsafe Vector256 CreateScalar(float value) static Vector256 SoftwareFallback(float value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2151,7 +2147,7 @@ public static unsafe Vector256 CreateScalar(ushort value) static Vector256 SoftwareFallback(ushort value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2173,7 +2169,7 @@ public static unsafe Vector256 CreateScalar(uint value) static Vector256 SoftwareFallback(uint value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2195,7 +2191,7 @@ public static unsafe Vector256 CreateScalar(ulong value) static Vector256 SoftwareFallback(ulong value) { - var result = Vector256.Zero; + Vector256 result = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -2277,14 +2273,11 @@ public static unsafe Vector256 CreateScalarUnsafe(long value) [Intrinsic] public static unsafe Vector256 CreateScalarUnsafe(nint value) { - if (Environment.Is64BitProcess) - { - return CreateScalarUnsafe((long)value).AsNInt(); - } - else - { - return CreateScalarUnsafe((int)value).AsNInt(); - } +#if TARGET_64BIT + return CreateScalarUnsafe((long)value).AsNInt(); +#else + return CreateScalarUnsafe((int)value).AsNInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements left uninitialized. @@ -2294,14 +2287,11 @@ public static unsafe Vector256 CreateScalarUnsafe(nint value) [CLSCompliant(false)] public static unsafe Vector256 CreateScalarUnsafe(nuint value) { - if (Environment.Is64BitProcess) - { - return CreateScalarUnsafe((ulong)value).AsNUInt(); - } - else - { - return CreateScalarUnsafe((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return CreateScalarUnsafe((ulong)value).AsNUInt(); +#else + return CreateScalarUnsafe((uint)value).AsNUInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements left uninitialized. @@ -2401,7 +2391,7 @@ public static T Dot(Vector256 left, Vector256 right) for (int index = 0; index < Vector256.Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result = Scalar.Add(result, value); } @@ -2421,7 +2411,7 @@ public static Vector256 Equals(Vector256 left, Vector256 right) for (int index = 0; index < Vector256.Count; index++) { - var value = Scalar.Equals(left.GetElementUnsafe(index), right.GetElementUnsafe(index)) ? Scalar.AllBitsSet : default; + T value = Scalar.Equals(left.GetElementUnsafe(index), right.GetElementUnsafe(index)) ? Scalar.AllBitsSet : default; result.SetElementUnsafe(index, value); } @@ -2448,6 +2438,28 @@ public static bool EqualsAll(Vector256 left, Vector256 right) public static bool EqualsAny(Vector256 left, Vector256 right) where T : struct => Equals(left, right).As() != Vector256.Zero; + /// Extracts the most significant bit from each element in a vector. + /// The vector whose elements should have their most significant bit extracted. + /// The type of the elements in the vector. + /// The packed most significant bits extracted from the elements in . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint ExtractMostSignificantBits(this Vector256 vector) + where T : struct + { + uint result = 0; + + for (int index = 0; index < Vector256.Count; index++) + { + uint value = Scalar.ExtractMostSignificantBit(vector.GetElementUnsafe(index)); + value <<= index; + result |= value; + } + + return result; + } + /// Computes the floor of each element in a vector. /// The vector that will have its floor computed. /// A vector whose elements are the floor of the elements in . @@ -2459,7 +2471,7 @@ public static Vector256 Floor(Vector256 vector) for (int index = 0; index < Vector256.Count; index++) { - var value = Scalar.Floor(vector.GetElementUnsafe(index)); + float value = Scalar.Floor(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -2477,7 +2489,7 @@ public static Vector256 Floor(Vector256 vector) for (int index = 0; index < Vector256.Count; index++) { - var value = Scalar.Floor(vector.GetElementUnsafe(index)); + double value = Scalar.Floor(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -2711,6 +2723,89 @@ public static bool LessThanOrEqualAll(Vector256 left, Vector256 right) public static bool LessThanOrEqualAny(Vector256 left, Vector256 right) where T : struct => LessThanOrEqual(left, right).As() != Vector256.Zero; + /// Loads a vector from the given source. + /// The source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector256 Load(T* source) + where T : unmanaged + { + return *(Vector256*)source; + } + + /// Loads a vector from the given aligned source. + /// The aligned source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector256 LoadAligned(T* source) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector256BaseType(); + + if (((nuint)source % Alignment) != 0) + { + throw new AccessViolationException(); + } + + return *(Vector256*)source; + } + + /// Loads a vector from the given aligned source. + /// The aligned source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + /// This method may bypass the cache on certain platforms. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector256 LoadAlignedNonTemporal(T* source) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector256BaseType(); + + if (((nuint)source % Alignment) != 0) + { + throw new AccessViolationException(); + } + + return *(Vector256*)source; + } + + /// Loads a vector from the given source. + /// The source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 LoadUnsafe(ref T source) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector256BaseType(); + return Unsafe.ReadUnaligned>(ref Unsafe.As(ref source)); + } + + /// Loads a vector from the given source and element offset. + /// The source to which will be added before loading the vector. + /// The element offset from from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from plus . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 LoadUnsafe(ref T source, nuint elementOffset) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector256BaseType(); + source = ref Unsafe.Add(ref source, (nint)elementOffset); + return Unsafe.ReadUnaligned>(ref Unsafe.As(ref source)); + } + /// Computes the maximum of two vectors on a per-element basis. /// The vector to compare with . /// The vector to compare with . @@ -2792,13 +2887,13 @@ public static unsafe Vector256 Narrow(Vector256 lower, Vector256< for (int i = 0; i < Vector256.Count; i++) { - var value = (float)lower.GetElementUnsafe(i); + float value = (float)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (float)upper.GetElementUnsafe(i - Vector256.Count); + float value = (float)upper.GetElementUnsafe(i - Vector256.Count); result.SetElementUnsafe(i, value); } @@ -2817,13 +2912,13 @@ public static unsafe Vector256 Narrow(Vector256 lower, Vector256.Count; i++) { - var value = (sbyte)lower.GetElementUnsafe(i); + sbyte value = (sbyte)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (sbyte)upper.GetElementUnsafe(i - Vector256.Count); + sbyte value = (sbyte)upper.GetElementUnsafe(i - Vector256.Count); result.SetElementUnsafe(i, value); } @@ -2841,13 +2936,13 @@ public static unsafe Vector256 Narrow(Vector256 lower, Vector256.Count; i++) { - var value = (short)lower.GetElementUnsafe(i); + short value = (short)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (short)upper.GetElementUnsafe(i - Vector256.Count); + short value = (short)upper.GetElementUnsafe(i - Vector256.Count); result.SetElementUnsafe(i, value); } @@ -2865,13 +2960,13 @@ public static unsafe Vector256 Narrow(Vector256 lower, Vector256.Count; i++) { - var value = (int)lower.GetElementUnsafe(i); + int value = (int)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (int)upper.GetElementUnsafe(i - Vector256.Count); + int value = (int)upper.GetElementUnsafe(i - Vector256.Count); result.SetElementUnsafe(i, value); } @@ -2890,13 +2985,13 @@ public static unsafe Vector256 Narrow(Vector256 lower, Vector256.Count; i++) { - var value = (byte)lower.GetElementUnsafe(i); + byte value = (byte)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (byte)upper.GetElementUnsafe(i - Vector256.Count); + byte value = (byte)upper.GetElementUnsafe(i - Vector256.Count); result.SetElementUnsafe(i, value); } @@ -2915,13 +3010,13 @@ public static unsafe Vector256 Narrow(Vector256 lower, Vector256.Count; i++) { - var value = (ushort)lower.GetElementUnsafe(i); + ushort value = (ushort)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (ushort)upper.GetElementUnsafe(i - Vector256.Count); + ushort value = (ushort)upper.GetElementUnsafe(i - Vector256.Count); result.SetElementUnsafe(i, value); } @@ -2940,13 +3035,13 @@ public static unsafe Vector256 Narrow(Vector256 lower, Vector256
      .Count; i++) { - var value = (uint)lower.GetElementUnsafe(i); + uint value = (uint)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (uint)upper.GetElementUnsafe(i - Vector256.Count); + uint value = (uint)upper.GetElementUnsafe(i - Vector256.Count); result.SetElementUnsafe(i, value); } @@ -2971,6 +3066,492 @@ public static Vector256 Negate(Vector256 vector) public static Vector256 OnesComplement(Vector256 vector) where T : struct => ~vector; + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + byte element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + short element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + int element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + long element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + nint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + nuint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + sbyte element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + ushort element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + uint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftLeft(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + ulong element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightArithmetic(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + short element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightArithmetic(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + int element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightArithmetic(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + long element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightArithmetic(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + nint element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightArithmetic(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + sbyte element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + byte element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + short element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + int element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + long element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + nint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + nuint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + sbyte element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + ushort element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + uint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector256 ShiftRightLogical(Vector256 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector256 result); + + for (int index = 0; index < Vector256.Count; index++) + { + ulong element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + /// Computes the square root of a vector on a per-element basis. /// The vector whose square root is to be computed. /// The type of the elements in the vector. @@ -2983,13 +3564,96 @@ public static Vector256 Sqrt(Vector256 vector) for (int index = 0; index < Vector256.Count; index++) { - var value = Scalar.Sqrt(vector.GetElementUnsafe(index)); + T value = Scalar.Sqrt(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } return result; } + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void Store(this Vector256 source, T* destination) + where T : unmanaged + { + *(Vector256*)destination = source; + } + + /// Stores a vector at the given aligned destination. + /// The vector that will be stored. + /// The aligned destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void StoreAligned(this Vector256 source, T* destination) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector256BaseType(); + + if (((nuint)destination % Alignment) != 0) + { + throw new AccessViolationException(); + } + + *(Vector256*)destination = source; + } + + /// Stores a vector at the given aligned destination. + /// The vector that will be stored. + /// The aligned destination at which will be stored. + /// The type of the elements in the vector. + /// This method may bypass the cache on certain platforms. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void StoreAlignedNonTemporal(this Vector256 source, T* destination) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector256BaseType(); + + if (((nuint)destination % Alignment) != 0) + { + throw new AccessViolationException(); + } + + *(Vector256*)destination = source; + } + + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StoreUnsafe(this Vector256 source, ref T destination) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector256BaseType(); + Unsafe.WriteUnaligned(ref Unsafe.As(ref destination), source); + } + + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination to which will be added before the vector will be stored. + /// The element offset from from which the vector will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StoreUnsafe(this Vector256 source, ref T destination, nuint elementOffset) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector256BaseType(); + destination = ref Unsafe.Add(ref destination, (nint)elementOffset); + Unsafe.WriteUnaligned(ref Unsafe.As(ref destination), source); + } + /// Subtracts two vectors to compute their difference. /// The vector from which will be subtracted. /// The vector to subtract from . @@ -3000,6 +3664,24 @@ public static Vector256 Sqrt(Vector256 vector) public static Vector256 Subtract(Vector256 left, Vector256 right) where T : struct => left - right; + /// Computes the sum of all elements in a vector. + /// The vector whose elements will be summed. + /// The type of the elements in the vector. + /// The sum of all elements in . + [Intrinsic] + public static T Sum(Vector256 vector) + where T : struct + { + T sum = default; + + for (int index = 0; index < Vector256.Count; index++) + { + sum = Scalar.Add(sum, vector.GetElementUnsafe(index)); + } + + return sum; + } + /// Converts the given vector to a scalar containing the value of the first element. /// The type of the input vector. /// The vector to get the first element from. @@ -3205,7 +3887,7 @@ internal static Vector256 WidenLower(Vector256 source) for (int i = 0; i < Vector256.Count; i++) { - var value = (ushort)source.GetElementUnsafe(i); + ushort value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3219,7 +3901,7 @@ internal static unsafe Vector256 WidenLower(Vector256 source) for (int i = 0; i < Vector256.Count; i++) { - var value = (int)source.GetElementUnsafe(i); + int value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3233,7 +3915,7 @@ internal static unsafe Vector256 WidenLower(Vector256 source) for (int i = 0; i < Vector256.Count; i++) { - var value = (long)source.GetElementUnsafe(i); + long value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3247,7 +3929,7 @@ internal static unsafe Vector256 WidenLower(Vector256 source) for (int i = 0; i < Vector256.Count; i++) { - var value = (short)source.GetElementUnsafe(i); + short value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3261,7 +3943,7 @@ internal static unsafe Vector256 WidenLower(Vector256 source) for (int i = 0; i < Vector256.Count; i++) { - var value = (double)source.GetElementUnsafe(i); + double value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3275,7 +3957,7 @@ internal static unsafe Vector256 WidenLower(Vector256 source) for (int i = 0; i < Vector256.Count; i++) { - var value = (uint)source.GetElementUnsafe(i); + uint value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3289,7 +3971,7 @@ internal static unsafe Vector256 WidenLower(Vector256 source) for (int i = 0; i < Vector256.Count; i++) { - var value = (ulong)source.GetElementUnsafe(i); + ulong value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -3303,7 +3985,7 @@ internal static Vector256 WidenUpper(Vector256 source) for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (ushort)source.GetElementUnsafe(i); + ushort value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector256.Count, value); } @@ -3317,7 +3999,7 @@ internal static unsafe Vector256 WidenUpper(Vector256 source) for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (int)source.GetElementUnsafe(i); + int value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector256.Count, value); } @@ -3331,7 +4013,7 @@ internal static unsafe Vector256 WidenUpper(Vector256 source) for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (long)source.GetElementUnsafe(i); + long value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector256.Count, value); } @@ -3345,7 +4027,7 @@ internal static unsafe Vector256 WidenUpper(Vector256 source) for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (short)source.GetElementUnsafe(i); + short value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector256.Count, value); } @@ -3359,7 +4041,7 @@ internal static unsafe Vector256 WidenUpper(Vector256 source) for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (double)source.GetElementUnsafe(i); + double value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector256.Count, value); } @@ -3373,7 +4055,7 @@ internal static unsafe Vector256 WidenUpper(Vector256 source) for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (uint)source.GetElementUnsafe(i); + uint value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector256.Count, value); } @@ -3387,7 +4069,7 @@ internal static unsafe Vector256 WidenUpper(Vector256 source) for (int i = Vector256.Count; i < Vector256.Count; i++) { - var value = (ulong)source.GetElementUnsafe(i); + ulong value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector256.Count, value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector256_1.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector256_1.cs index 37478d8e76242..4a3e083377826 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector256_1.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector256_1.cs @@ -71,6 +71,8 @@ internal static bool IsTypeSupported (typeof(T) == typeof(short)) || (typeof(T) == typeof(int)) || (typeof(T) == typeof(long)) || + (typeof(T) == typeof(nint)) || + (typeof(T) == typeof(nuint)) || (typeof(T) == typeof(sbyte)) || (typeof(T) == typeof(float)) || (typeof(T) == typeof(ushort)) || @@ -118,7 +120,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Add(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Add(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -172,7 +174,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Divide(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Divide(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -234,7 +236,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -252,7 +254,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right); result.SetElementUnsafe(index, value); } @@ -286,7 +288,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Subtract(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Subtract(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -373,7 +375,7 @@ public override int GetHashCode() for (int i = 0; i < Count; i++) { - var value = this.GetElement(i); + T value = this.GetElement(i); hashCode.Add(value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector64.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector64.cs index cd7ef0a3e27c0..c6e458325cd7b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector64.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector64.cs @@ -15,6 +15,8 @@ public static class Vector64 { internal const int Size = 8; + internal const int Alignment = 8; + /// Gets a value that indicates whether 64-bit vector operations are subject to hardware acceleration through JIT intrinsic support. /// if 64-bit vector operations are subject to hardware acceleration; otherwise, . /// 64-bit vector operations are subject to hardware acceleration on systems that support Single Instruction, Multiple Data (SIMD) instructions for 64-bit vectors and the RyuJIT just-in-time compiler is used to compile managed code. @@ -60,7 +62,7 @@ static Vector64 SoftwareFallback(Vector64 vector) for (int index = 0; index < Vector64.Count; index++) { - var value = Scalar.Abs(vector.GetElementUnsafe(index)); + T value = Scalar.Abs(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -250,7 +252,7 @@ public static Vector64 Ceiling(Vector64 vector) for (int index = 0; index < Vector64.Count; index++) { - var value = Scalar.Ceiling(vector.GetElementUnsafe(index)); + float value = Scalar.Ceiling(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -267,7 +269,7 @@ public static Vector64 Ceiling(Vector64 vector) { Unsafe.SkipInit(out Vector64 result); - var value = Scalar.Ceiling(vector.GetElementUnsafe(0)); + double value = Scalar.Ceiling(vector.GetElementUnsafe(0)); result.SetElementUnsafe(0, value); return result; @@ -294,7 +296,7 @@ public static unsafe Vector64 ConvertToDouble(Vector64 vector) for (int i = 0; i < Vector64.Count; i++) { - var value = (double)vector.GetElementUnsafe(i); + double value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -312,7 +314,7 @@ public static unsafe Vector64 ConvertToDouble(Vector64 vector) for (int i = 0; i < Vector64.Count; i++) { - var value = (double)vector.GetElementUnsafe(i); + double value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -329,7 +331,7 @@ public static unsafe Vector64 ConvertToInt32(Vector64 vector) for (int i = 0; i < Vector64.Count; i++) { - var value = (int)vector.GetElementUnsafe(i); + int value = (int)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -346,7 +348,7 @@ public static unsafe Vector64 ConvertToInt64(Vector64 vector) for (int i = 0; i < Vector64.Count; i++) { - var value = (long)vector.GetElementUnsafe(i); + long value = (long)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -363,7 +365,7 @@ public static unsafe Vector64 ConvertToSingle(Vector64 vector) for (int i = 0; i < Vector64.Count; i++) { - var value = (float)vector.GetElementUnsafe(i); + float value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -381,7 +383,7 @@ public static unsafe Vector64 ConvertToSingle(Vector64 vector) for (int i = 0; i < Vector64.Count; i++) { - var value = (float)vector.GetElementUnsafe(i); + float value = vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -399,7 +401,7 @@ public static unsafe Vector64 ConvertToUInt32(Vector64 vector) for (int i = 0; i < Vector64.Count; i++) { - var value = (uint)vector.GetElementUnsafe(i); + uint value = (uint)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -417,7 +419,7 @@ public static unsafe Vector64 ConvertToUInt64(Vector64 vector) for (int i = 0; i < Vector64.Count; i++) { - var value = (ulong)vector.GetElementUnsafe(i); + ulong value = (ulong)vector.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } @@ -675,14 +677,11 @@ public static unsafe Vector64 Create(nint value) static Vector64 SoftwareFallback(nint value) { - if (Environment.Is64BitProcess) - { - return Create((long)value).AsNInt(); - } - else - { - return Create((int)value).AsNInt(); - } +#if TARGET_64BIT + return Create((long)value).AsNInt(); +#else + return Create((int)value).AsNInt(); +#endif } } @@ -702,14 +701,11 @@ public static unsafe Vector64 Create(nuint value) static Vector64 SoftwareFallback(nuint value) { - if (Environment.Is64BitProcess) - { - return Create((ulong)value).AsNUInt(); - } - else - { - return Create((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return Create((ulong)value).AsNUInt(); +#else + return Create((uint)value).AsNUInt(); +#endif } } @@ -1137,7 +1133,7 @@ public static unsafe Vector64 CreateScalar(byte value) static Vector64 SoftwareFallback(byte value) { - var result = Vector64.Zero; + Vector64 result = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1177,7 +1173,7 @@ public static unsafe Vector64 CreateScalar(short value) static Vector64 SoftwareFallback(short value) { - var result = Vector64.Zero; + Vector64 result = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1198,7 +1194,7 @@ public static unsafe Vector64 CreateScalar(int value) static Vector64 SoftwareFallback(int value) { - var result = Vector64.Zero; + Vector64 result = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1229,14 +1225,11 @@ static Vector64 SoftwareFallback(long value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe Vector64 CreateScalar(nint value) { - if (Environment.Is64BitProcess) - { - return CreateScalar((long)value).AsNInt(); - } - else - { - return CreateScalar((int)value).AsNInt(); - } +#if TARGET_64BIT + return CreateScalar((long)value).AsNInt(); +#else + return CreateScalar((int)value).AsNInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements initialized to zero. @@ -1246,14 +1239,11 @@ public static unsafe Vector64 CreateScalar(nint value) [CLSCompliant(false)] public static unsafe Vector64 CreateScalar(nuint value) { - if (Environment.Is64BitProcess) - { - return CreateScalar((ulong)value).AsNUInt(); - } - else - { - return CreateScalar((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return CreateScalar((ulong)value).AsNUInt(); +#else + return CreateScalar((uint)value).AsNUInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements initialized to zero. @@ -1272,7 +1262,7 @@ public static unsafe Vector64 CreateScalar(sbyte value) static Vector64 SoftwareFallback(sbyte value) { - var result = Vector64.Zero; + Vector64 result = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1293,7 +1283,7 @@ public static unsafe Vector64 CreateScalar(float value) static Vector64 SoftwareFallback(float value) { - var result = Vector64.Zero; + Vector64 result = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1315,7 +1305,7 @@ public static unsafe Vector64 CreateScalar(ushort value) static Vector64 SoftwareFallback(ushort value) { - var result = Vector64.Zero; + Vector64 result = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1337,7 +1327,7 @@ public static unsafe Vector64 CreateScalar(uint value) static Vector64 SoftwareFallback(uint value) { - var result = Vector64.Zero; + Vector64 result = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref result), value); return result; } @@ -1412,14 +1402,11 @@ public static unsafe Vector64 CreateScalarUnsafe(int value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe Vector64 CreateScalarUnsafe(nint value) { - if (Environment.Is64BitProcess) - { - return Create((long)value).AsNInt(); - } - else - { - return CreateScalarUnsafe((int)value).AsNInt(); - } +#if TARGET_64BIT + return Create((long)value).AsNInt(); +#else + return CreateScalarUnsafe((int)value).AsNInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements left uninitialized. @@ -1429,14 +1416,11 @@ public static unsafe Vector64 CreateScalarUnsafe(nint value) [CLSCompliant(false)] public static unsafe Vector64 CreateScalarUnsafe(nuint value) { - if (Environment.Is64BitProcess) - { - return Create((ulong)value).AsNUInt(); - } - else - { - return CreateScalarUnsafe((uint)value).AsNUInt(); - } +#if TARGET_64BIT + return Create((ulong)value).AsNUInt(); +#else + return CreateScalarUnsafe((uint)value).AsNUInt(); +#endif } /// Creates a new instance with the first element initialized to the specified value and the remaining elements left uninitialized. @@ -1521,7 +1505,7 @@ public static T Dot(Vector64 left, Vector64 right) for (int index = 0; index < Vector64.Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result = Scalar.Add(result, value); } @@ -1541,7 +1525,7 @@ public static Vector64 Equals(Vector64 left, Vector64 right) for (int index = 0; index < Vector64.Count; index++) { - var value = Scalar.Equals(left.GetElementUnsafe(index), right.GetElementUnsafe(index)) ? Scalar.AllBitsSet : default; + T value = Scalar.Equals(left.GetElementUnsafe(index), right.GetElementUnsafe(index)) ? Scalar.AllBitsSet : default; result.SetElementUnsafe(index, value); } @@ -1568,6 +1552,28 @@ public static bool EqualsAll(Vector64 left, Vector64 right) public static bool EqualsAny(Vector64 left, Vector64 right) where T : struct => Equals(left, right).As() != Vector64.Zero; + /// Extracts the most significant bit from each element in a vector. + /// The vector whose elements should have their most significant bit extracted. + /// The type of the elements in the vector. + /// The packed most significant bits extracted from the elements in . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static uint ExtractMostSignificantBits(this Vector64 vector) + where T : struct + { + uint result = 0; + + for (int index = 0; index < Vector64.Count; index++) + { + uint value = Scalar.ExtractMostSignificantBit(vector.GetElementUnsafe(index)); + value <<= index; + result |= value; + } + + return result; + } + /// Computes the floor of each element in a vector. /// The vector that will have its floor computed. /// A vector whose elements are the floor of the elements in . @@ -1579,7 +1585,7 @@ public static Vector64 Floor(Vector64 vector) for (int index = 0; index < Vector64.Count; index++) { - var value = Scalar.Floor(vector.GetElementUnsafe(index)); + float value = Scalar.Floor(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -1596,7 +1602,7 @@ public static Vector64 Floor(Vector64 vector) { Unsafe.SkipInit(out Vector64 result); - var value = Scalar.Floor(vector.GetElementUnsafe(0)); + double value = Scalar.Floor(vector.GetElementUnsafe(0)); result.SetElementUnsafe(0, value); return result; @@ -1783,6 +1789,89 @@ public static bool LessThanOrEqualAll(Vector64 left, Vector64 right) public static bool LessThanOrEqualAny(Vector64 left, Vector64 right) where T : struct => LessThanOrEqual(left, right).As() != Vector64.Zero; + /// Loads a vector from the given source. + /// The source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector64 Load(T* source) + where T : unmanaged + { + return *(Vector64*)source; + } + + /// Loads a vector from the given aligned source. + /// The aligned source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector64 LoadAligned(T* source) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector64BaseType(); + + if (((nuint)source % Alignment) != 0) + { + throw new AccessViolationException(); + } + + return *(Vector64*)source; + } + + /// Loads a vector from the given aligned source. + /// The aligned source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + /// This method may bypass the cache on certain platforms. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe Vector64 LoadAlignedNonTemporal(T* source) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector64BaseType(); + + if (((nuint)source % Alignment) != 0) + { + throw new AccessViolationException(); + } + + return *(Vector64*)source; + } + + /// Loads a vector from the given source. + /// The source from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 LoadUnsafe(ref T source) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector64BaseType(); + return Unsafe.ReadUnaligned>(ref Unsafe.As(ref source)); + } + + /// Loads a vector from the given source and element offset. + /// The source to which will be added before loading the vector. + /// The element offset from from which the vector will be loaded. + /// The type of the elements in the vector. + /// The vector loaded from plus . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 LoadUnsafe(ref T source, nuint elementOffset) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector64BaseType(); + source = ref Unsafe.Add(ref source, (nint)elementOffset); + return Unsafe.ReadUnaligned>(ref Unsafe.As(ref source)); + } + /// Computes the maximum of two vectors on a per-element basis. /// The vector to compare with . /// The vector to compare with . @@ -1864,13 +1953,13 @@ public static unsafe Vector64 Narrow(Vector64 lower, Vector64.Count; i++) { - var value = (float)lower.GetElementUnsafe(i); + float value = (float)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (float)upper.GetElementUnsafe(i - Vector64.Count); + float value = (float)upper.GetElementUnsafe(i - Vector64.Count); result.SetElementUnsafe(i, value); } @@ -1889,13 +1978,13 @@ public static unsafe Vector64 Narrow(Vector64 lower, Vector64.Count; i++) { - var value = (sbyte)lower.GetElementUnsafe(i); + sbyte value = (sbyte)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (sbyte)upper.GetElementUnsafe(i - Vector64.Count); + sbyte value = (sbyte)upper.GetElementUnsafe(i - Vector64.Count); result.SetElementUnsafe(i, value); } @@ -1913,13 +2002,13 @@ public static unsafe Vector64 Narrow(Vector64 lower, Vector64 u for (int i = 0; i < Vector64.Count; i++) { - var value = (short)lower.GetElementUnsafe(i); + short value = (short)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (short)upper.GetElementUnsafe(i - Vector64.Count); + short value = (short)upper.GetElementUnsafe(i - Vector64.Count); result.SetElementUnsafe(i, value); } @@ -1937,13 +2026,13 @@ public static unsafe Vector64 Narrow(Vector64 lower, Vector64 u for (int i = 0; i < Vector64.Count; i++) { - var value = (int)lower.GetElementUnsafe(i); + int value = (int)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (int)upper.GetElementUnsafe(i - Vector64.Count); + int value = (int)upper.GetElementUnsafe(i - Vector64.Count); result.SetElementUnsafe(i, value); } @@ -1962,13 +2051,13 @@ public static unsafe Vector64 Narrow(Vector64 lower, Vector64.Count; i++) { - var value = (byte)lower.GetElementUnsafe(i); + byte value = (byte)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (byte)upper.GetElementUnsafe(i - Vector64.Count); + byte value = (byte)upper.GetElementUnsafe(i - Vector64.Count); result.SetElementUnsafe(i, value); } @@ -1987,13 +2076,13 @@ public static unsafe Vector64 Narrow(Vector64 lower, Vector64.Count; i++) { - var value = (ushort)lower.GetElementUnsafe(i); + ushort value = (ushort)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (ushort)upper.GetElementUnsafe(i - Vector64.Count); + ushort value = (ushort)upper.GetElementUnsafe(i - Vector64.Count); result.SetElementUnsafe(i, value); } @@ -2012,13 +2101,13 @@ public static unsafe Vector64 Narrow(Vector64 lower, Vector64.Count; i++) { - var value = (uint)lower.GetElementUnsafe(i); + uint value = (uint)lower.GetElementUnsafe(i); result.SetElementUnsafe(i, value); } for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (uint)upper.GetElementUnsafe(i - Vector64.Count); + uint value = (uint)upper.GetElementUnsafe(i - Vector64.Count); result.SetElementUnsafe(i, value); } @@ -2043,6 +2132,492 @@ public static Vector64 Negate(Vector64 vector) public static Vector64 OnesComplement(Vector64 vector) where T : struct => ~vector; + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + byte element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + short element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + int element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + long element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + nint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + nuint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + sbyte element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + ushort element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + uint element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts each element of a vector left by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted left by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftLeft(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + ulong element = Scalar.ShiftLeft(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightArithmetic(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + short element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightArithmetic(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + int element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightArithmetic(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + long element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightArithmetic(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + nint element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (signed) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightArithmetic(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + sbyte element = Scalar.ShiftRightArithmetic(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + byte element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + short element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + int element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + long element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + nint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + nuint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + sbyte element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + ushort element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + uint element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + + /// Shifts (unsigned) each element of a vector right by the specified amount. + /// The vector whose elements are to be shifted. + /// The number of bits by which to shift each element. + /// A vector whose elements where shifted right by . + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector64 ShiftRightLogical(Vector64 vector, int shiftCount) + { + Unsafe.SkipInit(out Vector64 result); + + for (int index = 0; index < Vector64.Count; index++) + { + ulong element = Scalar.ShiftRightLogical(vector.GetElementUnsafe(index), shiftCount); + result.SetElementUnsafe(index, element); + } + + return result; + } + /// Computes the square root of a vector on a per-element basis. /// The vector whose square root is to be computed. /// The type of the elements in the vector. @@ -2055,13 +2630,96 @@ public static Vector64 Sqrt(Vector64 vector) for (int index = 0; index < Vector64.Count; index++) { - var value = Scalar.Sqrt(vector.GetElementUnsafe(index)); + T value = Scalar.Sqrt(vector.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } return result; } + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void Store(this Vector64 source, T* destination) + where T : unmanaged + { + *(Vector64*)destination = source; + } + + /// Stores a vector at the given aligned destination. + /// The vector that will be stored. + /// The aligned destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void StoreAligned(this Vector64 source, T* destination) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector64BaseType(); + + if (((nuint)destination % Alignment) != 0) + { + throw new AccessViolationException(); + } + + *(Vector64*)destination = source; + } + + /// Stores a vector at the given aligned destination. + /// The vector that will be stored. + /// The aligned destination at which will be stored. + /// The type of the elements in the vector. + /// This method may bypass the cache on certain platforms. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void StoreAlignedNonTemporal(this Vector64 source, T* destination) + where T : unmanaged + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector64BaseType(); + + if (((nuint)destination % Alignment) != 0) + { + throw new AccessViolationException(); + } + + *(Vector64*)destination = source; + } + + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination at which will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StoreUnsafe(this Vector64 source, ref T destination) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector64BaseType(); + Unsafe.WriteUnaligned(ref Unsafe.As(ref destination), source); + } + + /// Stores a vector at the given destination. + /// The vector that will be stored. + /// The destination to which will be added before the vector will be stored. + /// The element offset from from which the vector will be stored. + /// The type of the elements in the vector. + [Intrinsic] + [CLSCompliant(false)] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void StoreUnsafe(this Vector64 source, ref T destination, nuint elementOffset) + where T : struct + { + ThrowHelper.ThrowForUnsupportedIntrinsicsVector64BaseType(); + destination = ref Unsafe.Add(ref destination, (nint)elementOffset); + Unsafe.WriteUnaligned(ref Unsafe.As(ref destination), source); + } + /// Subtracts two vectors to compute their difference. /// The vector from which will be subtracted. /// The vector to subtract from . @@ -2072,6 +2730,24 @@ public static Vector64 Sqrt(Vector64 vector) public static Vector64 Subtract(Vector64 left, Vector64 right) where T : struct => left - right; + /// Computes the sum of all elements in a vector. + /// The vector whose elements will be summed. + /// The type of the elements in the vector. + /// The sum of all elements in . + [Intrinsic] + public static T Sum(Vector64 vector) + where T : struct + { + T sum = default; + + for (int index = 0; index < Vector64.Count; index++) + { + sum = Scalar.Add(sum, vector.GetElementUnsafe(index)); + } + + return sum; + } + /// Converts the given vector to a scalar containing the value of the first element. /// The type of the input vector. /// The vector to get the first element from. @@ -2241,7 +2917,7 @@ internal static Vector64 WidenLower(Vector64 source) for (int i = 0; i < Vector64.Count; i++) { - var value = (ushort)source.GetElementUnsafe(i); + ushort value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -2255,7 +2931,7 @@ internal static unsafe Vector64 WidenLower(Vector64 source) for (int i = 0; i < Vector64.Count; i++) { - var value = (int)source.GetElementUnsafe(i); + int value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -2269,7 +2945,7 @@ internal static unsafe Vector64 WidenLower(Vector64 source) for (int i = 0; i < Vector64.Count; i++) { - var value = (long)source.GetElementUnsafe(i); + long value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -2283,7 +2959,7 @@ internal static unsafe Vector64 WidenLower(Vector64 source) for (int i = 0; i < Vector64.Count; i++) { - var value = (short)source.GetElementUnsafe(i); + short value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -2297,7 +2973,7 @@ internal static unsafe Vector64 WidenLower(Vector64 source) for (int i = 0; i < Vector64.Count; i++) { - var value = (double)source.GetElementUnsafe(i); + double value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -2311,7 +2987,7 @@ internal static unsafe Vector64 WidenLower(Vector64 source) for (int i = 0; i < Vector64.Count; i++) { - var value = (uint)source.GetElementUnsafe(i); + uint value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -2325,7 +3001,7 @@ internal static unsafe Vector64 WidenLower(Vector64 source) for (int i = 0; i < Vector64.Count; i++) { - var value = (ulong)source.GetElementUnsafe(i); + ulong value = source.GetElementUnsafe(i); lower.SetElementUnsafe(i, value); } @@ -2339,7 +3015,7 @@ internal static Vector64 WidenUpper(Vector64 source) for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (ushort)source.GetElementUnsafe(i); + ushort value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector64.Count, value); } @@ -2353,7 +3029,7 @@ internal static unsafe Vector64 WidenUpper(Vector64 source) for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (int)source.GetElementUnsafe(i); + int value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector64.Count, value); } @@ -2367,7 +3043,7 @@ internal static unsafe Vector64 WidenUpper(Vector64 source) for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (long)source.GetElementUnsafe(i); + long value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector64.Count, value); } @@ -2381,7 +3057,7 @@ internal static unsafe Vector64 WidenUpper(Vector64 source) for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (short)source.GetElementUnsafe(i); + short value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector64.Count, value); } @@ -2395,7 +3071,7 @@ internal static unsafe Vector64 WidenUpper(Vector64 source) for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (double)source.GetElementUnsafe(i); + double value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector64.Count, value); } @@ -2409,7 +3085,7 @@ internal static unsafe Vector64 WidenUpper(Vector64 source) for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (uint)source.GetElementUnsafe(i); + uint value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector64.Count, value); } @@ -2423,7 +3099,7 @@ internal static unsafe Vector64 WidenUpper(Vector64 source) for (int i = Vector64.Count; i < Vector64.Count; i++) { - var value = (ulong)source.GetElementUnsafe(i); + ulong value = source.GetElementUnsafe(i); upper.SetElementUnsafe(i - Vector64.Count, value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector64_1.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector64_1.cs index 4130c422389e5..e8332e0813b40 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector64_1.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Vector64_1.cs @@ -52,6 +52,8 @@ internal static bool IsTypeSupported (typeof(T) == typeof(short)) || (typeof(T) == typeof(int)) || (typeof(T) == typeof(long)) || + (typeof(T) == typeof(nint)) || + (typeof(T) == typeof(nuint)) || (typeof(T) == typeof(sbyte)) || (typeof(T) == typeof(float)) || (typeof(T) == typeof(ushort)) || @@ -99,7 +101,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Add(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Add(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -147,7 +149,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Divide(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Divide(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -206,7 +208,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -224,7 +226,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Multiply(left.GetElementUnsafe(index), right); + T value = Scalar.Multiply(left.GetElementUnsafe(index), right); result.SetElementUnsafe(index, value); } @@ -258,7 +260,7 @@ internal unsafe string DisplayString for (int index = 0; index < Count; index++) { - var value = Scalar.Subtract(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); + T value = Scalar.Subtract(left.GetElementUnsafe(index), right.GetElementUnsafe(index)); result.SetElementUnsafe(index, value); } @@ -312,7 +314,7 @@ public override int GetHashCode() for (int i = 0; i < Count; i++) { - var value = this.GetElement(i); + T value = this.GetElement(i); hashCode.Add(value); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs index b05714fd92cca..289bb93be4b1e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs @@ -706,7 +706,7 @@ private static void OnAssemblyLoad(RuntimeAssembly assembly) } // This method is called by the VM. - private static RuntimeAssembly? OnResourceResolve(RuntimeAssembly assembly, string resourceName) + internal static RuntimeAssembly? OnResourceResolve(RuntimeAssembly assembly, string resourceName) { return InvokeResolveEvent(ResourceResolve, assembly, resourceName); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs index 6bc4bf0ea4d41..c96729d8af4c8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/FrameworkName.cs @@ -161,7 +161,7 @@ public FrameworkName(string frameworkName) string component = components[i]; int separatorIndex = component.IndexOf(KeyValueSeparator); - if (separatorIndex == -1 || separatorIndex != component.LastIndexOf(KeyValueSeparator)) + if (separatorIndex < 0 || separatorIndex != component.LastIndexOf(KeyValueSeparator)) { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, nameof(frameworkName)); } diff --git a/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs b/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs index 5783792346b0c..8ad94b514bfa1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs +++ b/src/libraries/System.Private.CoreLib/src/System/RuntimeType.cs @@ -459,7 +459,7 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) } #endif // FEATURE_COMINTEROP - if (namedParams != null && Array.IndexOf(namedParams, null!) != -1) + if (namedParams != null && Array.IndexOf(namedParams, null!) >= 0) throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams)); int argCnt = (providedArgs != null) ? providedArgs.Length : 0; diff --git a/src/libraries/System.Private.CoreLib/src/System/SR.cs b/src/libraries/System.Private.CoreLib/src/System/SR.cs index 902dc7a590de2..550e972950de0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SR.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SR.cs @@ -51,7 +51,7 @@ private static string InternalGetResourceString(string key) // Are we recursively looking up the same resource? Note - our backout code will set // the ResourceHelper's currentlyLoading stack to null if an exception occurs. - if (_currentlyLoading != null && _currentlyLoading.Count > 0 && _currentlyLoading.LastIndexOf(key) != -1) + if (_currentlyLoading != null && _currentlyLoading.Count > 0 && _currentlyLoading.LastIndexOf(key) >= 0) { // We can start infinitely recursing for one resource lookup, // then during our failure reporting, start infinitely recursing again. diff --git a/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs b/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs index b714b64dc26cb..f48c702651fec 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Security/SecurityElement.cs @@ -18,9 +18,6 @@ public sealed class SecurityElement private const int AttributesTypical = 4 * 2; // 4 attributes, times 2 strings per attribute private const int ChildrenTypical = 1; - private static readonly char[] s_tagIllegalCharacters = new char[] { ' ', '<', '>' }; - private static readonly char[] s_textIllegalCharacters = new char[] { '<', '>' }; - private static readonly char[] s_valueIllegalCharacters = new char[] { '<', '>', '\"' }; private static readonly char[] s_escapeChars = new char[] { '<', '>', '\"', '\'', '&' }; private static readonly string[] s_escapeStringPairs = new string[] { @@ -298,34 +295,17 @@ public SecurityElement Copy() return element; } - public static bool IsValidTag([NotNullWhen(true)] string? tag) - { - if (tag == null) - return false; - - return tag.IndexOfAny(s_tagIllegalCharacters) == -1; - } - - public static bool IsValidText([NotNullWhen(true)] string? text) - { - if (text == null) - return false; + public static bool IsValidTag([NotNullWhen(true)] string? tag) => + tag != null && tag.AsSpan().IndexOfAny(' ', '<', '>') < 0; - return text.IndexOfAny(s_textIllegalCharacters) == -1; - } - - public static bool IsValidAttributeName([NotNullWhen(true)] string? name) - { - return IsValidTag(name); - } + public static bool IsValidText([NotNullWhen(true)] string? text) => + text != null && text.AsSpan().IndexOfAny('<', '>') < 0; - public static bool IsValidAttributeValue([NotNullWhen(true)] string? value) - { - if (value == null) - return false; + public static bool IsValidAttributeName([NotNullWhen(true)] string? name) => + IsValidTag(name); - return value.IndexOfAny(s_valueIllegalCharacters) == -1; - } + public static bool IsValidAttributeValue([NotNullWhen(true)] string? value) => + value != null && value.AsSpan().IndexOfAny('<', '>', '\"') < 0; private static string GetEscapeSequence(char c) { @@ -361,7 +341,7 @@ private static string GetEscapeSequence(char c) { index = str.IndexOfAny(s_escapeChars, newIndex); - if (index == -1) + if (index < 0) { if (sb == null) return str; @@ -425,7 +405,7 @@ private static string GetUnescapeSequence(string str, int index, out int newInde { index = str.IndexOf('&', newIndex); - if (index == -1) + if (index < 0) { if (sb == null) return str; diff --git a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Byte.cs b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Byte.cs index 05a52499925bf..e94b1dfe672b2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Byte.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Byte.cs @@ -32,7 +32,7 @@ public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte { // Do a quick search for the first element of "value". int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, offset), valueHead, remainingSearchSpaceLength); - if (relativeIndex == -1) + if (relativeIndex < 0) break; remainingSearchSpaceLength -= relativeIndex; @@ -430,7 +430,7 @@ public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref b // Do a quick search for the first element of "value". int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength); - if (relativeIndex == -1) + if (relativeIndex < 0) break; // Found the first element of "value". See if the tail matches. diff --git a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Char.cs b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Char.cs index 0c13e74367414..753e5301b503b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Char.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.Char.cs @@ -32,7 +32,7 @@ public static int IndexOf(ref char searchSpace, int searchSpaceLength, ref char { // Do a quick search for the first element of "value". int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength); - if (relativeIndex == -1) + if (relativeIndex < 0) break; remainingSearchSpaceLength -= relativeIndex; diff --git a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs index 684bce9d96f2f..91d2a34a47796 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs @@ -208,7 +208,7 @@ public static int IndexOf(ref T searchSpace, int searchSpaceLength, ref T val // Do a quick search for the first element of "value". int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength); - if (relativeIndex == -1) + if (relativeIndex < 0) break; index += relativeIndex; @@ -788,7 +788,7 @@ public static int LastIndexOf(ref T searchSpace, int searchSpaceLength, ref T // Do a quick search for the first element of "value". int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength); - if (relativeIndex == -1) + if (relativeIndex < 0) break; // Found the first element of "value". See if the tail matches. diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs index 9d068b4da0bc9..6a059351f376a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs @@ -683,6 +683,18 @@ public bool Equals([NotNullWhen(true)] string? value, StringComparison compariso // Determines whether two Strings match. public static bool Equals(string? a, string? b) { + // Transform 'str == ""' to 'str != null && str.Length == 0' if either a or b are jit-time + // constants. Otherwise, these two blocks are eliminated + if (RuntimeHelpers.IsKnownConstant(a) && a != null && a.Length == 0) + { + return b != null && b.Length == 0; + } + + if (RuntimeHelpers.IsKnownConstant(b) && b != null && b.Length == 0) + { + return a != null && a.Length == 0; + } + if (object.ReferenceEquals(a, b)) { return true; @@ -1013,7 +1025,14 @@ public bool StartsWith(string value, bool ignoreCase, CultureInfo? culture) return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } - public bool StartsWith(char value) => Length != 0 && _firstChar == value; + public bool StartsWith(char value) + { + if (RuntimeHelpers.IsKnownConstant(value) && value != '\0') + { + return _firstChar == value; + } + return Length != 0 && _firstChar == value; + } internal static void CheckStringComparison(StringComparison comparisonType) { diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs index d208eb3bedf63..0143c030432f5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs @@ -1087,7 +1087,7 @@ public string Replace(string oldValue, string? newValue) while (true) { int pos = SpanHelpers.IndexOf(ref Unsafe.Add(ref _firstChar, i), c, Length - i); - if (pos == -1) + if (pos < 0) { break; } @@ -1102,7 +1102,7 @@ public string Replace(string oldValue, string? newValue) while (true) { int pos = SpanHelpers.IndexOf(ref Unsafe.Add(ref _firstChar, i), Length - i, ref oldValue._firstChar, oldValue.Length); - if (pos == -1) + if (pos < 0) { break; } @@ -1683,12 +1683,13 @@ private void MakeSeparatorList(ReadOnlySpan separators, ref ValueListBuild { ProbabilisticMap map = default; uint* charMap = (uint*)↦ - InitializeProbabilisticMap(charMap, separators); + ProbabilisticMap.Initialize(charMap, separators); for (int i = 0; i < Length; i++) { char c = this[i]; - if (IsCharBitSet(charMap, (byte)c) && IsCharBitSet(charMap, (byte)(c >> 8)) && + if (ProbabilisticMap.IsCharBitSet(charMap, (byte)c) && + ProbabilisticMap.IsCharBitSet(charMap, (byte)(c >> 8)) && separators.Contains(c)) { sepListBuilder.Append(i); diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Searching.cs b/src/libraries/System.Private.CoreLib/src/System/String.Searching.cs index c7aaa59d72e25..5c1d4c3426d5a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Searching.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Searching.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; -using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System @@ -42,7 +41,7 @@ public bool Contains(char value, StringComparison comparisonType) public int IndexOf(char value, int startIndex) { - return IndexOf(value, startIndex, this.Length - startIndex); + return IndexOf(value, startIndex, Length - startIndex); } public int IndexOf(char value, StringComparison comparisonType) @@ -71,14 +70,18 @@ public int IndexOf(char value, StringComparison comparisonType) public unsafe int IndexOf(char value, int startIndex, int count) { if ((uint)startIndex > (uint)Length) - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); + } if ((uint)count > (uint)(Length - startIndex)) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); + } int result = SpanHelpers.IndexOf(ref Unsafe.Add(ref _firstChar, startIndex), value, count); - return result == -1 ? result : result + startIndex; + return result < 0 ? result : result + startIndex; } // Returns the index of the first occurrence of any specified character in the current instance. @@ -86,138 +89,39 @@ public unsafe int IndexOf(char value, int startIndex, int count) // public int IndexOfAny(char[] anyOf) { - return IndexOfAny(anyOf, 0, this.Length); + if (anyOf is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.anyOf); + } + + return new ReadOnlySpan(ref _firstChar, Length).IndexOfAny(anyOf); } public int IndexOfAny(char[] anyOf, int startIndex) { - return IndexOfAny(anyOf, startIndex, this.Length - startIndex); + return IndexOfAny(anyOf, startIndex, Length - startIndex); } public int IndexOfAny(char[] anyOf, int startIndex, int count) { - if (anyOf == null) - throw new ArgumentNullException(nameof(anyOf)); - - if ((uint)startIndex > (uint)Length) - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); - - if ((uint)count > (uint)(Length - startIndex)) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); - - if (anyOf.Length > 0 && anyOf.Length <= 5) - { - // The ReadOnlySpan.IndexOfAny extension is vectorized for values of 1 - 5 in length - int result = new ReadOnlySpan(ref Unsafe.Add(ref _firstChar, startIndex), count).IndexOfAny(anyOf); - return result == -1 ? result : result + startIndex; - } - else if (anyOf.Length > 5) - { - // Use Probabilistic Map - return IndexOfCharArray(anyOf, startIndex, count); - } - else // anyOf.Length == 0 + if (anyOf is null) { - return -1; + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.anyOf); } - } - - private unsafe int IndexOfCharArray(char[] anyOf, int startIndex, int count) - { - // use probabilistic map, see InitializeProbabilisticMap - ProbabilisticMap map = default; - uint* charMap = (uint*)↦ - InitializeProbabilisticMap(charMap, anyOf); - - fixed (char* pChars = &_firstChar) - { - char* pCh = pChars + startIndex; - - while (count > 0) - { - int thisChar = *pCh; - - if (IsCharBitSet(charMap, (byte)thisChar) && - IsCharBitSet(charMap, (byte)(thisChar >> 8)) && - ArrayContains((char)thisChar, anyOf)) - { - return (int)(pCh - pChars); - } - - count--; - pCh++; - } - - return -1; - } - } - - private const int PROBABILISTICMAP_BLOCK_INDEX_MASK = 0x7; - private const int PROBABILISTICMAP_BLOCK_INDEX_SHIFT = 0x3; - private const int PROBABILISTICMAP_SIZE = 0x8; - - // A probabilistic map is an optimization that is used in IndexOfAny/ - // LastIndexOfAny methods. The idea is to create a bit map of the characters we - // are searching for and use this map as a "cheap" check to decide if the - // current character in the string exists in the array of input characters. - // There are 256 bits in the map, with each character mapped to 2 bits. Every - // character is divided into 2 bytes, and then every byte is mapped to 1 bit. - // The character map is an array of 8 integers acting as map blocks. The 3 lsb - // in each byte in the character is used to index into this map to get the - // right block, the value of the remaining 5 msb are used as the bit position - // inside this block. - private static unsafe void InitializeProbabilisticMap(uint* charMap, ReadOnlySpan anyOf) - { - bool hasAscii = false; - uint* charMapLocal = charMap; // https://github.com/dotnet/runtime/issues/9040 - - for (int i = 0; i < anyOf.Length; ++i) + if ((uint)startIndex > (uint)Length) { - int c = anyOf[i]; - - // Map low bit - SetCharBit(charMapLocal, (byte)c); - - // Map high bit - c >>= 8; - - if (c == 0) - { - hasAscii = true; - } - else - { - SetCharBit(charMapLocal, (byte)c); - } + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } - if (hasAscii) + if ((uint)count > (uint)(Length - startIndex)) { - // Common to search for ASCII symbols. Just set the high value once. - charMapLocal[0] |= 1u; + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } - } - private static bool ArrayContains(char searchChar, char[] anyOf) - { - for (int i = 0; i < anyOf.Length; i++) - { - if (anyOf[i] == searchChar) - return true; - } + int result = new ReadOnlySpan(ref Unsafe.Add(ref _firstChar, startIndex), count).IndexOfAny(anyOf); - return false; - } - - private static unsafe bool IsCharBitSet(uint* charMap, byte value) - { - return (charMap[(uint)value & PROBABILISTICMAP_BLOCK_INDEX_MASK] & (1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT))) != 0; - } - - private static unsafe void SetCharBit(uint* charMap, byte value) - { - charMap[(uint)value & PROBABILISTICMAP_BLOCK_INDEX_MASK] |= 1u << (value >> PROBABILISTICMAP_BLOCK_INDEX_SHIFT); + return result < 0 ? result : result + startIndex; } /* @@ -322,12 +226,12 @@ public int IndexOf(string value, int startIndex, int count) public int IndexOf(string value, StringComparison comparisonType) { - return IndexOf(value, 0, this.Length, comparisonType); + return IndexOf(value, 0, Length, comparisonType); } public int IndexOf(string value, int startIndex, StringComparison comparisonType) { - return IndexOf(value, startIndex, this.Length - startIndex, comparisonType); + return IndexOf(value, startIndex, Length - startIndex, comparisonType); } public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType) @@ -370,18 +274,24 @@ public int LastIndexOf(char value, int startIndex) public unsafe int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) + { return -1; + } if ((uint)startIndex >= (uint)Length) - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); + } if ((uint)count > (uint)startIndex + 1) - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); + { + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); + } int startSearchAt = startIndex + 1 - count; int result = SpanHelpers.LastIndexOf(ref Unsafe.Add(ref _firstChar, startSearchAt), value, count); - return result == -1 ? result : result + startSearchAt; + return result < 0 ? result : result + startSearchAt; } // Returns the index of the last occurrence of any specified character in the current instance. @@ -391,7 +301,12 @@ public unsafe int LastIndexOf(char value, int startIndex, int count) // public int LastIndexOfAny(char[] anyOf) { - return LastIndexOfAny(anyOf, this.Length - 1, this.Length); + if (anyOf is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.anyOf); + } + + return new ReadOnlySpan(ref _firstChar, Length).LastIndexOfAny(anyOf); } public int LastIndexOfAny(char[] anyOf, int startIndex) @@ -401,65 +316,30 @@ public int LastIndexOfAny(char[] anyOf, int startIndex) public unsafe int LastIndexOfAny(char[] anyOf, int startIndex, int count) { - if (anyOf == null) - throw new ArgumentNullException(nameof(anyOf)); + if (anyOf is null) + { + ThrowHelper.ThrowArgumentNullException(ExceptionArgument.anyOf); + } if (Length == 0) + { return -1; + } if ((uint)startIndex >= (uint)Length) { - throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index); + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if ((count < 0) || ((count - 1) > startIndex)) { - throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); - } - - if (anyOf.Length > 1) - { - return LastIndexOfCharArray(anyOf, startIndex, count); - } - else if (anyOf.Length == 1) - { - return LastIndexOf(anyOf[0], startIndex, count); - } - else // anyOf.Length == 0 - { - return -1; + ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } - } - - private unsafe int LastIndexOfCharArray(char[] anyOf, int startIndex, int count) - { - // use probabilistic map, see InitializeProbabilisticMap - ProbabilisticMap map = default; - uint* charMap = (uint*)↦ - InitializeProbabilisticMap(charMap, anyOf); - - fixed (char* pChars = &_firstChar) - { - char* pCh = pChars + startIndex; - - while (count > 0) - { - int thisChar = *pCh; - - if (IsCharBitSet(charMap, (byte)thisChar) && - IsCharBitSet(charMap, (byte)(thisChar >> 8)) && - ArrayContains((char)thisChar, anyOf)) - { - return (int)(pCh - pChars); - } - - count--; - pCh--; - } + int startSearchAt = startIndex + 1 - count; + int result = new ReadOnlySpan(ref Unsafe.Add(ref _firstChar, startSearchAt), count).LastIndexOfAny(anyOf); - return -1; - } + return result < 0 ? result : result + startSearchAt; } // Returns the index of the last occurrence of any character in value in the current instance. @@ -469,7 +349,7 @@ private unsafe int LastIndexOfCharArray(char[] anyOf, int startIndex, int count) // public int LastIndexOf(string value) { - return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture); + return LastIndexOf(value, Length - 1, Length, StringComparison.CurrentCulture); } public int LastIndexOf(string value, int startIndex) @@ -484,7 +364,7 @@ public int LastIndexOf(string value, int startIndex, int count) public int LastIndexOf(string value, StringComparison comparisonType) { - return LastIndexOf(value, this.Length - 1, this.Length, comparisonType); + return LastIndexOf(value, Length - 1, Length, comparisonType); } public int LastIndexOf(string value, int startIndex, StringComparison comparisonType) @@ -516,8 +396,5 @@ public int LastIndexOf(string value, int startIndex, int count, StringComparison : new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } - - [StructLayout(LayoutKind.Explicit, Size = PROBABILISTICMAP_SIZE * sizeof(uint))] - private struct ProbabilisticMap { } } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index 5957628a6ac84..1f58c7185f6c6 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -2063,13 +2063,16 @@ public StringBuilder Replace(char oldChar, char newChar, int startIndex, int cou { int curInChunk = Math.Max(startIndexInChunk, 0); int endInChunk = Math.Min(chunk.m_ChunkLength, endIndexInChunk); - while (curInChunk < endInChunk) + + Span span = chunk.m_ChunkChars.AsSpan(curInChunk, endInChunk - curInChunk); + int i; + while ((i = span.IndexOf(oldChar)) >= 0) { - if (chunk.m_ChunkChars[curInChunk] == oldChar) - chunk.m_ChunkChars[curInChunk] = newChar; - curInChunk++; + span[i] = newChar; + span = span.Slice(i + 1); } } + if (startIndexInChunk >= 0) { break; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Windows.cs index c49e9dce80c38..34fec19463a81 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelLifoSemaphore.Windows.cs @@ -45,7 +45,7 @@ public bool WaitCore(int timeoutMs) { Debug.Assert(timeoutMs >= -1); - bool success = Interop.Kernel32.GetQueuedCompletionStatus(_completionPort, out int numberOfBytes, out UIntPtr completionKey, out IntPtr pointerToOverlapped, timeoutMs); + bool success = Interop.Kernel32.GetQueuedCompletionStatus(_completionPort, out _, out _, out _, timeoutMs); Debug.Assert(success || (Marshal.GetLastPInvokeError() == WaitHandle.WaitTimeout)); return success; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs index bd7d3d857e0ef..ad932e0cf7a49 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.WaitThread.cs @@ -442,9 +442,9 @@ private void UnregisterWait(RegisteredWaitHandle handle, bool blocking) try { // If this handle is not already pending removal and hasn't already been removed - if (Array.IndexOf(_registeredWaits, handle) != -1) + if (Array.IndexOf(_registeredWaits, handle) >= 0) { - if (Array.IndexOf(_pendingRemoves, handle) == -1) + if (Array.IndexOf(_pendingRemoves, handle) < 0) { _pendingRemoves[_numPendingRemoves++] = handle; _changeHandlesEvent.Set(); // Tell the wait thread that there are changes pending. diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/CachedCompletedInt32Task.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/CachedCompletedInt32Task.cs new file mode 100644 index 0000000000000..080253a37dc5a --- /dev/null +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/CachedCompletedInt32Task.cs @@ -0,0 +1,36 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; +using System.IO; +using System.Runtime.CompilerServices; + +namespace System.Threading.Tasks +{ + /// + /// Encapsulates the logic of caching the last synchronously completed task of integer. + /// Used in classes like to reduce allocations. + /// + internal struct CachedCompletedInt32Task + { + private Task? _task; + + /// Gets a completed whose result is . + /// This method will try to return an already cached task if available. + /// The result value for which a is needed. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public Task GetTask(int result) + { + if (_task is Task task) + { + Debug.Assert(task.IsCompletedSuccessfully, "Expected that a stored last task completed successfully"); + if (task.Result == result) + { + return task; + } + } + + return _task = Task.FromResult(result); + } + } +} diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs index 96a13501ce91f..6e319542ce488 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @@ -4552,7 +4552,7 @@ internal void RemoveContinuation(object continuationObject) // could be TaskCont // Find continuationObject in the continuation list int index = continuationsLocalListRef.IndexOf(continuationObject); - if (index != -1) + if (index >= 0) { // null out that TaskContinuation entry, which will be interpreted as "to be cleaned up" continuationsLocalListRef[index] = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs index 6a4b728728a56..45a665b8830cf 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs @@ -39,7 +39,7 @@ public static void Add(WorkStealingQueue queue) while (true) { WorkStealingQueue[] oldQueues = _queues; - Debug.Assert(Array.IndexOf(oldQueues, queue) == -1); + Debug.Assert(Array.IndexOf(oldQueues, queue) < 0); var newQueues = new WorkStealingQueue[oldQueues.Length + 1]; Array.Copy(oldQueues, newQueues, oldQueues.Length); @@ -63,7 +63,7 @@ public static void Remove(WorkStealingQueue queue) } int pos = Array.IndexOf(oldQueues, queue); - if (pos == -1) + if (pos < 0) { Debug.Fail("Should have found the queue"); return; diff --git a/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs b/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs index e5f4e144dd461..01e4a44dfc19d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ThrowHelper.cs @@ -852,6 +852,8 @@ private static string GetArgumentName(ExceptionArgument argument) return "offset"; case ExceptionArgument.stream: return "stream"; + case ExceptionArgument.anyOf: + return "anyOf"; default: Debug.Fail("The enum value is not defined, please check the ExceptionArgument Enum."); return ""; @@ -1119,7 +1121,8 @@ internal enum ExceptionArgument buffer, buffers, offset, - stream + stream, + anyOf, } // diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.NonAndroid.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.NonAndroid.cs index 0c3e38566825c..e1dc5f1434e9e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.NonAndroid.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.NonAndroid.cs @@ -89,15 +89,15 @@ private static List GetTimeZoneIds() // the format of the line is "country-code \t coordinates \t TimeZone Id \t comments" int firstTabIndex = zoneTabFileLine.IndexOf('\t'); - if (firstTabIndex != -1) + if (firstTabIndex >= 0) { int secondTabIndex = zoneTabFileLine.IndexOf('\t', firstTabIndex + 1); - if (secondTabIndex != -1) + if (secondTabIndex >= 0) { string timeZoneId; int startIndex = secondTabIndex + 1; int thirdTabIndex = zoneTabFileLine.IndexOf('\t', startIndex); - if (thirdTabIndex != -1) + if (thirdTabIndex >= 0) { int length = thirdTabIndex - startIndex; timeZoneId = zoneTabFileLine.Substring(startIndex, length); diff --git a/src/libraries/System.Private.CoreLib/src/System/Version.cs b/src/libraries/System.Private.CoreLib/src/System/Version.cs index 469da80ebe7cf..43d3bb34b098e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Version.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Version.cs @@ -304,11 +304,11 @@ public static bool TryParse(ReadOnlySpan input, [NotNullWhen(true)] out Ve // We musn't have any separators after build. int buildEnd = -1; int minorEnd = input.Slice(majorEnd + 1).IndexOf('.'); - if (minorEnd != -1) + if (minorEnd >= 0) { minorEnd += (majorEnd + 1); buildEnd = input.Slice(minorEnd + 1).IndexOf('.'); - if (buildEnd != -1) + if (buildEnd >= 0) { buildEnd += (minorEnd + 1); if (input.Slice(buildEnd + 1).Contains('.')) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs index 87625a843be20..697f9e3fcd4b3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs @@ -168,7 +168,7 @@ internal Delegate EndMethod() EmitSourceLabel("} End method"); Ret(); - Delegate? retVal = null; + Delegate? retVal; retVal = _dynamicMethod.CreateDelegate(_delegateType); _dynamicMethod = null!; _delegateType = null!; @@ -608,7 +608,7 @@ private static bool IsStruct(Type objType) internal Type LoadMember(MemberInfo memberInfo) { - Type? memberType = null; + Type? memberType; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs index f5ecf0a48e1cb..3715ea0835569 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs @@ -916,7 +916,7 @@ internal Type GetCollectionElementType() Debug.Assert(Kind != CollectionKind.Array, "GetCollectionElementType should not be called on Arrays"); Debug.Assert(GetEnumeratorMethod != null, "GetEnumeratorMethod should be non-null for non-Arrays"); - Type? enumeratorType = null; + Type? enumeratorType; if (Kind == CollectionKind.GenericDictionary) { Type[] keyValueTypes = ItemType.GetGenericArguments(); @@ -1012,8 +1012,7 @@ internal static bool IsCollectionInterface(Type type) [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsCollection(Type type) { - Type? itemType; - return IsCollection(type, out itemType); + return IsCollection(type, out _); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] @@ -1025,8 +1024,7 @@ internal static bool IsCollection(Type type, [NotNullWhen(true)] out Type? itemT [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsCollection(Type type, bool constructorRequired) { - Type? itemType; - return IsCollectionHelper(type, out itemType, constructorRequired); + return IsCollectionHelper(type, out _, constructorRequired); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] @@ -1037,21 +1035,18 @@ private static bool IsCollectionHelper(Type type, [NotNullWhen(true)] out Type? itemType = type.GetElementType()!; return true; } - DataContract? dataContract; - return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired); + return IsCollectionOrTryCreate(type, tryCreate: false, out _, out itemType, constructorRequired); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool TryCreate(Type type, [NotNullWhen(true)] out DataContract? dataContract) { - Type itemType; - return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, true /*constructorRequired*/); + return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: true); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool CreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { - Type itemType; if (type.IsArray) { dataContract = new CollectionDataContract(type); @@ -1059,7 +1054,7 @@ internal static bool CreateGetOnlyCollectionDataContract(Type type, [NotNullWhen } else { - return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, false /*constructorRequired*/); + return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: false); } } @@ -1069,7 +1064,6 @@ internal static bool TryCreateGetOnlyCollectionDataContract(Type type, [NotNullW dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract == null) { - Type itemType; if (type.IsArray) { dataContract = new CollectionDataContract(type); @@ -1077,7 +1071,7 @@ internal static bool TryCreateGetOnlyCollectionDataContract(Type type, [NotNullW } else { - return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, false /*constructorRequired*/); + return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: false); } } else diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index 1f0b0782bca33..4480e5f7cb3d6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -1328,8 +1328,7 @@ internal static bool IsValidNCName(string name) [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static XmlQualifiedName GetStableName(Type type) { - bool hasDataContract; - return GetStableName(type, out hasDataContract); + return GetStableName(type, out _); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] @@ -1362,7 +1361,7 @@ internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContra [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute) { - string? name = null, ns = null; + string? name, ns; if (dataContractAttribute.IsNameSetExplicitly) { name = dataContractAttribute.Name; @@ -1391,12 +1390,11 @@ private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttri [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static XmlQualifiedName GetNonDCTypeStableName(Type type) { - string? name = null, ns = null; + string? name, ns; Type? itemType; - CollectionDataContractAttribute? collectionContractAttribute; if (CollectionDataContract.IsCollection(type, out itemType)) - return GetCollectionStableName(type, itemType, out collectionContractAttribute); + return GetCollectionStableName(type, itemType, out _); name = GetDefaultStableLocalName(type); // ensures that ContractNamespaceAttribute is honored when used with non-attributed types @@ -1423,16 +1421,13 @@ private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, [NotNullWh } else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { - bool hasRoot; - XmlSchemaType? xsdType; XmlQualifiedName xmlTypeStableName; - SchemaExporter.GetXmlTypeInfo(type, out xmlTypeStableName, out xsdType, out hasRoot); + SchemaExporter.GetXmlTypeInfo(type, out xmlTypeStableName, out _, out _); stableName = xmlTypeStableName; } else if (type.IsArray) { - CollectionDataContractAttribute? collectionContractAttribute; - stableName = GetCollectionStableName(type, type.GetElementType()!, out collectionContractAttribute); + stableName = GetCollectionStableName(type, type.GetElementType()!, out _); } return stableName != null; } @@ -2265,8 +2260,8 @@ internal GenericNameProvider(string genericTypeName, object[] genericParams) _genericParams = new object[genericParams.Length]; genericParams.CopyTo(_genericParams, 0); - string name, ns; - DataContract.GetClrNameAndNamespace(genericTypeName, out name, out ns); + string name; + DataContract.GetClrNameAndNamespace(genericTypeName, out name, out _); _nestedParamCounts = DataContract.GetDataContractNameForGenericName(name, null); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs index 72229faaf8d3c..ca4047b2cc7fd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs @@ -382,7 +382,7 @@ internal void InternalWriteObjectContent(XmlWriterDelegator writer, object? grap } else { - XmlObjectSerializerWriteContext? context = null; + XmlObjectSerializerWriteContext? context; if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType))); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs index 61567c4faacf7..a9c7d36a652ac 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs @@ -121,7 +121,7 @@ public void Add(XmlQualifiedName name, DataContract dataContract) [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal void InternalAdd(XmlQualifiedName name, DataContract dataContract) { - DataContract? dataContractInSet = null; + DataContract? dataContractInSet; if (Contracts.TryGetValue(name, out dataContractInSet)) { if (!dataContractInSet.Equals(dataContract)) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs index a340de1f51644..148efe5f81fc8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs @@ -290,7 +290,7 @@ internal object ReadEnumValue(XmlReaderDelegator reader) // Read space-delimited values int startIndex = i; - int count = 0; + int count; for (; i < stringValue.Length; i++) { if (stringValue[i] == ' ') diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs index d0e9f8e118785..2e5368d568c73 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs @@ -22,8 +22,7 @@ internal void Add(string id, object? obj) if (_objectDictionary == null) _objectDictionary = new Dictionary(); - object? existingObject; - if (_objectDictionary.TryGetValue(id, out existingObject)) + if (_objectDictionary.ContainsKey(id)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.MultipleIdDefinition, id))); _objectDictionary.Add(id, obj); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs index 13be22414a5cb..453d2acc37ead 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs @@ -366,7 +366,7 @@ private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expec _ilg.Set(memberIndexLocal, memberCount); expectedElements.Load(memberCount); _ilg.Brfalse(throwDuplicateMemberLabel); - LocalBuilder? value = null; + LocalBuilder? value; if (dataMember.IsGetOnlyCollection) { _ilg.LoadAddress(_objectLocal); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs index 94089b749f4c3..cdee0af270ac9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs @@ -370,7 +370,7 @@ private void WriteCollection(CollectionDataContract collectionContract) } bool isDictionary = false, isGenericDictionary = false; - Type? enumeratorType = null; + Type? enumeratorType; Type[]? keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs index d7e72a18d01c6..4f3f51603c8a7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs @@ -110,8 +110,7 @@ internal static object ParseJsonNumber(string value, out TypeCode objectTypeCode private static object ParseJsonNumber(string value) { - TypeCode unusedTypeCode; - return ParseJsonNumber(value, out unusedTypeCode); + return ParseJsonNumber(value, out _); } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs index aea41cb1bdf6f..f4c03527b97ce 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs @@ -99,7 +99,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, Type elementType = collectionContract.GetCollectionElementType(); bool isDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary; - DataContract? itemContract = null; + DataContract? itemContract; JsonDataContract? jsonDataContract = null; if (isDictionary) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs index a4faf4835350c..3e24e963d84f6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs @@ -1507,7 +1507,7 @@ private void ReadServerTypeAttribute(bool consumedObjectChar) SkipWhitespaceInBufferReader(); SkipExpectedByteInBufferReader(JsonGlobals.QuoteByte); - buffer = BufferReader.GetBuffer(out offset, out offsetMax); + BufferReader.GetBuffer(out offset, out _); do { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs index 5648bf4734ced..b1cb4458d86b9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs @@ -47,7 +47,7 @@ public int GetId(object obj, ref bool newId) public int ReassignId(int oldObjId, object oldObj, object newObj) { bool isEmpty, isWrapped; - int position = FindElement(oldObj, out isEmpty, out isWrapped); + int position = FindElement(oldObj, out isEmpty, out _); if (isEmpty) return 0; int id = m_ids[position]; @@ -150,8 +150,8 @@ private void Rehash() object? obj = oldObjs[j]; if (obj != null) { - bool found, isWrapped; - int position = FindElement(obj, out found, out isWrapped); + bool isWrapped; + int position = FindElement(obj, out _, out isWrapped); m_objs[position] = obj; m_ids[position] = oldIds[j]; m_isWrapped[position] = isWrapped; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs index c82507311ae18..95b868eda105d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs @@ -87,7 +87,7 @@ public void ReflectionReadGetOnlyCollection(XmlReaderDelegator xmlReader, XmlObj } bool isReadOnlyCollection = true; - resultCollection = ReadCollectionItems(xmlReader, context, collectionItemName, collectionItemNamespace, collectionContract, resultCollection, isReadOnlyCollection); + ReadCollectionItems(xmlReader, context, collectionItemName, collectionItemNamespace, collectionContract, resultCollection, isReadOnlyCollection); } } @@ -103,7 +103,7 @@ private object ReflectionReadCollectionCore(XmlReaderDelegator xmlReader, XmlObj bool isArray = (collectionContract.Kind == CollectionKind.Array); int arraySize = context.GetArraySize(); - object? resultArray = null; + object? resultArray; if (isArray && ReflectionTryReadPrimitiveArray(xmlReader, context, collectionItemName, collectionItemNamespace, collectionContract.UnderlyingType, collectionContract.ItemType, arraySize, out resultArray)) { return resultArray; @@ -242,7 +242,7 @@ protected void ReflectionReadMember(XmlReaderDelegator xmlReader, XmlObjectSeria [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] protected object? ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract? primitiveContractForOriginalType = null) { - object? value = null; + object? value; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs index 48dccee71f7ba..47c2ee4241fa5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs @@ -736,7 +736,7 @@ internal static bool IsSpecialXmlType(Type type, [NotNullWhen(true)] out XmlQual hasRoot = true; if (type == Globals.TypeOfXmlElement || type == Globals.TypeOfXmlNodeArray) { - string? name = null; + string? name; if (type == Globals.TypeOfXmlElement) { xsdType = CreateAnyElementType(); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs index 14730cade7992..ea573ac1d803e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs @@ -135,10 +135,9 @@ internal XmlDataContractCriticalHelper( throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type)))); - XmlSchemaType? xsdType; bool hasRoot; XmlQualifiedName stableName; - SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot); + SchemaExporter.GetXmlTypeInfo(type, out stableName, out _, out hasRoot); this.StableName = stableName; this.HasRoot = hasRoot; XmlDictionary dictionary = new XmlDictionary(); @@ -356,7 +355,7 @@ internal IXmlSerializable ReflectionCreateXmlSerializable(Type type) } else { - object? o = null; + object? o; if (type == typeof(System.Xml.Linq.XElement)) { o = new System.Xml.Linq.XElement("default"); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs index 7d9cf66ee70f8..c6f0149d31f79 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs @@ -419,7 +419,7 @@ private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, _ilg.Set(requiredIndexLocal!, nextRequiredIndex); } - LocalBuilder? value = null; + LocalBuilder? value; if (dataMember.IsGetOnlyCollection) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs index 6c7b49690294a..c0793409e7bd8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs @@ -407,7 +407,7 @@ private void WriteCollection(CollectionDataContract collectionContract) } bool isDictionary = false, isGenericDictionary = false; - Type? enumeratorType = null; + Type? enumeratorType; Type[]? keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs index dff884dffdcbb..59e475d9e0164 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs @@ -885,7 +885,7 @@ private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string? dataC Read(xmlReader); } - while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) + while (xmlReader.MoveToContent() != XmlNodeType.EndElement) { if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs index e8b01329c3910..1dd59e61baed3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs @@ -94,8 +94,7 @@ internal override SerializationMode Mode if (assemblyName != null && typeName != null) { Assembly assembly; - Type type; - DataContract? tempDataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out type); + DataContract? tempDataContract = ResolveDataContractInSharedTypeMode(assemblyName, typeName, out assembly, out _); if (tempDataContract == null) { if (assembly == null) @@ -174,9 +173,7 @@ private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string { if (attributes.ClrAssembly != null && attributes.ClrType != null) { - Assembly assembly; - Type type; - return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out assembly, out type); + return ResolveDataContractInSharedTypeMode(attributes.ClrAssembly, attributes.ClrType, out _, out _); } } return null; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs index 8d21ec419b04b..3a05de1395bf2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs @@ -768,12 +768,12 @@ internal virtual XmlQualifiedName ReadContentAsQName() private XmlQualifiedName ParseQualifiedName(string str) { - string name, prefix; + string name; string? ns; if (str == null || str.Length == 0) name = ns = string.Empty; else - XmlObjectSerializerReadContext.ParseQualifiedName(str, this, out name, out ns, out prefix); + XmlObjectSerializerReadContext.ParseQualifiedName(str, this, out name, out ns, out _); return new XmlQualifiedName(name, ns); } @@ -807,7 +807,7 @@ internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context, { CheckExpectedArrayLength(context, arrayLength); array = new bool[arrayLength]; - int read = 0, offset = 0; + int read, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; @@ -837,7 +837,7 @@ internal virtual bool TryReadDateTimeArray(XmlObjectSerializerReadContext contex { CheckExpectedArrayLength(context, arrayLength); array = new DateTime[arrayLength]; - int read = 0, offset = 0; + int read, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; @@ -867,7 +867,7 @@ internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context, { CheckExpectedArrayLength(context, arrayLength); array = new decimal[arrayLength]; - int read = 0, offset = 0; + int read, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; @@ -897,7 +897,7 @@ internal bool TryReadInt32Array(XmlObjectSerializerReadContext context, { CheckExpectedArrayLength(context, arrayLength); array = new int[arrayLength]; - int read = 0, offset = 0; + int read, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; @@ -927,7 +927,7 @@ internal bool TryReadInt64Array(XmlObjectSerializerReadContext context, { CheckExpectedArrayLength(context, arrayLength); array = new long[arrayLength]; - int read = 0, offset = 0; + int read, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; @@ -957,7 +957,7 @@ internal bool TryReadSingleArray(XmlObjectSerializerReadContext context, { CheckExpectedArrayLength(context, arrayLength); array = new float[arrayLength]; - int read = 0, offset = 0; + int read, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; @@ -987,7 +987,7 @@ internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context, { CheckExpectedArrayLength(context, arrayLength); array = new double[arrayLength]; - int read = 0, offset = 0; + int read, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs index 1522ba1e25a95..05bffd65b03b2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs @@ -11,7 +11,7 @@ internal abstract class ArrayHelper public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, int maxArrayLength) { TArray[][]? arrays = null; - TArray[]? array = null; + TArray[]? array; int arrayCount = 0; int totalRead = 0; int count; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs index 09af5cbd9a501..d6de2307fb363 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs @@ -319,7 +319,7 @@ private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int int max = offset + Math.Min(count, BufferLength); // Encoding should be second "=", abort at first "?" - int i = 0; + int i; int eq = 0; for (i = offset + 2; i < max; i++) // Skip the "> 1); - XmlDictionaryString? xmlString; - if (!_session.TryLookup(sessionKey, out xmlString)) + if (!_session.TryLookup(sessionKey, out _)) { if (sessionKey < XmlDictionaryString.MinKey || sessionKey > XmlDictionaryString.MaxKey) XmlExceptionHelper.ThrowXmlDictionaryStringIDOutOfRange(_reader); @@ -1164,8 +1163,7 @@ public int ReadDictionaryKey() if (_dictionary == null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int staticKey = (key >> 1); - XmlDictionaryString? xmlString; - if (!_dictionary.TryLookup(staticKey, out xmlString)) + if (!_dictionary.TryLookup(staticKey, out _)) { if (staticKey < XmlDictionaryString.MinKey || staticKey > XmlDictionaryString.MaxKey) XmlExceptionHelper.ThrowXmlDictionaryStringIDOutOfRange(_reader); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs index 11dc79d1834fd..997c9fd2aa022 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs @@ -837,9 +837,7 @@ private void ResolvePrefix(ref Attribute attribute) private void ResolvePrefixes() { - int nsOffset; - int nsLength; - ResolvePrefix(_element.prefixOffset, _element.prefixLength, out nsOffset, out nsLength); + ResolvePrefix(_element.prefixOffset, _element.prefixLength, out _, out _); for (int i = 0; i < _attributeCount; i++) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs index 183029efc0d58..6d9595800eb58 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs @@ -209,7 +209,7 @@ public virtual void WriteValue(IStreamProvider value) if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.XmlInvalidStream)); int blockSize = 256; - int bytesRead = 0; + int bytesRead; byte[] block = new byte[blockSize]; while (true) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs index 292603012980d..fa033d03a9344 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs @@ -681,7 +681,7 @@ private void ReadQualifiedName(PrefixHandle prefix, StringHandle localName) int offsetMax; byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax); - int ch = 0; + int ch; int anyChar = 0; int prefixChar = 0; int prefixOffset = offset; @@ -736,7 +736,6 @@ private void ReadQualifiedName(PrefixHandle prefix, StringHandle localName) else { anyChar |= 0x80; - ch = 0; } localName.SetValue(localNameOffset, offset - localNameOffset); if (anyChar >= 0x80) @@ -1192,8 +1191,7 @@ private int ReadTextAndWatchForInvalidCharacters(byte[] buffer, int offset, int else { // Get enough bytes for us to process next character, then go back to top of while loop - int dummy; - BufferReader.GetBuffer(3, out dummy); + BufferReader.GetBuffer(3, out _); } } } @@ -1411,8 +1409,8 @@ public int LineNumber { get { - int row, column; - GetPosition(out row, out column); + int row; + GetPosition(out row, out _); return row; } } @@ -1421,8 +1419,8 @@ public int LinePosition { get { - int row, column; - GetPosition(out row, out column); + int column; + GetPosition(out _, out column); return column; } } diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs index c9b443e9c82ce..d31f1543ce76b 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs @@ -48,7 +48,7 @@ internal void AddInFlight() InFlightCounter++; if (InFlightCounter == 1) { - Debug.Assert(InFlight == null); + Debug.Assert(InFlight == null, "InFlight == null"); InFlight = GCHandle.Alloc(this, GCHandleType.Normal); } } @@ -61,12 +61,12 @@ internal void ReleaseInFlight() { lock (this) { - Debug.Assert(InFlightCounter != 0); + Debug.Assert(InFlightCounter != 0, "InFlightCounter != 0"); InFlightCounter--; if (InFlightCounter == 0) { - Debug.Assert(InFlight.HasValue); + Debug.Assert(InFlight.HasValue, "InFlight.HasValue"); InFlight.Value.Free(); InFlight = null; } diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.cs index 19cb346ad9bb4..33588095b3158 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.cs @@ -154,7 +154,7 @@ public void SetObjectProperty(string name, object value, bool createIfNotExists { AssertNotDisposed(); - object setPropResult = Interop.Runtime.SetObjectProperty(JSHandle, name, value, createIfNotExists, hasOwnProperty, out int exception); + Interop.Runtime.SetObjectProperty(JSHandle, name, value, createIfNotExists, hasOwnProperty, out int exception); if (exception != 0) throw new JSException($"Error setting {name} on (js-obj js '{JSHandle}')"); } diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.cs index 5f8b010ad1edb..4de1e1febc095 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Map.cs @@ -206,10 +206,9 @@ public bool MoveNext() if (_mapItemIterator == null) _mapItemIterator = (JSObject)_mapItemCollection._map.Invoke(_mapItemCollection._iterator); - var done = false; using (var result = (JSObject)_mapItemIterator.Invoke("next")) { - done = (bool)result.GetObjectProperty("done"); + bool done = (bool)result.GetObjectProperty("done"); if (!done) Current = result.GetObjectProperty("value"); return !done; diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs index 60f694e2b7cf3..4b5d072e8ac43 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/Runtime.cs @@ -49,14 +49,15 @@ private struct IntPtrAndHandle internal IntPtr ptr; [FieldOffset(0)] - internal RuntimeMethodHandle handle; + internal RuntimeMethodHandle methodHandle; [FieldOffset(0)] internal RuntimeTypeHandle typeHandle; } // see src/mono/wasm/driver.c MARSHAL_TYPE_xxx - public enum MarshalType : int { + public enum MarshalType : int + { NULL = 0, INT = 1, FP64 = 2, @@ -90,7 +91,8 @@ public enum MarshalType : int { } // see src/mono/wasm/driver.c MARSHAL_ERROR_xxx - public enum MarshalError : int { + public enum MarshalError : int + { BUFFER_TOO_SMALL = 512, NULL_CLASS_POINTER = 513, NULL_TYPE_POINTER = 514, @@ -98,13 +100,12 @@ public enum MarshalError : int { FIRST = BUFFER_TOO_SMALL } - public static string GetCallSignature(IntPtr methodHandle, object objForRuntimeType) + public static string GetCallSignature(IntPtr _methodHandle, object? objForRuntimeType) { - IntPtrAndHandle tmp = default(IntPtrAndHandle); - tmp.ptr = methodHandle; + var methodHandle = GetMethodHandleFromIntPtr(_methodHandle); - MethodBase? mb = objForRuntimeType == null ? MethodBase.GetMethodFromHandle(tmp.handle) : MethodBase.GetMethodFromHandle(tmp.handle, Type.GetTypeHandle(objForRuntimeType)); - if (mb == null) + MethodBase? mb = objForRuntimeType is null ? MethodBase.GetMethodFromHandle(methodHandle) : MethodBase.GetMethodFromHandle(methodHandle, Type.GetTypeHandle(objForRuntimeType)); + if (mb is null) return string.Empty; ParameterInfo[] parms = mb.GetParameters(); @@ -112,66 +113,163 @@ public static string GetCallSignature(IntPtr methodHandle, object objForRuntimeT if (parmsLength == 0) return string.Empty; - char[] res = new char[parmsLength]; + var result = new char[parmsLength]; + for (int i = 0; i < parmsLength; i++) + { + Type t = parms[i].ParameterType; + var mt = GetMarshalTypeFromType(t); + result[i] = GetCallSignatureCharacterForMarshalType(mt, null); + } + + return new string(result); + } + + private static RuntimeMethodHandle GetMethodHandleFromIntPtr(IntPtr ptr) + { + var temp = new IntPtrAndHandle { ptr = ptr }; + return temp.methodHandle; + } + + private static RuntimeTypeHandle GetTypeHandleFromIntPtr(IntPtr ptr) + { + var temp = new IntPtrAndHandle { ptr = ptr }; + return temp.typeHandle; + } + + internal static MarshalType GetMarshalTypeFromType(Type? type) + { + if (type is null) + return MarshalType.VOID; - for (int c = 0; c < parmsLength; c++) + var typeCode = Type.GetTypeCode(type); + if (type.IsEnum) { - Type t = parms[c].ParameterType; - switch (Type.GetTypeCode(t)) + switch (typeCode) + { + case TypeCode.Int32: + case TypeCode.UInt32: + return MarshalType.ENUM; + case TypeCode.Int64: + case TypeCode.UInt64: + return MarshalType.ENUM64; + default: + throw new JSException($"Unsupported enum underlying type {typeCode}"); + } + } + + switch (typeCode) + { + case TypeCode.Byte: + case TypeCode.SByte: + case TypeCode.Int16: + case TypeCode.UInt16: + case TypeCode.Int32: + return MarshalType.INT; + case TypeCode.UInt32: + return MarshalType.UINT32; + case TypeCode.Boolean: + return MarshalType.BOOL; + case TypeCode.Int64: + return MarshalType.INT64; + case TypeCode.UInt64: + return MarshalType.UINT64; + case TypeCode.Single: + return MarshalType.FP32; + case TypeCode.Double: + return MarshalType.FP64; + case TypeCode.String: + return MarshalType.STRING; + case TypeCode.Char: + return MarshalType.CHAR; + } + + if (type.IsArray) + { + if (!type.IsSZArray) + throw new JSException("Only single-dimensional arrays with a zero lower bound can be marshaled to JS"); + + var elementType = type.GetElementType(); + switch (Type.GetTypeCode(elementType)) { case TypeCode.Byte: + return MarshalType.ARRAY_UBYTE; case TypeCode.SByte: + return MarshalType.ARRAY_BYTE; case TypeCode.Int16: + return MarshalType.ARRAY_SHORT; case TypeCode.UInt16: + return MarshalType.ARRAY_USHORT; case TypeCode.Int32: + return MarshalType.ARRAY_INT; case TypeCode.UInt32: - case TypeCode.Boolean: - // Enums types have the same code as their underlying numeric types - if (t.IsEnum) - res[c] = 'j'; - else - res[c] = 'i'; - break; - case TypeCode.Int64: - case TypeCode.UInt64: - // Enums types have the same code as their underlying numeric types - if (t.IsEnum) - res[c] = 'k'; - else - res[c] = 'l'; - break; + return MarshalType.ARRAY_UINT; case TypeCode.Single: - res[c] = 'f'; - break; + return MarshalType.ARRAY_FLOAT; case TypeCode.Double: - res[c] = 'd'; - break; - case TypeCode.String: - res[c] = 's'; - break; + return MarshalType.ARRAY_DOUBLE; default: - if (t == typeof(IntPtr)) - { - res[c] = 'i'; - } - else if (t == typeof(Uri)) - { - res[c] = 'u'; - } - else if (t == typeof(SafeHandle)) - { - res[c] = 'h'; - } - else - { - if (t.IsValueType) - throw new NotSupportedException(SR.ValueTypeNotSupported); - res[c] = 'o'; - } - break; + throw new JSException($"Unsupported array element type {elementType}"); } } - return new string(res); + else if (type == typeof(IntPtr)) + return MarshalType.POINTER; + else if (type == typeof(UIntPtr)) + return MarshalType.POINTER; + else if (type == typeof(SafeHandle)) + return MarshalType.SAFEHANDLE; + else if (typeof(Delegate).IsAssignableFrom(type)) + return MarshalType.DELEGATE; + else if ((type == typeof(Task)) || typeof(Task).IsAssignableFrom(type)) + return MarshalType.TASK; + else if (typeof(Uri) == type) + return MarshalType.URI; + else if (type.IsPointer) + return MarshalType.POINTER; + + if (type.IsValueType) + return MarshalType.VT; + else + return MarshalType.OBJECT; + } + + internal static char GetCallSignatureCharacterForMarshalType(MarshalType t, char? defaultValue) + { + switch (t) + { + case MarshalType.BOOL: + case MarshalType.INT: + case MarshalType.UINT32: + case MarshalType.POINTER: + return 'i'; + case MarshalType.UINT64: + case MarshalType.INT64: + return 'l'; + case MarshalType.FP32: + return 'f'; + case MarshalType.FP64: + return 'd'; + case MarshalType.STRING: + return 's'; + case MarshalType.URI: + return 'u'; + case MarshalType.SAFEHANDLE: + return 'h'; + case MarshalType.ENUM: + return 'j'; + case MarshalType.ENUM64: + return 'k'; + case MarshalType.TASK: + case MarshalType.DELEGATE: + case MarshalType.OBJECT: + return 'o'; + case MarshalType.VT: + return 'a'; + default: + if (defaultValue.HasValue) + return defaultValue.Value; + else + throw new JSException($"Unsupported marshal type {t}"); + } } /// diff --git a/src/libraries/System.Private.Uri/src/System/Uri.cs b/src/libraries/System.Private.Uri/src/System/Uri.cs index b0bda36d92db2..b69b12368f2aa 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -4916,7 +4916,7 @@ private static string CombineUri(Uri basePart, string relativePart, UriFormat ur bool convBackSlashes = basePart.Syntax.InFact(UriSyntaxFlags.ConvertPathSlashes); - string? left = null; + string? left; // check for network or local absolute path if (c1 == '/' || (c1 == '\\' && convBackSlashes)) diff --git a/src/libraries/System.Private.Uri/src/System/UriExt.cs b/src/libraries/System.Private.Uri/src/System/UriExt.cs index 070e11a7f987f..799f9ca2d577f 100644 --- a/src/libraries/System.Private.Uri/src/System/UriExt.cs +++ b/src/libraries/System.Private.Uri/src/System/UriExt.cs @@ -204,7 +204,6 @@ private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatExcep (UriComponents)0); if (_string.Length > ushort.MaxValue) { - err = ParsingError.SizeLimit; return; } } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs index 56774c9684da5..2d98ae02585d9 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs @@ -1127,7 +1127,6 @@ public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o } _currentContainer.AddNodeSkipNotify(newNode); - newNode = null; } return true; @@ -1247,7 +1246,6 @@ public async ValueTask ReadContentFromAsync(XContainer rootContainer, XmlR } _currentContainer.AddNodeSkipNotify(newNode); - newNode = null; } return true; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs index 58c536966a359..a5bade7824418 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs @@ -221,11 +221,10 @@ public XHashtableState Resize() for (int bucketIdx = 0; bucketIdx < _buckets.Length; bucketIdx++) { int entryIdx = _buckets[bucketIdx]; - TValue newValue; while (entryIdx > EndOfList) { - newHashtable.TryAdd(_entries[entryIdx].Value, out newValue); + newHashtable.TryAdd(_entries[entryIdx].Value, out _); entryIdx = _entries[entryIdx].Next; } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs index 074dd99d4a9db..8460c3345330c 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs @@ -498,7 +498,7 @@ public override bool MoveToNext() XContainer? container = currentNode.GetParent(); if (container != null) { - XNode? next = null; + XNode? next; for (XNode node = currentNode; node != null; node = next) { next = node.NextNode; @@ -548,7 +548,7 @@ public override bool MoveToNext(XPathNodeType type) { mask &= ~TextMask; } - XNode? next = null; + XNode? next; for (XNode node = currentNode; ; node = next) { next = node.NextNode; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs index 90a9359058044..9bacf94038822 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs @@ -141,7 +141,7 @@ public static byte[] Decode(char[] chars, bool allowOddChars) bool hasHalfByteCached = false; byte cachedHalfByte = 0; - Decode(chars, bytes, ref hasHalfByteCached, ref cachedHalfByte, out int charsDecoded, out int bytesDecoded); + Decode(chars, bytes, ref hasHalfByteCached, ref cachedHalfByte, out _, out int bytesDecoded); if (hasHalfByteCached && !allowOddChars) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs index a43399d28bd6b..074f795ea54c0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs @@ -1083,7 +1083,7 @@ private int FinishContentAsXXX(int origPos) public override bool ReadContentAsBoolean() { int origPos = _pos; - bool value = false; + bool value; try { if (SetupContentAsXXX("ReadContentAsBoolean")) @@ -2536,7 +2536,7 @@ private void GenerateImpliedXmlnsAttrs() private bool ReadInit(bool skipXmlDecl) { - string? err = null; + string? err; if (!_sniffed) { // check magic header @@ -2809,8 +2809,7 @@ private void FinishCDATA() case BinXmlToken.CData: // skip _pos++; - int pos; - ScanText(out pos); + ScanText(out _); // try again break; case BinXmlToken.EndCData: diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs index 41c65bd432a18..c8ec2d3fb6df9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentBuilder.cs @@ -530,7 +530,9 @@ internal override void WriteNamespaceDeclaration(string prefix, string namespace { Debug.Assert(pageOrig != null); // Make a copy of the original namespace node +#pragma warning disable IDE0059 // https://github.com/dotnet/roslyn/issues/58564 idxTemp = pageOrig[idxOrig].GetParent(out pageTemp!); +#pragma warning restore IDE0059 idxTemp = NewNamespaceNode(out pageTemp, pageOrig[idxOrig].LocalName, pageOrig[idxOrig].Value, pageTemp, idxTemp); // Attach copy to chain of copied nodes diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeHelper.cs index 857b69429247b..e267206f6e538 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeHelper.cs @@ -642,7 +642,6 @@ public static bool GetNonDescendant(ref XPathNode[] pageNode, ref int idxNode) if (page![idx].HasSibling) { // Then that is the first non-descendant - pageNode = page; idxNode = page[idx].GetSibling(out pageNode!); return true; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs index 038222f073106..0b52424d01f10 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs @@ -843,14 +843,13 @@ private void EncodeChars(int startOffset, int endOffset, bool writeAllToStream) // Write encoded text to stream int chEnc; int bEnc; - bool completed; while (startOffset < endOffset) { if (_charEntityFallback != null) { _charEntityFallback.StartOffset = startOffset; } - _encoder.Convert(_bufChars, startOffset, endOffset - startOffset, _bufBytes, _bufBytesUsed, _bufBytes.Length - _bufBytesUsed, false, out chEnc, out bEnc, out completed); + _encoder.Convert(_bufChars, startOffset, endOffset - startOffset, _bufBytes, _bufBytesUsed, _bufBytes.Length - _bufBytesUsed, false, out chEnc, out bEnc, out _); startOffset += chEnc; _bufBytesUsed += bEnc; if (_bufBytesUsed >= (_bufBytes.Length - 16)) @@ -871,11 +870,9 @@ private void FlushEncoder() Debug.Assert(_bufPos == 1); if (_stream != null) { - int chEnc; int bEnc; - bool completed; // decode no chars, just flush - _encoder.Convert(_bufChars, 1, 0, _bufBytes, 0, _bufBytes.Length, true, out chEnc, out bEnc, out completed); + _encoder.Convert(_bufChars, 1, 0, _bufBytes, 0, _bufBytes.Length, true, out _, out bEnc, out _); if (bEnc != 0) { _stream.Write(_bufBytes, 0, bEnc); @@ -1852,7 +1849,7 @@ protected void ValidateContentChars(string chars, string propertyName, bool allo } else { - string error = null; + string error; for (int i = 0; i < chars.Length; i++) { if (!XmlCharType.IsTextChar(chars[i])) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs index 9231fe81926b4..e3484c076dade 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs @@ -676,14 +676,13 @@ private async Task EncodeCharsAsync(int startOffset, int endOffset, bool writeAl // Write encoded text to stream int chEnc; int bEnc; - bool completed; while (startOffset < endOffset) { if (_charEntityFallback != null) { _charEntityFallback.StartOffset = startOffset; } - _encoder.Convert(_bufChars, startOffset, endOffset - startOffset, _bufBytes, _bufBytesUsed, _bufBytes.Length - _bufBytesUsed, false, out chEnc, out bEnc, out completed); + _encoder.Convert(_bufChars, startOffset, endOffset - startOffset, _bufBytes, _bufBytesUsed, _bufBytes.Length - _bufBytesUsed, false, out chEnc, out bEnc, out _); startOffset += chEnc; _bufBytesUsed += bEnc; if (_bufBytesUsed >= (_bufBytes.Length - 16)) @@ -704,11 +703,9 @@ private Task FlushEncoderAsync() Debug.Assert(_bufPos == 1); if (_stream != null) { - int chEnc; int bEnc; - bool completed; // decode no chars, just flush - _encoder.Convert(_bufChars, 1, 0, _bufBytes, 0, _bufBytes.Length, true, out chEnc, out bEnc, out completed); + _encoder.Convert(_bufChars, 1, 0, _bufBytes, 0, _bufBytes.Length, true, out _, out bEnc, out _); if (bEnc != 0) { return _stream.WriteAsync(_bufBytes, 0, bEnc); @@ -873,7 +870,7 @@ protected unsafe int WriteAttributeTextBlockNoFlush(string text, int index, int protected async Task WriteAttributeTextBlockAsync(char[] chars, int index, int count) { - int writeLen = 0; + int writeLen; int curIndex = index; int leftCount = count; do @@ -890,7 +887,7 @@ protected async Task WriteAttributeTextBlockAsync(char[] chars, int index, int c protected Task WriteAttributeTextBlockAsync(string text) { - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; @@ -1084,10 +1081,10 @@ protected unsafe int WriteElementTextBlockNoFlush(string text, int index, int co protected async Task WriteElementTextBlockAsync(char[] chars, int index, int count) { - int writeLen = 0; + int writeLen; int curIndex = index; int leftCount = count; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteElementTextBlockNoFlush(chars, curIndex, leftCount, out needWriteNewLine); @@ -1109,10 +1106,10 @@ protected async Task WriteElementTextBlockAsync(char[] chars, int index, int cou protected Task WriteElementTextBlockAsync(string text) { - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; - bool needWriteNewLine = false; + bool needWriteNewLine; writeLen = WriteElementTextBlockNoFlush(text, curIndex, leftCount, out needWriteNewLine); curIndex += writeLen; @@ -1131,8 +1128,8 @@ protected Task WriteElementTextBlockAsync(string text) private async Task _WriteElementTextBlockAsync(bool newLine, string text, int curIndex, int leftCount) { - int writeLen = 0; - bool needWriteNewLine = false; + int writeLen; + bool needWriteNewLine; if (newLine) { @@ -1319,7 +1316,7 @@ private async Task _RawTextAsync( // Write out the remainder of the first string await FlushBufferAsync().ConfigureAwait(false); - int writeLen = 0; + int writeLen; do { writeLen = RawTextNoFlush(text1, curIndex1, leftCount1); @@ -1483,10 +1480,10 @@ protected unsafe int WriteRawWithCharCheckingNoFlush(string text, int index, int protected async Task WriteRawWithCharCheckingAsync(char[] chars, int index, int count) { - int writeLen = 0; + int writeLen; int curIndex = index; int leftCount = count; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteRawWithCharCheckingNoFlush(chars, curIndex, leftCount, out needWriteNewLine); @@ -1507,10 +1504,10 @@ protected async Task WriteRawWithCharCheckingAsync(char[] chars, int index, int protected async Task WriteRawWithCharCheckingAsync(string text) { - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteRawWithCharCheckingNoFlush(text, curIndex, leftCount, out needWriteNewLine); @@ -1694,10 +1691,10 @@ protected async Task WriteCommentOrPiAsync(string text, int stopChar) return; } - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteCommentOrPiNoFlush(text, curIndex, leftCount, stopChar, out needWriteNewLine); @@ -1878,10 +1875,10 @@ protected async Task WriteCDataSectionAsync(string text) return; } - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteCDataSectionNoFlush(text, curIndex, leftCount, out needWriteNewLine); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index e248843145208..6c7614308a93d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -636,7 +636,7 @@ internal XmlTextReaderImpl(string uriStr, XmlReaderSettings settings, XmlParserC private void FinishInitUriString() { - Stream? stream = null; + Stream? stream; Debug.Assert(_laterInitParam != null); Debug.Assert(_laterInitParam.inputUriResolver != null); Debug.Assert(_laterInitParam.inputbaseUri != null); @@ -2557,8 +2557,7 @@ internal int DtdParserProxy_ReadData() internal int DtdParserProxy_ParseNumericCharRef(StringBuilder? internalSubsetBuilder) { - EntityType entType; - return this.ParseNumericCharRef(true, internalSubsetBuilder, out entType); + return this.ParseNumericCharRef(true, internalSubsetBuilder, out _); } internal int DtdParserProxy_ParseNamedCharRef(bool expand, StringBuilder? internalSubsetBuilder) @@ -4140,8 +4139,7 @@ private bool ParseDocumentContent() { _fragmentType = XmlNodeType.Element; } - int i; - switch (HandleEntityReference(false, EntityExpandType.OnlyGeneral, out i)) + switch (HandleEntityReference(false, EntityExpandType.OnlyGeneral, out _)) { case EntityType.Unexpanded: if (_parsingFunction == ParsingFunction.EntityReference) @@ -4159,8 +4157,6 @@ private bool ParseDocumentContent() } continue; default: - chars = _ps.chars; - pos = _ps.charPos; continue; } } @@ -4198,11 +4194,7 @@ private bool ParseDocumentContent() ReadData: // read new characters into the buffer - if (ReadData() != 0) - { - pos = _ps.charPos; - } - else + if (ReadData() == 0) { if (needMoreChars) { @@ -4232,9 +4224,6 @@ private bool ParseDocumentContent() OnEof(); return false; } - - pos = _ps.charPos; - chars = _ps.chars; } } @@ -4778,8 +4767,7 @@ private void ThrowTagMismatch(NodeData startTag) if (startTag.type == XmlNodeType.Element) { // parse the bad name - int colonPos; - int endPos = ParseQName(out colonPos); + int endPos = ParseQName(out _); Debug.Assert(_ps.chars != null); string[] args = new string[4]; @@ -5522,7 +5510,7 @@ private bool ParseText() // skip over the text if not in full parsing mode if (_parsingMode != ParsingMode.Full) { - while (!ParseText(out startPos, out endPos, ref orChars)); + while (!ParseText(out _, out _, ref orChars)); goto IgnoredNode; } @@ -5583,7 +5571,7 @@ private bool ParseText() // V2 reader -> do not cache the whole value yet, read only up to 4kB to decide whether the value is a whitespace else { - bool fullValue = false; + bool fullValue; // if it's a partial text value, not a whitespace -> return if (orChars > 0x20) @@ -5618,7 +5606,7 @@ private bool ParseText() _stringBuilder.Length = 0; if (!fullValue) { - while (!ParseText(out startPos, out endPos, ref orChars)); + while (!ParseText(out _, out _, ref orChars)); } goto IgnoredNode; } @@ -5829,7 +5817,6 @@ private bool ParseText(out int startPos, out int endPos, ref int outOrChars) int offset = pos - _ps.charPos; if (ZeroEndingStream(pos)) { - chars = _ps.chars; pos = _ps.charPos + offset; goto ReturnPartialValue; } @@ -5968,12 +5955,10 @@ private void SkipPartialTextValue() { Debug.Assert(_parsingFunction == ParsingFunction.PartialTextValue || _parsingFunction == ParsingFunction.InReadValueChunk || _parsingFunction == ParsingFunction.InReadContentAsBinary || _parsingFunction == ParsingFunction.InReadElementContentAsBinary); - int startPos; - int endPos; int orChars = 0; _parsingFunction = _nextParsingFunction; - while (!ParseText(out startPos, out endPos, ref orChars)); + while (!ParseText(out _, out _, ref orChars)); } private void FinishReadValueChunk() @@ -6398,7 +6383,7 @@ private bool ParsePI(StringBuilder? piInDtdStringBuilder) { if (_ignorePIs || _parsingMode != ParsingMode.Full) { - while (!ParsePIValue(out startPos, out endPos)); + while (!ParsePIValue(out _, out _)); return false; } sb = _stringBuilder; @@ -6625,7 +6610,7 @@ private void ParseCDataOrComment(XmlNodeType type) } else { - while (!ParseCDataOrComment(type, out startPos, out endPos)); + while (!ParseCDataOrComment(type, out _, out _)); } } @@ -6871,10 +6856,8 @@ private void ParseDtd() private void SkipDtd() { - int colonPos; - // parse dtd name - int pos = ParseQName(out colonPos); + int pos = ParseQName(out _); _ps.charPos = pos; // check whitespace @@ -7643,8 +7626,7 @@ private int ParseNamedCharRefInline(int startPos, bool expand, StringBuilder? in private int ParseName() { - int colonPos; - return ParseQName(false, 0, out colonPos); + return ParseQName(false, 0, out _); } private int ParseQName(out int colonPos) @@ -8366,8 +8348,8 @@ private int IncrementalRead() } } - int startPos = 0; - int pos = 0; + int startPos; + int pos; while (true) { @@ -8416,8 +8398,6 @@ private int IncrementalRead() ThrowUnclosedElements(); } _incReadState = IncrementalReadState.Text; - startPos = _ps.charPos; - pos = startPos; break; default: Debug.Fail($"Unexpected read state {_incReadState}"); @@ -8445,7 +8425,7 @@ private int IncrementalRead() } else { - while (XmlCharType.IsAttributeValueChar(c = chars[pos])) + while (XmlCharType.IsAttributeValueChar(chars[pos])) { pos++; } @@ -8535,9 +8515,8 @@ private int IncrementalRead() Debug.Assert(_ps.charPos - pos == 0); Debug.Assert(_ps.charPos - startPos == 0); - int colonPos; // ParseQName can flush the buffer, so we need to update the startPos, pos and chars after calling it - int endPos = ParseQName(true, 2, out colonPos); + int endPos = ParseQName(true, 2, out _); if (XmlConvert.StrEqual(chars, _ps.charPos + 2, endPos - _ps.charPos - 2, _curNode.GetNameWPrefix(_nameTable)) && (_ps.chars[endPos] == '>' || XmlCharType.IsWhiteSpace(_ps.chars[endPos]))) { @@ -8575,9 +8554,8 @@ private int IncrementalRead() Debug.Assert(_ps.charPos - pos == 0); Debug.Assert(_ps.charPos - startPos == 0); - int colonPos; // ParseQName can flush the buffer, so we need to update the startPos, pos and chars after calling it - int endPos = ParseQName(true, 1, out colonPos); + int endPos = ParseQName(true, 1, out _); if (XmlConvert.StrEqual(_ps.chars, _ps.charPos + 1, endPos - _ps.charPos - 1, _curNode.localName) && (_ps.chars[endPos] == '>' || _ps.chars[endPos] == '/' || XmlCharType.IsWhiteSpace(_ps.chars[endPos]))) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs index 06dfee97fbd89..dab8726286b55 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs @@ -749,7 +749,6 @@ public override async Task ReadValueChunkAsync(char[] buffer, int index, in var tuple_0 = await ParseTextAsync(orChars).ConfigureAwait(false); startPos = tuple_0.Item1; endPos = tuple_0.Item2; - orChars = tuple_0.Item3; endOfValue = tuple_0.Item4; @@ -2356,10 +2355,8 @@ private async Task ThrowTagMismatchAsync(NodeData startTag) if (startTag.type == XmlNodeType.Element) { // parse the bad name - int colonPos; var tuple_5 = await ParseQNameAsync().ConfigureAwait(false); - colonPos = tuple_5.Item1; int endPos = tuple_5.Item2; @@ -2977,7 +2974,7 @@ private Task ParseTextAsync() // the whole value is in buffer ValueTask<(int, int, int, bool)> parseTextTask = ParseTextAsync(orChars).Preserve(); - bool fullValue = false; + bool fullValue; if (!parseTextTask.IsCompletedSuccessfully) { return _ParseTextAsync(parseTextTask.AsTask()); @@ -3033,8 +3030,6 @@ private async Task _ParseTextAsync(Task<(int, int, int, bool)>? parseTask) do { tuple_9 = await ParseTextAsync(orChars).ConfigureAwait(false); - startPos = tuple_9.Item1; - endPos = tuple_9.Item2; orChars = tuple_9.Item3; } while (!tuple_9.Item4); @@ -3109,7 +3104,7 @@ private async Task _ParseTextAsync(Task<(int, int, int, bool)>? parseTask) // V2 reader -> do not cache the whole value yet, read only up to 4kB to decide whether the value is a whitespace else { - bool fullValue = false; + bool fullValue; // if it's a partial text value, not a whitespace -> return if (orChars > 0x20) @@ -3153,8 +3148,6 @@ private async Task _ParseTextAsync(Task<(int, int, int, bool)>? parseTask) do { tuple_13 = await ParseTextAsync(orChars).ConfigureAwait(false); - startPos = tuple_13.Item1; - endPos = tuple_13.Item2; orChars = tuple_13.Item3; } while (!tuple_13.Item4); } @@ -4059,8 +4052,6 @@ private async Task ParsePIAsync(StringBuilder? piInDtdStringBuilder) do { tuple_19 = await ParsePIValueAsync().ConfigureAwait(false); - startPos = tuple_19.Item1; - endPos = tuple_19.Item2; } while (!tuple_19.Item3); return false; @@ -4314,8 +4305,6 @@ private async Task ParseCDataOrCommentAsync(XmlNodeType type) do { tuple_23 = await ParseCDataOrCommentTupleAsync(type).ConfigureAwait(false); - startPos = tuple_23.Item1; - endPos = tuple_23.Item2; } while (!tuple_23.Item3); } } @@ -4564,12 +4553,10 @@ private async Task ParseDtdAsync() private async Task SkipDtdAsync() { - int colonPos; // parse dtd name var tuple_24 = await ParseQNameAsync().ConfigureAwait(false); - colonPos = tuple_24.Item1; int pos = tuple_24.Item2; @@ -5496,7 +5483,6 @@ private async Task ReadContentAsBinaryAsync(byte[] buffer, int index, int c var tuple_36 = await ParseTextAsync(orChars).ConfigureAwait(false); startPos = tuple_36.Item1; endPos = tuple_36.Item2; - orChars = tuple_36.Item3; endOfValue = tuple_36.Item4; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs index f98fd600fe9e4..feda115e1bbc2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs @@ -1722,7 +1722,7 @@ protected void ValidateContentChars(string chars, string propertyName, bool allo } else { - string error = null; + string error; for (int i = 0; i < chars.Length; i++) { if (!XmlCharType.IsTextChar(chars[i])) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs index cf6547e4f4ff6..35739f7884d37 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs @@ -740,7 +740,7 @@ protected unsafe int WriteAttributeTextBlockNoFlush(string text, int index, int protected async Task WriteAttributeTextBlockAsync(char[] chars, int index, int count) { - int writeLen = 0; + int writeLen; int curIndex = index; int leftCount = count; do @@ -757,7 +757,7 @@ protected async Task WriteAttributeTextBlockAsync(char[] chars, int index, int c protected Task WriteAttributeTextBlockAsync(string text) { - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; @@ -950,10 +950,10 @@ protected unsafe int WriteElementTextBlockNoFlush(string text, int index, int co protected async Task WriteElementTextBlockAsync(char[] chars, int index, int count) { - int writeLen = 0; + int writeLen; int curIndex = index; int leftCount = count; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteElementTextBlockNoFlush(chars, curIndex, leftCount, out needWriteNewLine); @@ -975,10 +975,10 @@ protected async Task WriteElementTextBlockAsync(char[] chars, int index, int cou protected Task WriteElementTextBlockAsync(string text) { - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; - bool needWriteNewLine = false; + bool needWriteNewLine; writeLen = WriteElementTextBlockNoFlush(text, curIndex, leftCount, out needWriteNewLine); curIndex += writeLen; @@ -997,8 +997,8 @@ protected Task WriteElementTextBlockAsync(string text) private async Task _WriteElementTextBlockAsync(bool newLine, string text, int curIndex, int leftCount) { - int writeLen = 0; - bool needWriteNewLine = false; + int writeLen; + bool needWriteNewLine; if (newLine) { @@ -1184,7 +1184,7 @@ private async Task _RawTextAsync( // Write out the remainder of the first string await FlushBufferAsync().ConfigureAwait(false); - int writeLen = 0; + int writeLen; do { writeLen = RawTextNoFlush(text1, curIndex1, leftCount1); @@ -1347,10 +1347,10 @@ protected unsafe int WriteRawWithCharCheckingNoFlush(string text, int index, int protected async Task WriteRawWithCharCheckingAsync(char[] chars, int index, int count) { - int writeLen = 0; + int writeLen; int curIndex = index; int leftCount = count; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteRawWithCharCheckingNoFlush(chars, curIndex, leftCount, out needWriteNewLine); @@ -1371,10 +1371,10 @@ protected async Task WriteRawWithCharCheckingAsync(char[] chars, int index, int protected async Task WriteRawWithCharCheckingAsync(string text) { - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteRawWithCharCheckingNoFlush(text, curIndex, leftCount, out needWriteNewLine); @@ -1557,10 +1557,10 @@ protected async Task WriteCommentOrPiAsync(string text, int stopChar) return; } - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteCommentOrPiNoFlush(text, curIndex, leftCount, stopChar, out needWriteNewLine); @@ -1740,10 +1740,10 @@ protected async Task WriteCDataSectionAsync(string text) return; } - int writeLen = 0; + int writeLen; int curIndex = 0; int leftCount = text.Length; - bool needWriteNewLine = false; + bool needWriteNewLine; do { writeLen = WriteCDataSectionNoFlush(text, curIndex, leftCount, out needWriteNewLine); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs index 62e9a433a199c..a1e868aaca83b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs @@ -2239,7 +2239,7 @@ private void ClearAttributesInfo() { Debug.Assert(_coreReaderNameTable.Get(localName) != null); Debug.Assert(_coreReaderNameTable.Get(ns) != null); - AttributePSVIInfo? attInfo = null; + AttributePSVIInfo? attInfo; for (int i = 0; i < _coreReaderAttributeCount; i++) { @@ -2284,7 +2284,7 @@ private void ClearAttributesInfo() { Debug.Assert(_coreReaderNameTable.Get(attrLocalName) != null); Debug.Assert(_coreReaderNameTable.Get(ns) != null); - ValidatingReaderNodeData? defaultNode = null; + ValidatingReaderNodeData? defaultNode; for (int i = 0; i < _defaultAttributes.Count; i++) { @@ -2449,7 +2449,7 @@ private object InternalReadContentAsObject(bool unwrapTypedValue, out string ori private object? InternalReadElementContentAsObject(out XmlSchemaType? xmlType, bool unwrapTypedValue, out string? originalString) { Debug.Assert(this.NodeType == XmlNodeType.Element); - object? typedValue = null; + object? typedValue; xmlType = null; // If its an empty element, can have default/fixed value diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs index 97b475c53dbe4..e0225d0630ab5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs @@ -767,7 +767,7 @@ private async Task InternalReadContentAsObjectAsync(bool unwrapTypedValu private async Task<(XmlSchemaType, string, object)> InternalReadElementContentAsObjectTupleAsync(bool unwrapTypedValue) { - XmlSchemaType? xmlType = null; + XmlSchemaType? xmlType; string originalString; Debug.Assert(this.NodeType == XmlNodeType.Element); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs index 68085baec4465..13c2e36354c42 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs @@ -340,7 +340,7 @@ private void ValidateElement() Debug.Assert(elementNode != null); XmlAttributeCollection attributes = elementNode.Attributes; - XmlAttribute? attr = null; + XmlAttribute? attr; //Find Xsi attributes that need to be processed before validating the element string? xsiNil = null; @@ -401,7 +401,7 @@ private void ValidateElement() private void ValidateAttributes(XmlElement elementNode) { XmlAttributeCollection attributes = elementNode.Attributes; - XmlAttribute? attr = null; + XmlAttribute? attr; for (int i = 0; i < attributes.Count; i++) { @@ -431,7 +431,6 @@ private void ValidateAttributes(XmlElement elementNode) } _validator!.GetUnspecifiedDefaultAttributes(_defaultAttributes); XmlQualifiedName attrQName; - attr = null; for (int i = 0; i < _defaultAttributes.Count; i++) { XmlSchemaAttribute schemaAttribute = (_defaultAttributes[i] as XmlSchemaAttribute)!; @@ -507,7 +506,7 @@ private void SetDefaultAttributeSchemaInfo(XmlSchemaAttribute schemaAttribute) //Create nodelist to navigate down again XmlNode currentNode = elementToValidate; - IXmlSchemaInfo? parentSchemaInfo = null; + IXmlSchemaInfo? parentSchemaInfo; int nodeIndex = 0; //Check common case of parent node first @@ -633,7 +632,7 @@ private void CheckNodeSequenceCapacity(int currentIndex) //validate element whose type is needed, ValidateSingleElement(elementToValidate, false, _schemaInfo); - XmlSchemaObject? schemaInfoFound = null; + XmlSchemaObject? schemaInfoFound; if (_schemaInfo.SchemaElement != null) { schemaInfoFound = _schemaInfo.SchemaElement; @@ -678,7 +677,7 @@ private bool AncestorTypeHasWildcard(XmlSchemaObject? ancestorType) } XmlSchemaElement? schemaElement = schemaObject as XmlSchemaElement; - XmlSchemaComplexType? complexType = null; + XmlSchemaComplexType? complexType; if (schemaElement != null) { complexType = schemaElement.ElementSchemaType as XmlSchemaComplexType; @@ -697,7 +696,7 @@ private void ValidateSingleElement(XmlElement elementNode, bool skipToEnd, XmlSc Debug.Assert(elementNode != null); XmlAttributeCollection attributes = elementNode.Attributes; - XmlAttribute? attr = null; + XmlAttribute? attr; //Find Xsi attributes that need to be processed before validating the element string? xsiNil = null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs index dc21a3fd364b4..d2fc81cf554ed 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs @@ -101,9 +101,9 @@ public override string InnerText set { - string? tempVersion = null; - string? tempEncoding = null; - string? tempStandalone = null; + string? tempVersion; + string? tempEncoding; + string? tempStandalone; string orgEncoding = this.Encoding; string orgStandalone = this.Standalone; string? orgVersion = this.Version; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs index 650ad0aacfc70..6dddd2976ba49 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs @@ -614,8 +614,8 @@ internal override bool CanInsertAfter(XmlNode newChild, XmlNode? refChild) // Creates an XmlAttribute with the specified name. public XmlAttribute CreateAttribute(string name) { - string prefix = string.Empty; - string localName = string.Empty; + string prefix; + string localName; string namespaceURI = string.Empty; SplitName(name, out prefix, out localName); @@ -665,8 +665,8 @@ public virtual XmlDocumentFragment CreateDocumentFragment() // Creates an element with the specified name. public XmlElement CreateElement(string name) { - string prefix = string.Empty; - string localName = string.Empty; + string prefix; + string localName; SplitName(name, out prefix, out localName); return CreateElement(prefix, localName, string.Empty); } @@ -923,8 +923,8 @@ public virtual XmlNodeList GetElementsByTagName(string name) // and NamespaceURI. public XmlAttribute CreateAttribute(string qualifiedName, string? namespaceURI) { - string prefix = string.Empty; - string localName = string.Empty; + string prefix; + string localName; SplitName(qualifiedName, out prefix, out localName); return CreateAttribute(prefix, localName, namespaceURI); @@ -934,8 +934,8 @@ public XmlAttribute CreateAttribute(string qualifiedName, string? namespaceURI) // NamespaceURI. public XmlElement CreateElement(string qualifiedName, string? namespaceURI) { - string prefix = string.Empty; - string localName = string.Empty; + string prefix; + string localName; SplitName(qualifiedName, out prefix, out localName); return CreateElement(prefix, localName, namespaceURI); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs index d4847fbe6ddb7..cbbb1f1e3f8e0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs @@ -56,7 +56,7 @@ private void LoadDocSequence(XmlDocument parentDoc) { Debug.Assert(_reader != null); Debug.Assert(parentDoc != null); - XmlNode? node = null; + XmlNode? node; while ((node = LoadNode(true)) != null) { parentDoc.AppendChildForLoad(node, parentDoc); @@ -102,7 +102,7 @@ private void LoadDocSequence(XmlDocument parentDoc) IXmlSchemaInfo? schemaInfo; do { - XmlNode? node = null; + XmlNode? node; switch (r.NodeType) { case XmlNodeType.Element: @@ -463,7 +463,7 @@ private XmlDocumentType LoadDocumentTypeNode() XmlNode? parent = null; do { - XmlNode? node = null; + XmlNode? node; switch (r.NodeType) { case XmlNodeType.Element: @@ -763,7 +763,7 @@ internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string inne if (nt == XmlNodeType.Entity) { - XmlNode? node = null; + XmlNode? node; while (_reader.Read() && (node = LoadNodeDirect()) != null) { parentNode.AppendChildForLoad(node, _doc); @@ -771,7 +771,7 @@ internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string inne } else { - XmlNode? node = null; + XmlNode? node; while (_reader.Read() && (node = LoadNode(true)) != null) { parentNode.AppendChildForLoad(node, _doc); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs index ce5118c2b0b65..295950dab4b1f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs @@ -1051,7 +1051,7 @@ public virtual string BaseURI public virtual void RemoveAll() { XmlNode? child = FirstChild; - XmlNode? sibling = null; + XmlNode? sibling; while (child != null) { @@ -1351,7 +1351,7 @@ internal virtual XmlSpace XmlSpace get { XmlNode? node = this; - XmlElement? elem = null; + XmlElement? elem; do { elem = node as XmlElement; @@ -1381,7 +1381,7 @@ internal virtual string XmlLang get { XmlNode? node = this; - XmlElement? elem = null; + XmlElement? elem; do { elem = node as XmlElement; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs index 6e3387dc072c3..ade3ad8fbfdd8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs @@ -226,7 +226,7 @@ public string Value //See comments in HasValue get { - string? retValue = null; + string? retValue; XmlNodeType nt = _curNode.NodeType; if (_nAttrInd != -1) { @@ -626,7 +626,7 @@ public bool MoveToAttribute(string name) } private bool MoveToAttributeFromElement(XmlElement elem, string name, string ns) { - XmlAttribute? attr = null; + XmlAttribute? attr; if (ns.Length == 0) attr = elem.GetAttributeNode(name); else @@ -677,7 +677,7 @@ public void MoveToAttribute(int attributeIndex) { if (_bCreatedOnAttribute) return; - XmlAttribute? attr = null; + XmlAttribute? attr; switch (_curNode.NodeType) { case XmlNodeType.Element: @@ -1067,7 +1067,7 @@ public bool ReadAttributeValue(ref int level, ref bool bResolveEntity, ref XmlNo } else if (_bOnAttrVal) { - XmlNode? nextSibling = null; + XmlNode? nextSibling; if (_curNode.NodeType == XmlNodeType.EntityReference && bResolveEntity) { //going down to ent ref node @@ -1528,12 +1528,10 @@ private bool Read(bool fSkipChildren) FinishReadBinary(); } - bool bRead = false; if ((_readerNav.CreatedOnAttribute)) return false; ReSetReadingMarks(); - bRead = ReadNextNode(fSkipChildren); - if (bRead) + if (ReadNextNode(fSkipChildren)) { return true; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs index e7523cb04ff51..78685724522bd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs @@ -577,7 +577,7 @@ internal override object ParseValue(string s, XmlNameTable? nameTable, IXmlNames internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue) { - Exception? exception = null; + Exception? exception; typedValue = null; if (value == null) @@ -2093,7 +2093,7 @@ internal override int Compare(object value1, object value2) goto Error; } - DateTime dateTimeValue = DateTime.MinValue; + DateTime dateTimeValue; try { dateTimeValue = (DateTime)dateTime; @@ -2472,7 +2472,7 @@ internal override int Compare(object value1, object value2) exception = binaryFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - byte[]? byteArrayValue = null; + byte[]? byteArrayValue; try { byteArrayValue = XmlConvert.FromBinHexString(s, false); @@ -2573,7 +2573,7 @@ internal override int Compare(object value1, object value2) exception = binaryFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - byte[]? byteArrayValue = null; + byte[]? byteArrayValue; try { byteArrayValue = Convert.FromBase64String(s); @@ -2773,7 +2773,7 @@ internal override RestrictionFlags ValidRestrictionFlags exception = qnameFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - XmlQualifiedName? qname = null; + XmlQualifiedName? qname; try { string prefix; @@ -3109,7 +3109,7 @@ internal override RestrictionFlags ValidRestrictionFlags exception = qnameFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - XmlQualifiedName? qname = null; + XmlQualifiedName? qname; try { string prefix; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs index 7e784726a97b0..768c00aaf5d08 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs @@ -937,7 +937,7 @@ private void ParseElementDecl() } // get schema decl for element - SchemaElementDecl? elementDecl = null; + SchemaElementDecl? elementDecl; XmlQualifiedName name = GetNameQualified(true); if (_schemaInfo.ElementDecls.TryGetValue(name, out elementDecl)) @@ -987,7 +987,7 @@ private void ParseElementDecl() } case Token.None: { - ParticleContentValidator? pcv = null; + ParticleContentValidator? pcv; pcv = new ParticleContentValidator(XmlSchemaContentType.ElementOnly); pcv.Start(); pcv.OpenGroup(); @@ -1210,7 +1210,7 @@ private void ParseElementMixedContent(ParticleContentValidator pcv, int startPar private void ParseEntityDecl() { bool isParamEntity = false; - SchemaEntity? entity = null; + SchemaEntity? entity; // get entity name and type switch (GetToken(true)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs index 65c5f9bc615d3..60f01aa75aa56 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs @@ -579,7 +579,7 @@ private async Task ParseElementDeclAsync() } // get schema decl for element - SchemaElementDecl? elementDecl = null; + SchemaElementDecl? elementDecl; XmlQualifiedName name = GetNameQualified(true); if (_schemaInfo.ElementDecls.TryGetValue(name, out elementDecl)) @@ -629,7 +629,7 @@ private async Task ParseElementDeclAsync() } case Token.None: { - ParticleContentValidator? pcv = null; + ParticleContentValidator? pcv; pcv = new ParticleContentValidator(XmlSchemaContentType.ElementOnly); pcv.Start(); pcv.OpenGroup(); @@ -839,7 +839,7 @@ private async Task ParseElementMixedContentAsync(ParticleContentValidator pcv, i private async Task ParseEntityDeclAsync() { bool isParamEntity = false; - SchemaEntity? entity = null; + SchemaEntity? entity; // get entity name and type switch (await GetTokenAsync(true).ConfigureAwait(false)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs index 57ba0c8906f6f..feade926601eb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs @@ -149,7 +149,7 @@ private void ValidateChildElement() Debug.Assert(reader.NodeType == XmlNodeType.Element); if (context!.NeedValidateChildren) { //i think i can get away with removing this if cond since won't make this call for documentelement - int errorCode = 0; + int errorCode; context.ElementDecl!.ContentValidator!.ValidateElement(elementName, context, out errorCode); if (errorCode < 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs index de828715a33cb..38286d3917e54 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs @@ -1460,8 +1460,7 @@ private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaData case XmlTypeCode.AnyUri: if (verifyUri) { - Uri? uri; - exception = XmlConvert.TryToUri(s, out uri); + exception = XmlConvert.TryToUri(s, out _); } break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs index 9f2a8d5c0f7b1..33847d7040ea6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs @@ -215,7 +215,7 @@ internal XmlSchemaSet InferSchema1(XmlReader instanceDocument, XmlSchemaSet sche if (_rootSchema == null) { //rootSchema = CreateXmlSchema(xtr.NamespaceURI); - xse = AddElement(_xtr.LocalName, _xtr.Prefix, _xtr.NamespaceURI, null, null, -1); + AddElement(_xtr.LocalName, _xtr.Prefix, _xtr.NamespaceURI, null, null, -1); } else { @@ -276,9 +276,9 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string throw new XmlSchemaInferenceException(SR.SchInf_schema, 0, 0); } - XmlSchemaAttribute? xsa = null; + XmlSchemaAttribute? xsa; int AttributeType = -1; - XmlSchemaAttribute? returnedAttribute = null; //this value will change to attributeReference if childURI!= parentURI + XmlSchemaAttribute? returnedAttribute; //this value will change to attributeReference if childURI!= parentURI XmlSchema? xs = null; bool add = true; @@ -302,7 +302,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string } if (childURI == XmlReservedNs.NsXml) { - XmlSchemaAttribute? attributeReference = null; + XmlSchemaAttribute? attributeReference; //see if the reference exists attributeReference = FindAttributeRef(searchCollectionPrimary, localName, childURI); if (attributeReference == null && searchCollectionSecondary != null) @@ -362,7 +362,7 @@ private XmlSchemaAttribute AddAttribute(string localName, string prefix, string if (childURI!.Length != 0) //BUGBUG It need not be an attribute reference if there is a namespace, it can be attribute with attributeFormDefault = qualified { - XmlSchemaAttribute? attributeReference = null; + XmlSchemaAttribute? attributeReference; //see if the reference exists attributeReference = FindAttributeRef(searchCollectionPrimary, localName, childURI); if (attributeReference == null & searchCollectionSecondary != null) @@ -503,9 +503,9 @@ private XmlSchemaElement AddElement(string localName, string prefix, string? chi throw new XmlSchemaInferenceException(SR.SchInf_schema, 0, 0); } - XmlSchemaElement? xse = null; - XmlSchemaElement? returnedElement = xse; //this value will change to elementReference if childURI!= parentURI - XmlSchema? xs = null; + XmlSchemaElement? xse; + XmlSchemaElement? returnedElement; //this value will change to elementReference if childURI!= parentURI + XmlSchema? xs; bool bCreatingNewType = true; if (childURI == string.Empty) { @@ -592,7 +592,7 @@ private XmlSchemaElement AddElement(string localName, string prefix, string? chi } if (positionWithinCollection == -1) { - positionWithinCollection = addLocation.Add(xse); + addLocation.Add(xse); } else { @@ -609,7 +609,7 @@ private XmlSchemaElement AddElement(string localName, string prefix, string? chi } if (positionWithinCollection == -1) { - positionWithinCollection = addLocation.Add(elementReference); + addLocation.Add(elementReference); } else { @@ -1163,7 +1163,7 @@ internal XmlSchemaElement FindMatchingElement(bool bCreatingNewType, XmlReader x } //element not found in the sequence order, if it is found out of order change Sequence of elements to Sequence of Choices otherwise insert into sequence as optional - XmlSchemaElement? subElement = null; + XmlSchemaElement? subElement; XmlSchemaElement? actualElement = null; //BUGBUG - is this logic correct - if there is a sequence of elements should they be int he parent's namespace. @@ -1246,7 +1246,7 @@ internal void ProcessAttributes(ref XmlSchemaElement xse, XmlSchemaType? effecti xse.SchemaType = ct; } - XmlSchemaAttribute? xsa = null; + XmlSchemaAttribute? xsa; //The earlier assumption of checking just schemaTypeName !Empty is not correct for schemas that are not generated by us, schemaTypeName can point to any complex type as well //Check that it is a simple type by checking typeCode //Switch to complex type simple content extension @@ -1342,7 +1342,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten internal XmlSchemaElement? FindGlobalElement(string? namespaceURI, string localName, out XmlSchema? parentSchema) { ICollection col = _schemaSet!.Schemas(namespaceURI); - XmlSchemaElement? xse = null; + XmlSchemaElement? xse; parentSchema = null; foreach (XmlSchema? schema in col) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/NamespaceList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/NamespaceList.cs index 6ed6ff98e6a91..e4d26e3ccf542 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/NamespaceList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/NamespaceList.cs @@ -286,7 +286,7 @@ public static bool IsSubset(NamespaceList sub, NamespaceList super) private NamespaceList? CompareSetToOther(NamespaceList other) { //clause 5.1 - NamespaceList? nslist = null; + NamespaceList? nslist; if (_set!.Contains(other._targetNamespace!)) { //S contains negated ns if (_set.Contains(string.Empty)) @@ -341,7 +341,6 @@ public static bool IsSubset(NamespaceList sub, NamespaceList super) } else if (o1._type == ListType.Set && o2._type == ListType.Set) { //clause 4 - nslist = o1.Clone(); nslist = new NamespaceList(); nslist._type = ListType.Set; nslist._set = new Hashtable(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs index 6a83819b7fb40..e2c2b263e76b0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs @@ -275,7 +275,7 @@ private void ProcessAppInfoDocMarkup(bool root) { case XmlNodeType.Element: _annotationNSManager!.PushScope(); - currentNode = LoadElementNode(root); + LoadElementNode(root); // Dev10 (TFS) #479761: The following code was to address the issue of where an in-scope namespace delaration attribute // was not added when an element follows an empty element. This fix will result in persisting schema in a consistent form // although it does not change the semantic meaning of the schema. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs index 9056db9b5323e..764c4216ecfeb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs @@ -152,7 +152,7 @@ public bool Execute(XmlSchema schema, string? targetNamespace, bool loadExternal schemaIndex--; } - for (int i = schemaIndex; schemaIndex >= 0; schemaIndex--) + for (; schemaIndex >= 0; schemaIndex--) { listSchema = (XmlSchema)_lockList.GetByIndex(schemaIndex)!; listSchema.IsProcessing = false; //Reset processing flag from Preprocess @@ -344,7 +344,7 @@ private void LoadExternals(XmlSchema schema) if (_schemaLocations![ruri] == null) { // Only if location already not processed - object? obj = null; + object? obj; try { obj = GetSchemaEntity(ruri); @@ -534,7 +534,7 @@ private void ParseUri(string uri, string code, XmlSchemaObject sourceSchemaObjec private void Preprocess(XmlSchema schema, string? targetNamespace, ArrayList imports) { - XmlSchema? prevRootSchemaForRedefine = null; + XmlSchema? prevRootSchemaForRedefine; if (schema.IsProcessing) { return; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs index 615c405d31bc0..03597a53e8783 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs @@ -811,7 +811,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, XmlSchemaSimpleContentExtension simpleExtension) { - XmlSchemaComplexType? baseType = null; + XmlSchemaComplexType? baseType; if (complexType.Redefined != null && simpleExtension.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; @@ -850,7 +850,7 @@ private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, Xml private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, XmlSchemaSimpleContentRestriction simpleRestriction) { - XmlSchemaComplexType? baseType = null; + XmlSchemaComplexType? baseType; XmlSchemaDatatype? datatype = null; if (complexType.Redefined != null && simpleRestriction.BaseTypeName == complexType.Redefined.QualifiedName) { @@ -935,7 +935,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X private void CompileComplexContentExtension(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentExtension complexExtension) { - XmlSchemaComplexType? baseType = null; + XmlSchemaComplexType? baseType; if (complexType.Redefined != null && complexExtension.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; @@ -1001,7 +1001,7 @@ private void CompileComplexContentExtension(XmlSchemaComplexType complexType, Xm private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentRestriction complexRestriction) { - XmlSchemaComplexType? baseType = null; + XmlSchemaComplexType? baseType; if (complexType.Redefined != null && complexRestriction.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; @@ -1618,8 +1618,8 @@ private int GetMappingParticle(XmlSchemaParticle particle, XmlSchemaObjectCollec private bool IsParticleEmptiable(XmlSchemaParticle particle) { - decimal minOccurs, maxOccurs; - CalculateEffectiveTotalRange(particle, out minOccurs, out maxOccurs); + decimal minOccurs; + CalculateEffectiveTotalRange(particle, out minOccurs, out _); return minOccurs == decimal.Zero; } @@ -1992,7 +1992,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) return; } xa.IsProcessing = true; - SchemaAttDef? decl = null; + SchemaAttDef? decl; try { if (!xa.RefName.IsEmpty) @@ -2142,7 +2142,7 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) } xi.IsProcessing = true; - CompiledIdentityConstraint? compic = null; + CompiledIdentityConstraint? compic; try { SchemaNamespaceManager xnmgr = new SchemaNamespaceManager(xi); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs index 81a3e9f87432b..e4a1d6c24c2f5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs @@ -174,7 +174,7 @@ private void LoadExternals(XmlSchema schema, XmlSchemaCollection? xsc) _schemaLocations.Add(include.Schema.BaseUri, include.Schema.BaseUri); } //To avoid re-including components that were already included through a different path - Uri? subUri = null; + Uri? subUri; for (int j = 0; j < include.Schema.Includes.Count; ++j) { XmlSchemaExternal subInc = (XmlSchemaExternal)include.Schema.Includes[j]; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs index 72169a1d2da3d..76bcab42ffe22 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs @@ -905,7 +905,7 @@ private void CompileComplexType(XmlSchemaComplexType complexType) private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, XmlSchemaSimpleContentExtension simpleExtension) { - XmlSchemaComplexType? baseType = null; + XmlSchemaComplexType? baseType; if (complexType.Redefined != null && simpleExtension.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; @@ -946,7 +946,7 @@ private void CompileSimpleContentExtension(XmlSchemaComplexType complexType, Xml private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, XmlSchemaSimpleContentRestriction simpleRestriction) { - XmlSchemaComplexType? baseType = null; + XmlSchemaComplexType? baseType; XmlSchemaDatatype? datatype = null; if (complexType.Redefined != null && simpleRestriction.BaseTypeName == complexType.Redefined.QualifiedName) { @@ -1034,7 +1034,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X private void CompileComplexContentExtension(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentExtension complexExtension) { - XmlSchemaComplexType? baseType = null; + XmlSchemaComplexType? baseType; if (complexType.Redefined != null && complexExtension.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; @@ -1105,7 +1105,7 @@ private void CompileComplexContentExtension(XmlSchemaComplexType complexType, Xm private void CompileComplexContentRestriction(XmlSchemaComplexType complexType, XmlSchemaComplexContent complexContent, XmlSchemaComplexContentRestriction complexRestriction) { - XmlSchemaComplexType? baseType = null; + XmlSchemaComplexType? baseType; if (complexType.Redefined != null && complexRestriction.BaseTypeName == complexType.Redefined.QualifiedName) { baseType = (XmlSchemaComplexType)complexType.Redefined; @@ -1988,8 +1988,8 @@ private int GetMappingParticle(XmlSchemaParticle particle, XmlSchemaObjectCollec private bool IsParticleEmptiable(XmlSchemaParticle particle) { - decimal minOccurs, maxOccurs; - CalculateEffectiveTotalRange(particle, out minOccurs, out maxOccurs); + decimal minOccurs; + CalculateEffectiveTotalRange(particle, out minOccurs, out _); return minOccurs == decimal.Zero; } @@ -2453,7 +2453,7 @@ private void CompileAttribute(XmlSchemaAttribute xa) return; } xa.IsProcessing = true; - SchemaAttDef? decl = null; + SchemaAttDef? decl; try { if (!xa.RefName.IsEmpty) @@ -2618,7 +2618,7 @@ private void CompileIdentityConstraint(XmlSchemaIdentityConstraint xi) } xi.IsProcessing = true; - CompiledIdentityConstraint? compic = null; + CompiledIdentityConstraint? compic; try { SchemaNamespaceManager xnmgr = new SchemaNamespaceManager(xi); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs index bbbffb483e92c..6c91f1f48dcb4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs @@ -108,7 +108,7 @@ private void ValidateChildElement() { if (context!.NeedValidateChildren) { - int errorCode = 0; + int errorCode; context.ElementDecl!.ContentValidator!.ValidateElement(elementName, context, out errorCode); if (errorCode < 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs index a453d72bd41c6..b305f688fbd3f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs @@ -139,7 +139,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) bool ignoreXS = false; if (this.Namespaces != null) { //User may have set both nsManager and Namespaces property on the XmlSchema object - ignoreXS = this.Namespaces.TryLookupPrefix("xs", out string? p) || this.Namespaces.TryLookupNamespace(XmlReservedNs.NsXs, out string? n); + ignoreXS = this.Namespaces.TryLookupPrefix("xs", out _) || this.Namespaces.TryLookupNamespace(XmlReservedNs.NsXs, out _); } if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null && namespaceManager.LookupNamespace("xs") == null) @@ -156,7 +156,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) } else if (this.Namespaces != null && this.Namespaces.Count > 0) { - if (!this.Namespaces.TryLookupPrefix("xs", out string? p) && !this.Namespaces.TryLookupNamespace(XmlReservedNs.NsXs, out string? n)) + if (!this.Namespaces.TryLookupPrefix("xs", out _) && !this.Namespaces.TryLookupNamespace(XmlReservedNs.NsXs, out _)) { //Prefix xs not defined AND schema namespace not already mapped to a prefix this.Namespaces.Add("xs", XmlReservedNs.NsXs); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs index 0b82c430a82b3..0837f29924f8b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs @@ -485,7 +485,7 @@ private static XmlSchemaObjectCollection CloneGroupBaseParticles(XmlSchemaObject XmlSchemaGroupBase? groupBase = particle as XmlSchemaGroupBase; if (groupBase != null) { //Choice or sequence - XmlSchemaGroupBase newGroupBase = groupBase; + XmlSchemaGroupBase newGroupBase; XmlSchemaObjectCollection newGroupbaseParticles = CloneGroupBaseParticles(groupBase.Items, parentSchema); newGroupBase = (XmlSchemaGroupBase)groupBase.Clone(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs index efb67b70d84cb..5469337241857 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs @@ -25,7 +25,7 @@ internal void Add(XmlQualifiedName name, XmlSchemaObject value) internal void Insert(XmlQualifiedName name, XmlSchemaObject value) { - XmlSchemaObject? oldValue = null; + XmlSchemaObject? oldValue; if (_table.TryGetValue(name, out oldValue)) { _table[name] = value; //set new value diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs index cdbe0178c0c32..50ba298672844 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs @@ -901,7 +901,7 @@ internal void Add(string? targetNamespace, XmlReader reader, Hashtable validated //Not locking set as this will not be accessible outside the validator XmlSchema? schema; - if (IsSchemaLoaded(new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute), targetNamespace, out schema)) + if (IsSchemaLoaded(new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute), targetNamespace, out _)) { return; } @@ -1344,7 +1344,6 @@ internal SchemaNames GetSchemaNames(XmlNameTable nt) internal bool IsSchemaLoaded(Uri schemaUri, string? targetNamespace, out XmlSchema? schema) { - schema = null; if (targetNamespace == null) { targetNamespace = string.Empty; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index 86b9f54055227..e02e6af5fe859 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -1353,7 +1353,7 @@ private void ProcessSchemaLocations(string? xsiSchemaLocation, string? xsiNoName private object? ValidateElementContext(XmlQualifiedName elementName, out bool invalidElementInContext) { object? particle = null; - int errorCode = 0; + int errorCode; XmlQualifiedName head; XmlSchemaElement? headElement = null; invalidElementInContext = false; @@ -1697,7 +1697,7 @@ private void AddXsiAttributes(ArrayList attList) XmlQualifiedName xsiTypeName = XmlQualifiedName.Empty; if (xsiType != null) { - object? typedVal = null; + object? typedVal; Exception? exception = s_dtQName.TryParseValue(xsiType, _nameTable, _nsResolver, out typedVal); if (exception != null) { @@ -1990,13 +1990,13 @@ private void ProcessTokenizedType(XmlTokenizedType ttype, string name, bool attr private object? CheckAttributeValue(object value, SchemaAttDef attdef) { - object? typedValue = null; + object? typedValue; SchemaDeclBase decl = attdef as SchemaDeclBase; XmlSchemaDatatype dtype = attdef.Datatype; Debug.Assert(dtype != null); string? stringValue = value as string; - Exception? exception = null; + Exception? exception; if (stringValue != null) { @@ -2032,7 +2032,7 @@ private void ProcessTokenizedType(XmlTokenizedType ttype, string name, bool attr private object? CheckElementValue(string stringValue) { - object? typedValue = null; + object? typedValue; SchemaDeclBase decl = (_context.ElementDecl as SchemaDeclBase)!; XmlSchemaDatatype dtype = decl.Datatype; @@ -2675,7 +2675,7 @@ internal static string PrintExpectedElements(ArrayList expected, bool getParticl if (getParticles) { string ContinuationString = SR.Format(SR.Sch_ContinuationString, new string[] { " " }); - XmlSchemaParticle? currentParticle = null; + XmlSchemaParticle? currentParticle; XmlSchemaParticle? nextParticle = null; XmlQualifiedName currentQName; ArrayList expectedNames = new ArrayList(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs index 454d7f8eb8359..443a22c08aa2e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs @@ -259,7 +259,7 @@ public TimeSpan ToTimeSpan(DurationType durationType) internal Exception? TryToTimeSpan(DurationType durationType, out TimeSpan result) { - Exception? exception = null; + Exception? exception; ulong ticks = 0; // Throw error if result cannot fit into a long @@ -446,7 +446,6 @@ internal string ToString(DurationType durationType) length = s.Length; pos = 0; - numDigits = 0; if (pos >= length) goto InvalidFormat; @@ -505,7 +504,7 @@ internal string ToString(DurationType durationType) result._days = value; if (++pos == length) goto Done; - errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); + errorCode = TryParseDigits(s, ref pos, false, out _, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs index f34d3b5e3c43d..9b7adb815b028 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs @@ -142,7 +142,7 @@ private void ProcessInlineSchema() { // Done _inlineSchemaParser.FinishParsing(); XmlSchema? schema = _inlineSchemaParser.XmlSchema; - string? inlineNS = null; + string? inlineNS; if (schema != null && schema.ErrorCount == 0) { try @@ -187,7 +187,7 @@ private void ValidateElement() private object? ValidateChildElement() { object? particle = null; - int errorCode = 0; + int errorCode; if (context!.NeedValidateChildren) { if (context.IsNill) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs index eb098c59450f7..0d867111bf655 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs @@ -109,7 +109,7 @@ private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic) MarkLabel(_methodEndLabel); Ret(); - MethodBuilder? retVal = null; + MethodBuilder? retVal; retVal = _methodBuilder; _methodBuilder = null; _ilGen = null; @@ -528,7 +528,7 @@ internal Type LoadMember(object obj, MemberInfo memberInfo) [RequiresUnreferencedCode("calls GetPropertyMethodFromBaseType")] internal Type LoadMember(MemberInfo memberInfo) { - Type? memberType = null; + Type? memberType; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; @@ -567,7 +567,7 @@ internal Type LoadMember(MemberInfo memberInfo) [RequiresUnreferencedCode("calls GetPropertyMethodFromBaseType")] internal Type LoadMemberAddress(MemberInfo memberInfo) { - Type? memberType = null; + Type? memberType; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; @@ -936,7 +936,7 @@ internal void Ldloc(string name) internal void Stloc(Type type, string name) { - LocalBuilder? local = null; + LocalBuilder? local; if (!_currentScope!.TryGetValue(name, out local)) { local = DeclareLocal(type, name); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs index 6dffc8c217609..071052f5af01a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs @@ -149,7 +149,7 @@ internal void InitAssemblyMethods(XmlMapping[] xmlMappings) { Assembly? serializer = null; contract = null; - string? serializerName = null; + string? serializerName; using (AssemblyLoadContext.EnterContextualReflection(type.Assembly)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index 7d042e04787d1..81a4ee0f97e2c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs @@ -512,8 +512,7 @@ internal void Depends(XmlSchemaObject? item, ArrayList refs) XmlAttribute attribute = attrs[i]; if (attribute.LocalName == Wsdl.ArrayType && attribute.NamespaceURI == Wsdl.Namespace) { - string dims; - XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attribute.Value, out dims, item); + XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attribute.Value, out _, item); XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(qname, typeof(XmlSchemaType), false); AddRef(refs, type); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index 0c74ae4944e95..0c674716fbdc7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -630,8 +630,7 @@ internal CodeIdentifiers Scope } internal bool Declares(MemberMapping member, string? parent) { - StructMapping? m; - return (FindDeclaringMapping(member, out m, parent) != null); + return (FindDeclaringMapping(member, out _, parent) != null); } internal void SetContentModel(TextAccessor? text, bool hasElements) @@ -1239,7 +1238,7 @@ internal void CheckDuplicateElement(XmlSchemaElement? element, string? elementNs if (element.Parent == null || !(element.Parent is XmlSchema)) return; - XmlSchemaObjectTable? elements = null; + XmlSchemaObjectTable? elements; if (Schema != null && Schema.TargetNamespace == elementNs) { XmlSchemas.Preprocess(Schema); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index 92f54f923386f..6c4e4fb6bb6a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -970,8 +970,8 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, xmlQualifiedName = new XmlQualifiedName(mapping.TypeName, mapping.Namespace); } - string? stringValue = null; - bool hasValidStringValue = false; + string? stringValue; + bool hasValidStringValue; if (mapping is EnumMapping enumMapping) { stringValue = WriteEnumMethod(enumMapping, o); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index 443a6748ecd53..ee804a5bfd4a0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -784,7 +784,7 @@ internal TypeDesc GetArrayTypeDesc(Type type) [RequiresUnreferencedCode("calls GetEnumeratorElementType")] private TypeDesc ImportTypeDesc(Type type, MemberInfo? memberInfo, bool directReference) { - TypeDesc? typeDesc = null; + TypeDesc? typeDesc; TypeKind kind; Type? arrayElementType = null; Type? baseType = null; @@ -1164,7 +1164,7 @@ private static void PopulateMemberInfos(StructMapping structMapping, MemberMappi // 2) Do the same thing for the memberMapping array. Note that we need to create a new copy of MemberMapping object since the old one could still be referenced // by the StructMapping of the baseclass, so updating it directly could lead to other issues. Dictionary? replaceList = null; - MemberInfo? replacedInfo = null; + MemberInfo? replacedInfo; foreach (KeyValuePair pair in memberInfos) { if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc!.Type!, out replacedInfo)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 69f23fc7ea41a..105c5f2897051 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -515,7 +515,7 @@ private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string } if (typeDesc.Kind == TypeKind.Serializable) { - SerializableMapping? serializableMapping = null; + SerializableMapping? serializableMapping; // get the schema method info object[] attrs = type.GetCustomAttributes(typeof(XmlSchemaProviderAttribute), false); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index b9020be08972f..e6694d5ed00c6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -1849,7 +1849,7 @@ private PrimitiveMapping ImportPrimitiveDataType(XmlSchemaSimpleType dataType, T private PrimitiveMapping? ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string? ns, TypeFlags flags) { PrimitiveMapping? mapping = null; - TypeDesc? typeDesc = null; + TypeDesc? typeDesc; if (dataType.Name != null && dataType.Name.Length != 0) { typeDesc = Scope.GetTypeDesc(dataType.Name, ns, flags); @@ -1905,7 +1905,7 @@ internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) [RequiresUnreferencedCode("calls FindDataType")] private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags) { - TypeDesc? typeDesc = null; + TypeDesc? typeDesc; if (dataType.Name != null && dataType.Name.Length != 0) { typeDesc = Scope.GetTypeDesc(dataType); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index 94fdb0a374c93..858b4db17b512 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -527,7 +527,7 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) ns = ((XmlSchema)tmp).TargetNamespace; } } - string? item = null; + string? item; if (o is XmlSchemaNotation) { item = SR.Format(SR.XmlSchemaNamedItem, ns, "notation", ((XmlSchemaNotation)o).Name, details); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 52e70f990d16f..1a49b131660f2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -520,7 +520,7 @@ private byte[] ReadByteArray(bool isBase64) private object? ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType) { InitPrimitiveIDs(); - object? value = null; + object? value; if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) return ReadXmlNodes(elementCanBeType); @@ -682,7 +682,7 @@ private byte[] ReadByteArray(bool isBase64) protected object? ReadTypedNull(XmlQualifiedName type) { InitPrimitiveIDs(); - object? value = null; + object? value; if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) { return null; @@ -1770,10 +1770,9 @@ protected void FixupArrayRefs(object fixup) protected void ReadReferencedElements() { _r.MoveToContent(); - string? dummy; while (_r.NodeType != XmlNodeType.EndElement && _r.NodeType != XmlNodeType.None) { - ReadReferencingElement(null, null, true, out dummy); + ReadReferencingElement(null, null, true, out _); _r.MoveToContent(); } DoFixups(); @@ -1790,8 +1789,7 @@ protected void ReadReferencedElements() [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] protected object? ReadReferencedElement(string? name, string? ns) { - string? dummy; - return ReadReferencingElement(name, ns, out dummy); + return ReadReferencingElement(name, ns, out _); } [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] @@ -1810,7 +1808,7 @@ protected void ReadReferencedElements() [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] protected object? ReadReferencingElement(string? name, string? ns, bool elementCanBeType, out string? fixupReference) { - object? o = null; + object? o; EnsureCallbackTables(); _r.MoveToContent(); @@ -1885,8 +1883,7 @@ private object ReadXmlNodes(bool elementCanBeType) string? xsiTypeName = null; string? xsiTypeNs = null; int skippableNodeCount = 0; - int lineNumber = -1, linePosition = -1; - XmlNode? unknownNode = null; + XmlNode? unknownNode; if (Reader.NodeType == XmlNodeType.Attribute) { XmlAttribute attr = Document.CreateAttribute(elemName, elemNs); @@ -1895,7 +1892,7 @@ private object ReadXmlNodes(bool elementCanBeType) } else unknownNode = Document.CreateElement(elemName, elemNs); - GetCurrentPosition(out lineNumber, out linePosition); + GetCurrentPosition(out _, out _); XmlElement? unknownElement = unknownNode as XmlElement; while (Reader.MoveToNextAttribute()) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 60701eeba407b..dcd12e683a766 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -1823,10 +1823,9 @@ private void WriteID(string? name) //return; name = ""; } - string? idName; - if (!_idNames.TryGetValue(name, out idName)) + if (!_idNames.ContainsKey(name)) { - idName = NextIdName(name); + string? idName = NextIdName(name); _idNames.Add(name, idName); _idNameFields.Add(name, this.typeBuilder.DefineField(idName, typeof(string), FieldAttributes.Private)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index 991be5cdf3a0a..e479a6b2662b7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -247,7 +247,7 @@ private XmlQualifiedName GetPrimitiveTypeName(Type type) [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] protected void WriteTypedPrimitive(string? name, string? ns, object o, bool xsiType) { - string? value = null; + string? value; string type; string typeNs = XmlSchema.Namespace; bool writeRaw = true; @@ -964,12 +964,6 @@ protected void WriteAttribute(string localName, string ns, byte[]? value) { if (ns == XmlReservedNs.NsXml) { - string? prefix = _w.LookupPrefix(ns); - - if (prefix == null || prefix.Length == 0) - { - prefix = "xml"; - } _w.WriteStartAttribute("xml", localName, ns); } else @@ -1679,21 +1673,21 @@ private void WriteMappingInfo(TypeMapping mapping, string typeVariable, for (int i = 0; i < structMapping.Members!.Length; i++) { MemberMapping member = structMapping.Members[i]; - string memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, member.Name); + WriteMemberInfo(type, typeFullName, typeVariable, member.Name); if (member.CheckShouldPersist) { string memberName = $"ShouldSerialize{member.Name}"; - memberVariable = WriteMethodInfo(typeFullName, typeVariable, memberName, false); + WriteMethodInfo(typeFullName, typeVariable, memberName, false); } if (member.CheckSpecified != SpecifiedAccessor.None) { string memberName = $"{member.Name}Specified"; - memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, memberName); + WriteMemberInfo(type, typeFullName, typeVariable, memberName); } if (member.ChoiceIdentifier != null) { string memberName = member.ChoiceIdentifier.MemberName!; - memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, memberName); + WriteMemberInfo(type, typeFullName, typeVariable, memberName); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index 1e22c1c4d4ea4..2b865d46501e7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -1228,7 +1228,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes { string methodName; Type methodType; - Type argType = typeof(string); + Type argType; // check to see if we can write values of the attribute sequentially if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index 0428b863df732..7b66766d4cab0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -587,7 +587,7 @@ public static XmlSerializer[] FromMappings(XmlMapping[]? mappings, Type? type) XmlSerializerImplementation? contract = null; Assembly? assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); - TempAssembly? tempAssembly = null; + TempAssembly? tempAssembly; if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.cs index 451e9eabbf6b5..abd0fbe00963c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.cs @@ -31,7 +31,7 @@ public DescendantBaseQuery(DescendantBaseQuery other) : base(other) { throw XPathException.Create(SR.Xp_InvalidPattern); } - XPathNavigator? result = null; + XPathNavigator? result; if (matches(context)) { if (matchSelf) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FunctionQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FunctionQuery.cs index e6269202f624d..7218c62e8a06b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FunctionQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FunctionQuery.cs @@ -100,7 +100,7 @@ public override object Evaluate(XPathNodeIterator nodeIterator) throw XPathException.Create(SR.Xp_InvalidPattern); } this.Evaluate(new XPathSingletonIterator(navigator!, /*moved:*/true)); - XPathNavigator? nav = null; + XPathNavigator? nav; while ((nav = this.Advance()) != null) { if (nav.IsSamePosition(navigator!)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs index d45bae233b8cf..e9de690235ddd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs @@ -55,7 +55,7 @@ private void Reset() private Query ProcessAxis(Axis root, Flags flags, out Props props) { - Query? result = null; + Query? result; if (root.Prefix.Length > 0) { _needContext = true; @@ -352,7 +352,7 @@ private Query ProcessVariable(Variable root) private Query ProcessFunction(Function root, out Props props) { props = Props.None; - Query? qy = null; + Query? qy; switch (root.TypeOfFunction) { case FT.FuncLast: @@ -504,9 +504,8 @@ private Query ProcessNode(AstNode root, Flags flags, out Props props) private Query Build(AstNode root, string query) { Reset(); - Props props; _query = query; - Query result = ProcessNode(root, Flags.None, out props); + Query result = ProcessNode(root, Flags.None, out _); return result; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/SortQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/SortQuery.cs index 51dff75b027fb..67d08831fd789 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/SortQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/SortQuery.cs @@ -195,7 +195,7 @@ public Query Expression(int i) int IComparer.Compare(SortKey? x, SortKey? y) { Debug.Assert(x != null && y != null, "Oops!! what happened?"); - int result = 0; + int result; for (int i = 0; i < x.NumKeys; i++) { result = _comparers[i].Compare(x[i], y[i]); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/UnionExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/UnionExpr.cs index c3f18463a6306..bc398077e62d1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/UnionExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/UnionExpr.cs @@ -86,7 +86,7 @@ private XPathNavigator ProcessAfterPosition(XPathNavigator res1, XPathNavigator public override XPathNavigator? Advance() { XPathNavigator? res1, res2; - XmlNodeOrder order = 0; + XmlNodeOrder order; if (_advance1) { res1 = qy1.Advance(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs index 8b0bbc78d81b4..d7edb4c9acbae 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs @@ -558,7 +558,7 @@ public override bool MoveToAttribute(string localName, string? namespaceName) { if (null == localName) throw new ArgumentNullException(nameof(localName)); - int depth = _depth; + int depth; XPathNavigator? nav = GetElemNav(out depth); if (null != nav) { @@ -711,7 +711,7 @@ public override bool MoveToAttribute(string name) ValidateNames.SplitQName(name, out prefix, out localname); // watch for a namespace name - bool IsXmlnsNoPrefix = false; + bool IsXmlnsNoPrefix; if ((IsXmlnsNoPrefix = (0 == prefix.Length && localname == "xmlns")) || (prefix == "xmlns")) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs index ea5cacea74813..7f2e13f22e52e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -89,8 +89,8 @@ public class XmlConvert int copyPosition = 0; int underscorePos = name.IndexOf('_'); - MatchCollection? mc = null; - IEnumerator? en = null; + MatchCollection? mc; + IEnumerator? en; if (underscorePos >= 0) { if (s_decodeCharPattern == null) @@ -201,7 +201,7 @@ public class XmlConvert int position = 0; int underscorePos = name.IndexOf('_'); - MatchCollection? mc = null; + MatchCollection? mc; IEnumerator? en = null; if (underscorePos >= 0) { @@ -396,9 +396,7 @@ internal static string VerifyQName(string name, ExceptionType exceptionType) throw new ArgumentNullException(nameof(name)); } - int colonPosition = -1; - - int endPos = ValidateNames.ParseQName(name, 0, out colonPosition); + int endPos = ValidateNames.ParseQName(name, 0, out _); if (endPos != name.Length) { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs index 57742531e80aa..05029d3ab6b49 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs @@ -422,7 +422,7 @@ public override int GetCharCount(byte[] bytes, int index, int count) public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // finish a character from the bytes that were cached last time - int i = lastBytesCount; + int i; if (lastBytesCount > 0) { // copy remaining bytes into the cache @@ -473,7 +473,7 @@ public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] bytesUsed = 0; charsUsed = 0; // finish a character from the bytes that were cached last time - int i = 0; + int i; int lbc = lastBytesCount; if (lbc > 0) { @@ -499,7 +499,6 @@ public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] charIndex += i; charCount -= i; - charsUsed = i; lastBytesCount = 0; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs index 29145c1c7371f..513066fcbedc6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs @@ -231,7 +231,6 @@ protected override void RecalculateType(QilNode node, XmlQueryType oldType) #region meta protected override QilNode VisitQilExpression(QilExpression local0) { - QilNode local1 = local0[0]; if (this[XmlILOptimization.EliminateUnusedGlobals]) { // PATTERN: [EliminateUnusedGlobals] $qil:(QilExpression *) => { ... } @@ -721,8 +720,6 @@ protected override QilNode VisitConditional(QilTernary local0) protected override QilNode VisitChoice(QilChoice local0) { - QilNode local1 = local0[0]; - QilNode local2 = local0[1]; if (this[XmlILOptimization.AnnotateConstruction]) { // PATTERN: [AnnotateConstruction] $ctor:(Choice * *) => { ... } @@ -3271,7 +3268,6 @@ protected override QilNode VisitFilter(QilLoop local0) protected override QilNode VisitSort(QilLoop local0) { QilNode local1 = local0[0]; - QilNode local2 = local0[1]; if (this[XmlILOptimization.FoldNone]) { if ((object?)((local1).XmlType) == (object)XmlQueryTypeFactory.None) @@ -3607,8 +3603,6 @@ protected override QilNode VisitFunction(QilFunction local0) { QilNode local1 = local0[0]; QilNode local2 = local0[1]; - QilNode local3 = local0[2]; - XmlQueryType? local4 = (XmlQueryType?)((QilFunction)local0).XmlType; if (((local0).XmlType!.IsSubtypeOf(XmlQueryTypeFactory.NodeS)) && (this[XmlILOptimization.AnnotateIndex1])) { if (((local1.Count == 2) && (((QilNode)(local1)[0]).XmlType!.IsSubtypeOf(XmlQueryTypeFactory.Node))) && ((((QilNode)(local1)[1]).XmlType) == (XmlQueryTypeFactory.StringX))) @@ -3730,7 +3724,6 @@ protected override QilNode VisitFunction(QilFunction local0) protected override QilNode VisitInvoke(QilInvoke local0) { QilNode local1 = local0[0]; - QilNode local2 = local0[1]; if (this[XmlILOptimization.NormalizeInvokeEmpty]) { if (local1.NodeType == QilNodeType.Function) @@ -4392,7 +4385,6 @@ protected override QilNode VisitNamespaceDecl(QilBinary local0) protected override QilNode VisitRtfCtor(QilBinary local0) { QilNode local1 = local0[0]; - QilNode local2 = local0[1]; if (this[XmlILOptimization.FoldNone]) { if ((object?)((local1).XmlType) == (object)XmlQueryTypeFactory.None) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs index 4316ebf70add7..e88c7c7210b3d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs @@ -410,7 +410,7 @@ public string NextName() /// the node name (unique across nodes) public string NameOf(QilNode n) { - string? name = null; + string? name; object? old = n.Annotation; NameAnnotation? a = old as NameAnnotation; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs index dba6c4bf8d555..24a74cfd38f76 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs @@ -60,7 +60,7 @@ public DecimalFormatter(string formatPicture, DecimalFormat decimalFormat) char perMilleSymbol = _posFormatInfo.PerMilleSymbol[0]; int commaIndex = 0; - int groupingSize = 0; + int groupingSize; int decimalIndex = -1; int lastDigitIndex = -1; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs index 36f2f469171fe..f645633dbbb47 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs @@ -377,10 +377,10 @@ public XmlNavigatorFilter GetTypeFilter(XPathNodeType nodeType) /// public XmlQualifiedName ParseTagName(string tagName, int indexPrefixMappings) { - string prefix, localName, ns; + string localName, ns; // Parse the tagName as a prefix, localName pair and resolve the prefix - ParseTagName(tagName, indexPrefixMappings, out prefix, out localName, out ns); + ParseTagName(tagName, indexPrefixMappings, out _, out localName, out ns); return new XmlQualifiedName(localName, ns); } @@ -390,10 +390,10 @@ public XmlQualifiedName ParseTagName(string tagName, int indexPrefixMappings) /// public XmlQualifiedName ParseTagName(string tagName, string ns) { - string prefix, localName; + string localName; // Parse the tagName as a prefix, localName pair - ValidateNames.ParseQNameThrow(tagName, out prefix, out localName); + ValidateNames.ParseQNameThrow(tagName, out _, out localName); return new XmlQualifiedName(localName, ns); } @@ -726,7 +726,7 @@ public bool MatchesXmlType(IList seq, int indexType) typBase = typBase.Prime; for (int i = 0; i < seq.Count; i++) { - if (!CreateXmlType(seq[0]).IsSubtypeOf(typBase)) + if (!CreateXmlType(seq[i]).IsSubtypeOf(typBase)) return false; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs index 327bd70c9f66b..8595d37ff3d5e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs @@ -186,7 +186,6 @@ private void NipOffTypeNameCheck() } // Recognized pattern A, check for B - QilNode x = isType; _nodeKind = nodeKinds; QilBinary lastAnd = leftPath[idx & 3]; @@ -200,7 +199,6 @@ private void NipOffTypeNameCheck() ) { // Recognized pattern B - x = lastAnd; _qname = (QilName?)((QilLiteral)eq.Right).Value; idx--; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs index 1a9097fed7c7d..4b4a5c508615f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs @@ -226,8 +226,7 @@ private QilExpression Compile(Compiler compiler) private QilNode InvokeOnCurrentNodeChanged() { Debug.Assert(IsDebug && _curLoop.IsFocusSet); - QilIterator i; - return _f.Loop(i = _f.Let(_f.InvokeOnCurrentNodeChanged(_curLoop.GetCurrent()!)), _f.Sequence()); + return _f.Loop(_f.Let(_f.InvokeOnCurrentNodeChanged(_curLoop.GetCurrent()!)), _f.Sequence()); } [Conditional("DEBUG")] @@ -1056,8 +1055,6 @@ private QilNode CompileAvt(string source) return result; } - private static readonly char[] s_curlyBraces = { '{', '}' }; - [return: NotNullIfNotNull("avt")] private QilNode? CompileStringAvt(string? avt) { @@ -1065,7 +1062,7 @@ private QilNode CompileAvt(string source) { return null; } - if (avt.IndexOfAny(s_curlyBraces) == -1) + if (avt.AsSpan().IndexOfAny('{', '}') < 0) { return _f.String(avt); } @@ -1075,7 +1072,7 @@ private QilNode CompileAvt(string source) private QilNode CompileTextAvt(string avt) { Debug.Assert(avt != null); - if (avt.IndexOfAny(s_curlyBraces) == -1) + if (avt.AsSpan().IndexOfAny('{', '}') < 0) { return _f.TextCtor(_f.String(avt)); } @@ -1623,8 +1620,8 @@ private void CompileDataTypeAttribute(string? attValue, bool fwdCompat, ref QilN if (!fwdCompat) { // check for qname-but-not-ncname - string prefix, local, nsUri; - bool isValid = _compiler.ParseQName(dataType, out prefix, out local, (IErrorHelper)this); + string prefix, nsUri; + bool isValid = _compiler.ParseQName(dataType, out prefix, out _, (IErrorHelper)this); nsUri = isValid ? ResolvePrefix(/*ignoreDefaultNs:*/true, prefix) : _compiler.CreatePhantomNamespace(); if (nsUri.Length == 0) @@ -1640,13 +1637,13 @@ private void CompileDataTypeAttribute(string? attValue, bool fwdCompat, ref QilN else { // Precalculate its value outside of for-each loop - QilIterator dt, qname; + QilIterator dt; result = _f.Loop(dt = _f.Let(result), _f.Conditional(_f.Eq(dt, _f.String(DtNumber)), _f.False(), _f.Conditional(_f.Eq(dt, _f.String(DtText)), _f.True(), fwdCompat ? _f.True() : - _f.Loop(qname = _f.Let(ResolveQNameDynamic(/*ignoreDefaultNs:*/true, dt)), + _f.Loop(_f.Let(ResolveQNameDynamic(/*ignoreDefaultNs:*/true, dt)), _f.Error(_lastScope!.SourceLine, SR.Xslt_BistateAttribute, "data-type", DtText, DtNumber ) @@ -1787,7 +1784,6 @@ private void CompileSort(Sort sort, QilList keyList, ref LoopFocus parentLoop) _strConcat.Append(separator); _strConcat.Append("upperFirst="); _strConcat.Append(caseOrder); - separator = '&'; } QilNode collation = _strConcat.ToQil(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs index b893962edeadd..b3ecb042a8690 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs @@ -83,7 +83,7 @@ public void AddEdge(V v1, V v2) // NOTE: We do not check for duplicate edges here adjList.Add(v2); - if (!TryGetValue(v2, out adjList)) + if (!TryGetValue(v2, out _)) { this[v2] = null; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs index 77a16b8600fd1..a9e764763c5b4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs @@ -848,7 +848,7 @@ private void LoadKey(NsDecl? stylesheetNsList) _input.MoveToElement(); - List? content = null; + List? content; if (V1) { @@ -1300,11 +1300,7 @@ private void LoadMsScript(NsDecl? stylesheetNsList) { scriptNs = _compiler.CreatePhantomNamespace(); } - string? language = ParseStringAttribute(1, "language"); - if (language == null) - { - language = "jscript"; - } + ParseStringAttribute(1, "language"); if (!_compiler.Settings.EnableScript) { @@ -1856,7 +1852,6 @@ private XslNode XslValueOf() { if (!_input.BackwardCompatibility) { - separator = select != null ? " " : string.Empty; } } else @@ -1864,7 +1859,7 @@ private XslNode XslValueOf() ReportNYI("xsl:value-of/@separator"); } - List? content = null; + List? content; if (V1) { @@ -1882,7 +1877,6 @@ private XslNode XslValueOf() if (content.Count != 0) { ReportNYI("xsl:value-of/*"); - content = null; } } @@ -2111,7 +2105,6 @@ private XslNode XslAttribute() if (select != null) ReportNYI("xsl:attribute/@select"); string? separator = ParseStringAttribute(3, "separator"); if (separator != null) ReportNYI("xsl:attribute/@separator"); - separator = separator != null ? separator : (select != null ? " " : string.Empty); ParseTypeAttribute(4); ParseValidationAttribute(5, /*defVal:*/false); @@ -2147,7 +2140,7 @@ private XslNode XslSort(int sortNumber) CheckError(sortNumber != 0, SR.Xslt_SortStable); } - List? content = null; + List? content; if (V1) { CheckNoContent(); @@ -2158,7 +2151,6 @@ private XslNode XslSort(int sortNumber) if (content.Count != 0) { ReportNYI("xsl:sort/*"); - content = null; } } @@ -2838,8 +2830,8 @@ private QilName CreateXPathQName(string qname) // Does not suppress errors private XmlQualifiedName ResolveQName(bool ignoreDefaultNs, string qname) { - string prefix, localName, namespaceName; - ResolveQName(ignoreDefaultNs, qname, out localName, out namespaceName, out prefix); + string localName, namespaceName; + ResolveQName(ignoreDefaultNs, qname, out localName, out namespaceName, out _); return new XmlQualifiedName(localName, namespaceName); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ChooseAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ChooseAction.cs index 2a7935d7d885f..3dce8434b944e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ChooseAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ChooseAction.cs @@ -38,7 +38,7 @@ private void CompileConditions(Compiler compiler) if (Ref.Equal(nspace, input.Atoms.UriXsl)) { - IfAction? action = null; + IfAction? action; if (Ref.Equal(name, input.Atoms.When)) { if (otherwise) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs index 52f256dfdd2fc..b38aec5b1267d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs @@ -959,8 +959,7 @@ internal ArrayList CompileAvt(string avtText, out bool constant) internal ArrayList CompileAvt(string avtText) { - bool constant; - return CompileAvt(avtText, out constant); + return CompileAvt(avtText, out _); } // Compiler is a class factory for some actions: diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs index e315c71d0d52c..b9aa4d89e25b8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs @@ -485,8 +485,7 @@ private double NameTest(string name) } else { - string prefix, localname; - PrefixQName.ParseQualifiedName(name, out prefix, out localname); + PrefixQName.ParseQualifiedName(name, out _, out _); return 0; } } @@ -673,7 +672,7 @@ protected void CompileOnceTemplate(Compiler compiler) private void CompileInstruction(Compiler compiler) { NavigatorInput input = compiler.Input; - CompiledAction? action = null; + CompiledAction? action; Debug.Assert(Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs index 6c5051d49bafa..7c38c5269e1a6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs @@ -653,8 +653,6 @@ private static void mapFormatToken(string wsToken, int startLen, int tokLen, out { // 60-based Zodiak numbering begins with two characters seq = NumberingSequence.Zodiac3; - tokLen--; - startLen++; } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScopeManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScopeManager.cs index 8cce6af5e27e2..4a3dd2419d2a8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScopeManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScopeManager.cs @@ -107,8 +107,7 @@ internal void PopScope() internal string? ResolveNamespace(string prefix) { - bool thisScope; - return ResolveNamespace(prefix, out thisScope); + return ResolveNamespace(prefix, out _); } internal string? ResolveNamespace(string prefix, out bool thisScope) @@ -156,7 +155,7 @@ internal bool FindPrefix(string nspace, out string? prefix) Debug.Assert(_elementScopesStack[i] is OutputScope); OutputScope elementScope = (OutputScope)_elementScopesStack[i]; - string? pfx = null; + string? pfx; if (elementScope.FindPrefix(nspace, out pfx)) { string? testNspace = ResolveNamespace(pfx); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs index 7eec614316236..28610ebc78174 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs @@ -160,7 +160,7 @@ internal Key[]? KeyList internal XPathNavigator GetNavigator(Uri ruri) { - XPathNavigator? result = null; + XPathNavigator? result; if (_documentCache != null) { result = _documentCache[ruri] as XPathNavigator; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs index 5e5c646ffe3f1..9aed9e0b69edc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RecordBuilder.cs @@ -337,7 +337,7 @@ private void BeginAttribute(string prefix, string name, string nspace, object? h private void BeginNamespace(string name, string nspace) { - bool thisScope = false; + bool thisScope; if (Ref.Equal(name, _atoms.Empty)) { if (Ref.Equal(nspace, _scopeManager.DefaultNamespace)) @@ -529,7 +529,7 @@ private void FixupElement() } else { - bool thisScope = false; + bool thisScope; string? nspace = _scopeManager.ResolveNamespace(_mainNode.Prefix, out thisScope); if (nspace != null) { @@ -575,7 +575,7 @@ private void FixupAttributes(int attributeCount) } else { - bool thisScope = false; + bool thisScope; string? nspace = _scopeManager.ResolveNamespace(info.Prefix, out thisScope); if (nspace != null) { @@ -770,7 +770,7 @@ private string DeclareNewNamespace(string nspace) internal string GetPrefixForNamespace(string nspace) { - string? prefix = null; + string? prefix; if (_scopeManager.FindPrefix(nspace, out prefix)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SortAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SortAction.cs index b03f30517b9fa..5d454c7f32941 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SortAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/SortAction.cs @@ -62,8 +62,8 @@ private XmlDataType ParseDataType(string? value, InputScopeManager manager) { return XmlDataType.Number; } - string prefix, localname; - PrefixQName.ParseQualifiedName(value, out prefix, out localname); + string prefix; + PrefixQName.ParseQualifiedName(value, out prefix, out _); manager.ResolveXmlNamespace(prefix); if (prefix.Length == 0 && !_forwardCompatibility) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs index 4b73d0950126c..39145741848ed 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateLookupAction.cs @@ -25,7 +25,7 @@ internal override void Execute(Processor processor, ActionFrame frame) Debug.Assert(processor != null && frame != null); Debug.Assert(frame.State == Initialized); - Action? action = null; + Action? action; if (this.mode != null) { @@ -102,7 +102,7 @@ internal override void Execute(Processor processor, ActionFrame frame) Debug.Assert(frame.State == Initialized); Debug.Assert(processor.Debugger != null); - Action? action = null; + Action? action; if (this.mode == Compiler.BuiltInMode) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs index af038b5711cf0..abff50de6c97a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs @@ -178,7 +178,6 @@ public override bool PreserveWhitespace(XPathNavigator node) methods[free++] = methods[i]; } } - length = free; return methods[0]; } @@ -215,7 +214,7 @@ public override bool PreserveWhitespace(XPathNavigator node) public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] argTypes) { - IXsltContextFunction? func = null; + IXsltContextFunction? func; if (prefix.Length == 0) { func = s_FunctionTable[name] as IXsltContextFunction; @@ -485,8 +484,7 @@ private bool FunctionAvailable(string qname) else { // Is this script or extention function? - object? extension; - return GetExtentionMethod(ns, name, /*argTypes*/null, out extension) != null; + return GetExtentionMethod(ns, name, /*argTypes*/null, out _) != null; } } diff --git a/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/System.Xml.Xsl.XslCompiledTransformApi.Tests.csproj b/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/System.Xml.Xsl.XslCompiledTransformApi.Tests.csproj index 2349cc2a966b3..697c0cc5a9e63 100644 --- a/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/System.Xml.Xsl.XslCompiledTransformApi.Tests.csproj +++ b/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/System.Xml.Xsl.XslCompiledTransformApi.Tests.csproj @@ -2,6 +2,15 @@ $(NetCoreAppCurrent) + + + + WasmTestOnBrowser + $(TestArchiveRoot)browserornodejs/ + $(TestArchiveTestsRoot)$(OSPlatformConfig)/ + $(DefineConstants);TARGET_BROWSER + + diff --git a/src/libraries/System.Private.Xml/tests/Xslt/XslTransformApi/System.Xml.Xsl.XslTransformApi.Tests.csproj b/src/libraries/System.Private.Xml/tests/Xslt/XslTransformApi/System.Xml.Xsl.XslTransformApi.Tests.csproj index 904076419ca09..08280f2142870 100644 --- a/src/libraries/System.Private.Xml/tests/Xslt/XslTransformApi/System.Xml.Xsl.XslTransformApi.Tests.csproj +++ b/src/libraries/System.Private.Xml/tests/Xslt/XslTransformApi/System.Xml.Xsl.XslTransformApi.Tests.csproj @@ -2,6 +2,15 @@ $(NetCoreAppCurrent) + + + + WasmTestOnBrowser + $(TestArchiveRoot)browserornodejs/ + $(TestArchiveTestsRoot)$(OSPlatformConfig)/ + $(DefineConstants);TARGET_BROWSER + + diff --git a/src/libraries/System.Private.Xml/tests/Xslt/XsltCompiler/XsltCompiler.Tests.csproj b/src/libraries/System.Private.Xml/tests/Xslt/XsltCompiler/XsltCompiler.Tests.csproj index 4fa9ed0e9ce82..3a91657ef67b0 100644 --- a/src/libraries/System.Private.Xml/tests/Xslt/XsltCompiler/XsltCompiler.Tests.csproj +++ b/src/libraries/System.Private.Xml/tests/Xslt/XsltCompiler/XsltCompiler.Tests.csproj @@ -2,6 +2,15 @@ $(NetCoreAppCurrent) + + + + WasmTestOnBrowser + $(TestArchiveRoot)browserornodejs/ + $(TestArchiveTestsRoot)$(OSPlatformConfig)/ + $(DefineConstants);TARGET_BROWSER + + diff --git a/src/libraries/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj b/src/libraries/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj index 5088eb6beba6b..0360c466275e9 100644 --- a/src/libraries/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj +++ b/src/libraries/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj @@ -6,7 +6,7 @@ $(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum) enable true - This packages provides a low-level .NET (ECMA-335) metadata reader and writer. It's geared for performance and is the ideal choice for building higher-level libraries that intend to provide their own object model, such as compilers. + This package provides a low-level .NET (ECMA-335) metadata reader and writer. It's geared for performance and is the ideal choice for building higher-level libraries that intend to provide their own object model, such as compilers. Commonly Used Types: System.Reflection.Metadata.MetadataReader diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BlobUtilities.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BlobUtilities.cs index ca27815bde9fb..dd990afe48b5b 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BlobUtilities.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BlobUtilities.cs @@ -252,8 +252,7 @@ internal static unsafe int GetUTF8ByteCount(string str) internal static unsafe int GetUTF8ByteCount(char* str, int charCount) { - char* remainder; - return GetUTF8ByteCount(str, charCount, int.MaxValue, out remainder); + return GetUTF8ByteCount(str, charCount, int.MaxValue, out _); } internal static int GetUTF8ByteCount(char* str, int charCount, int byteLimit, out char* remainder) diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs index a938d8766bec3..77a4ee2acbc3c 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/MemoryBlock.cs @@ -59,8 +59,7 @@ private string GetDebuggerDisplay() return ""; } - int displayedBytes; - return GetDebuggerDisplay(out displayedBytes); + return GetDebuggerDisplay(out _); } internal string GetDebuggerDisplay(out int displayedBytes) @@ -375,13 +374,11 @@ internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) { - int firstDifference; - FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifference, terminator, ignoreCase); + FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out _, terminator, ignoreCase); if (result == FastComparisonResult.Inconclusive) { - int bytesRead; - string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator); + string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out _, terminator); return decoded.Equals(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } @@ -391,8 +388,7 @@ internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDe // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) { - int endIndex; - FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out endIndex, terminator, ignoreCase); + FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out _, terminator, ignoreCase); switch (result) { @@ -406,8 +402,7 @@ internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStri default: Debug.Assert(result == FastComparisonResult.Inconclusive); - int bytesRead; - string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator); + string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out _, terminator); return decoded.StartsWith(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs index c2b0151b9ffca..57f130a8ffd46 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs @@ -163,19 +163,17 @@ private string GetNonVirtualString(StringHandle handle, MetadataStringDecoder ut { Debug.Assert(handle.StringKind != StringKind.Virtual); - int bytesRead; char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; - return Block.PeekUtf8NullTerminated(handle.GetHeapOffset(), prefixOpt, utf8Decoder, out bytesRead, otherTerminator); + return Block.PeekUtf8NullTerminated(handle.GetHeapOffset(), prefixOpt, utf8Decoder, out _, otherTerminator); } private unsafe MemoryBlock GetNonVirtualStringMemoryBlock(StringHandle handle) { Debug.Assert(handle.StringKind != StringKind.Virtual); - int bytesRead; char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; int offset = handle.GetHeapOffset(); - int length = Block.GetUtf8NullTerminatedLength(offset, out bytesRead, otherTerminator); + int length = Block.GetUtf8NullTerminatedLength(offset, out _, otherTerminator); return new MemoryBlock(Block.Pointer + offset, length); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs index 49a0debe174ce..de4c80edffac8 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.WinMD.cs @@ -327,8 +327,7 @@ internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); - bool isIDisposable; - int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable); + int projectionIndex = GetProjectionIndexForTypeReference(handle, out _); if (projectionIndex >= 0) { return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, projectionIndex); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs index 925bd4fa6f4a7..b1e1b01c64302 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs @@ -205,8 +205,7 @@ private void ReadMetadataHeader(ref BlobReader memReader, out string versionStri throw new BadImageFormatException(SR.NotEnoughSpaceForVersionString); } - int numberOfBytesRead; - versionString = memReader.GetMemoryBlockAt(0, versionStringSize).PeekUtf8NullTerminated(0, null, UTF8Decoder, out numberOfBytesRead, '\0'); + versionString = memReader.GetMemoryBlockAt(0, versionStringSize).PeekUtf8NullTerminated(0, null, UTF8Decoder, out _, '\0'); memReader.Offset += versionStringSize; } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.CoreAssembly.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.CoreAssembly.cs index 0a0de6a52a338..924f4b91ff8c8 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.CoreAssembly.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/MetadataLoadContext.CoreAssembly.cs @@ -14,7 +14,6 @@ public sealed partial class MetadataLoadContext // Cache loaded coreAssembly and core types. internal RoAssembly? TryGetCoreAssembly(string? coreAssemblyName, out Exception? e) { - e = null; Debug.Assert(_coreAssembly == null); if (coreAssemblyName == null) { diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodBody.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodBody.cs index 8169a6ac7dbf4..5d81222a07db2 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodBody.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/MethodBase/Ecma/EcmaMethodBody.cs @@ -42,7 +42,7 @@ public sealed override IList LocalVariables { bool isPinned = false; RoType localType = sig[i]; - if (localType is RoPinnedType roPinnedType) + if (localType is RoPinnedType) { isPinned = true; localType = localType.SkipTypeWrappers(); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Parameters/Ecma/EcmaFatMethodParameter.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Parameters/Ecma/EcmaFatMethodParameter.cs index 13cb8f694f8e3..099a41b7e6d56 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Parameters/Ecma/EcmaFatMethodParameter.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Parameters/Ecma/EcmaFatMethodParameter.cs @@ -51,7 +51,6 @@ public sealed override object? RawDefaultValue private bool TryGetRawDefaultValue(out object? rawDefaultValue) { - rawDefaultValue = null; MetadataReader reader = Reader; ConstantHandle ch = Parameter.GetDefaultValue(); if (!ch.IsNil) diff --git a/src/libraries/System.Runtime.Extensions/tests/System/EnvironmentTests.cs b/src/libraries/System.Runtime.Extensions/tests/System/EnvironmentTests.cs index 415cafb9f02c2..8c6fc1a78d47b 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/EnvironmentTests.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/EnvironmentTests.cs @@ -236,7 +236,7 @@ public void Version_Valid() [Fact] public void WorkingSet_Valid() { - if (PlatformDetection.IsBrowser) + if (PlatformDetection.IsBrowser || (PlatformDetection.IsiOS && !PlatformDetection.IsMacCatalyst) || PlatformDetection.IstvOS) Assert.Equal(0, Environment.WorkingSet); else Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value"); diff --git a/src/libraries/System.Runtime.InteropServices/gen/DllImportGenerator/DllImportGenerator.csproj b/src/libraries/System.Runtime.InteropServices/gen/DllImportGenerator/DllImportGenerator.csproj index 85f7a7c0c00bc..b3baca91121a9 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/DllImportGenerator/DllImportGenerator.csproj +++ b/src/libraries/System.Runtime.InteropServices/gen/DllImportGenerator/DllImportGenerator.csproj @@ -16,8 +16,8 @@ Microsoft - https://github.com/dotnet/runtimelab/tree/feature/DllImportGenerator - https://github.com/dotnet/runtimelab/tree/feature/DllImportGenerator + https://github.com/dotnet/runtime/tree/main/src/libraries/System.Runtime.InteropServices/gen/DllImportGenerator + https://github.com/dotnet/runtime/ false DllImportGenerator Summary of changes made in this release of the package. @@ -26,10 +26,6 @@ true - - https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet5/nuget/v3/index.json ;$(RestoreAdditionalProjectSources) - - diff --git a/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.Forwards.cs b/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.Forwards.cs index 4cf2e0e22a369..d1fedae069dde 100644 --- a/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.Forwards.cs +++ b/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.Forwards.cs @@ -11,4 +11,5 @@ [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.InAttribute))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.SafeBuffer))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.SafeHandle))] +[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.UnmanagedType))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.Missing))] diff --git a/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs b/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs index 6fa5eb10ea0d4..901b76346b82c 100644 --- a/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs +++ b/src/libraries/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs @@ -999,61 +999,6 @@ public sealed partial class UnmanagedFunctionPointerAttribute : System.Attribute public UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention callingConvention) { } public System.Runtime.InteropServices.CallingConvention CallingConvention { get { throw null; } } } - public enum UnmanagedType - { - Bool = 2, - I1 = 3, - U1 = 4, - I2 = 5, - U2 = 6, - I4 = 7, - U4 = 8, - I8 = 9, - U8 = 10, - R4 = 11, - R8 = 12, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("Marshalling as Currency may be unavailable in future releases.")] - Currency = 15, - BStr = 19, - LPStr = 20, - LPWStr = 21, - LPTStr = 22, - ByValTStr = 23, - IUnknown = 25, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - IDispatch = 26, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - Struct = 27, - Interface = 28, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - SafeArray = 29, - ByValArray = 30, - SysInt = 31, - SysUInt = 32, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("Marshalling as VBByRefString may be unavailable in future releases.")] - VBByRefStr = 34, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("Marshalling as AnsiBStr may be unavailable in future releases.")] - AnsiBStr = 35, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("Marshalling as TBstr may be unavailable in future releases.")] - TBStr = 36, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - VariantBool = 37, - FunctionPtr = 38, - [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] - [System.ObsoleteAttribute("Marshalling arbitrary types may be unavailable in future releases. Specify the type you wish to marshal as.")] - AsAny = 40, - LPArray = 42, - LPStruct = 43, - CustomMarshaler = 44, - Error = 45, - IInspectable = 46, - HString = 47, - LPUTF8Str = 48, - } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public enum VarEnum { diff --git a/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ObjectiveC/MessageSendTests.cs b/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ObjectiveC/MessageSendTests.cs index 8ccf493a3795e..10104a0a0bb77 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ObjectiveC/MessageSendTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ObjectiveC/MessageSendTests.cs @@ -71,6 +71,11 @@ public void SetMessageSendCallback_AlreadySet() var (msgSend, func) = msgSendOverrides[0]; ObjectiveCMarshal.SetMessageSendCallback(msgSend, func); Assert.Throws(() => ObjectiveCMarshal.SetMessageSendCallback(msgSend, func)); + + // TODO: Remove once https://github.com/dotnet/arcade/issues/5865 is resolved + // RemoteExecutor currently only checks the expected exit code if the invoked function returns an int. + // Check the exit code to ensure the test will fail if there was a crash that could not be caught by the executor. + return RemoteExecutor.SuccessExitCode; }).Dispose(); } @@ -97,6 +102,11 @@ public void SetMessageSendCallback(MessageSendFunction[] funcsToOverride) } SetMessageSendCallbackImpl(msgSendArray); + + // TODO: Remove once https://github.com/dotnet/arcade/issues/5865 is resolved + // RemoteExecutor currently only checks the expected exit code if the invoked function returns an int. + // Check the exit code to ensure the test will fail if there was a crash that could not be caught by the executor. + return RemoteExecutor.SuccessExitCode; }, string.Join(';', funcsToOverride)).Dispose(); } @@ -150,4 +160,3 @@ private static void SetMessageSendCallbackImpl(MessageSendFunction[] funcsToOver } } } - diff --git a/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ObjectiveC/PendingExceptionTests.cs b/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ObjectiveC/PendingExceptionTests.cs index c17f2915a8dd3..5a67e3367eaff 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ObjectiveC/PendingExceptionTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ObjectiveC/PendingExceptionTests.cs @@ -59,6 +59,11 @@ public void ValidateSetMessageSendPendingException(MessageSendFunction func) Assert.True(Enum.IsDefined(msgSend)); ValidateSetMessageSendPendingExceptionImpl(msgSend); + + // TODO: Remove once https://github.com/dotnet/arcade/issues/5865 is resolved + // RemoteExecutor currently only checks the expected exit code if the invoked function returns an int. + // Check the exit code to ensure the test will fail if there was a crash that could not be caught by the executor. + return RemoteExecutor.SuccessExitCode; }, func.ToString()).Dispose(); } @@ -95,4 +100,4 @@ private static void ValidateSetMessageSendPendingExceptionImpl(MessageSendFuncti Assert.Equal(msgSend.ToString(), ex.Message); } } -} \ No newline at end of file +} diff --git a/src/libraries/System.Runtime.Intrinsics/ref/System.Runtime.Intrinsics.cs b/src/libraries/System.Runtime.Intrinsics/ref/System.Runtime.Intrinsics.cs index bc79e1ed629d3..68f2b6005d5f5 100644 --- a/src/libraries/System.Runtime.Intrinsics/ref/System.Runtime.Intrinsics.cs +++ b/src/libraries/System.Runtime.Intrinsics/ref/System.Runtime.Intrinsics.cs @@ -146,6 +146,8 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector128 vector, public static bool EqualsAll(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } public static bool EqualsAny(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 Equals(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static uint ExtractMostSignificantBits(this System.Runtime.Intrinsics.Vector128 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 Floor(System.Runtime.Intrinsics.Vector128 vector) { throw null; } public static System.Runtime.Intrinsics.Vector128 Floor(System.Runtime.Intrinsics.Vector128 vector) { throw null; } public static T GetElement(this System.Runtime.Intrinsics.Vector128 vector, int index) where T : struct { throw null; } @@ -163,6 +165,15 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector128 vector, public static bool LessThanOrEqualAny(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 LessThanOrEqual(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 LessThan(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector128 Load(T* source) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector128 LoadAligned(T* source) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector128 LoadAlignedNonTemporal(T* source) where T : unmanaged { throw null; } + public static System.Runtime.Intrinsics.Vector128 LoadUnsafe(ref T source) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 LoadUnsafe(ref T source, nuint elementOffset) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 Max(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 Min(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 Multiply(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } @@ -181,8 +192,54 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector128 vector, public static System.Runtime.Intrinsics.Vector128 Narrow(System.Runtime.Intrinsics.Vector128 lower, System.Runtime.Intrinsics.Vector128 upper) { throw null; } public static System.Runtime.Intrinsics.Vector128 Negate(System.Runtime.Intrinsics.Vector128 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 OnesComplement(System.Runtime.Intrinsics.Vector128 vector) where T : struct { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftLeft(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector128 ShiftRightLogical(System.Runtime.Intrinsics.Vector128 vector, int shiftCount) { throw null; } public static System.Runtime.Intrinsics.Vector128 Sqrt(System.Runtime.Intrinsics.Vector128 vector) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void Store(this System.Runtime.Intrinsics.Vector128 source, T* destination) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void StoreAligned(this System.Runtime.Intrinsics.Vector128 source, T* destination) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void StoreAlignedNonTemporal(this System.Runtime.Intrinsics.Vector128 source, T* destination) where T : unmanaged { throw null; } + public static void StoreUnsafe(this System.Runtime.Intrinsics.Vector128 source, ref T destination) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static void StoreUnsafe(this System.Runtime.Intrinsics.Vector128 source, ref T destination, nuint elementOffset) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 Subtract(System.Runtime.Intrinsics.Vector128 left, System.Runtime.Intrinsics.Vector128 right) where T : struct { throw null; } + public static T Sum(System.Runtime.Intrinsics.Vector128 vector) where T : struct { throw null; } public static T ToScalar(this System.Runtime.Intrinsics.Vector128 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 ToVector256Unsafe(this System.Runtime.Intrinsics.Vector128 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 ToVector256(this System.Runtime.Intrinsics.Vector128 vector) where T : struct { throw null; } @@ -363,6 +420,8 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector256 vector, public static bool EqualsAll(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } public static bool EqualsAny(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 Equals(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static uint ExtractMostSignificantBits(this System.Runtime.Intrinsics.Vector256 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 Floor(System.Runtime.Intrinsics.Vector256 vector) { throw null; } public static System.Runtime.Intrinsics.Vector256 Floor(System.Runtime.Intrinsics.Vector256 vector) { throw null; } public static T GetElement(this System.Runtime.Intrinsics.Vector256 vector, int index) where T : struct { throw null; } @@ -380,6 +439,15 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector256 vector, public static bool LessThanOrEqualAny(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 LessThanOrEqual(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 LessThan(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector256 Load(T* source) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector256 LoadAligned(T* source) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector256 LoadAlignedNonTemporal(T* source) where T : unmanaged { throw null; } + public static System.Runtime.Intrinsics.Vector256 LoadUnsafe(ref T source) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 LoadUnsafe(ref T source, nuint elementOffset) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 Max(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 Min(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 Multiply(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } @@ -398,8 +466,54 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector256 vector, public static System.Runtime.Intrinsics.Vector256 Narrow(System.Runtime.Intrinsics.Vector256 lower, System.Runtime.Intrinsics.Vector256 upper) { throw null; } public static System.Runtime.Intrinsics.Vector256 Negate(System.Runtime.Intrinsics.Vector256 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 OnesComplement(System.Runtime.Intrinsics.Vector256 vector) where T : struct { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftLeft(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector256 ShiftRightLogical(System.Runtime.Intrinsics.Vector256 vector, int shiftCount) { throw null; } public static System.Runtime.Intrinsics.Vector256 Sqrt(System.Runtime.Intrinsics.Vector256 vector) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void Store(this System.Runtime.Intrinsics.Vector256 source, T* destination) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void StoreAligned(this System.Runtime.Intrinsics.Vector256 source, T* destination) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void StoreAlignedNonTemporal(this System.Runtime.Intrinsics.Vector256 source, T* destination) where T : unmanaged { throw null; } + public static void StoreUnsafe(this System.Runtime.Intrinsics.Vector256 source, ref T destination) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static void StoreUnsafe(this System.Runtime.Intrinsics.Vector256 source, ref T destination, nuint elementOffset) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector256 Subtract(System.Runtime.Intrinsics.Vector256 left, System.Runtime.Intrinsics.Vector256 right) where T : struct { throw null; } + public static T Sum(System.Runtime.Intrinsics.Vector256 vector) where T : struct { throw null; } public static T ToScalar(this System.Runtime.Intrinsics.Vector256 vector) where T : struct { throw null; } public static bool TryCopyTo(this System.Runtime.Intrinsics.Vector256 vector, System.Span destination) where T : struct { throw null; } [System.CLSCompliantAttribute(false)] @@ -554,6 +668,8 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector64 vector, public static bool EqualsAll(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } public static bool EqualsAny(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 Equals(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static uint ExtractMostSignificantBits(this System.Runtime.Intrinsics.Vector64 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 Floor(System.Runtime.Intrinsics.Vector64 vector) { throw null; } public static System.Runtime.Intrinsics.Vector64 Floor(System.Runtime.Intrinsics.Vector64 vector) { throw null; } public static T GetElement(this System.Runtime.Intrinsics.Vector64 vector, int index) where T : struct { throw null; } @@ -569,6 +685,15 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector64 vector, public static bool LessThanOrEqualAny(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 LessThanOrEqual(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 LessThan(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector64 Load(T* source) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector64 LoadAligned(T* source) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe System.Runtime.Intrinsics.Vector64 LoadAlignedNonTemporal(T* source) where T : unmanaged { throw null; } + public static System.Runtime.Intrinsics.Vector64 LoadUnsafe(ref T source) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 LoadUnsafe(ref T source, nuint elementOffset) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 Max(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 Min(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 Multiply(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } @@ -587,8 +712,54 @@ public static void CopyTo(this System.Runtime.Intrinsics.Vector64 vector, public static System.Runtime.Intrinsics.Vector64 Narrow(System.Runtime.Intrinsics.Vector64 lower, System.Runtime.Intrinsics.Vector64 upper) { throw null; } public static System.Runtime.Intrinsics.Vector64 Negate(System.Runtime.Intrinsics.Vector64 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 OnesComplement(System.Runtime.Intrinsics.Vector64 vector) where T : struct { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftLeft(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftRightArithmetic(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } + [System.CLSCompliantAttribute(false)] + public static System.Runtime.Intrinsics.Vector64 ShiftRightLogical(System.Runtime.Intrinsics.Vector64 vector, int shiftCount) { throw null; } public static System.Runtime.Intrinsics.Vector64 Sqrt(System.Runtime.Intrinsics.Vector64 vector) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void Store(this System.Runtime.Intrinsics.Vector64 source, T* destination) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void StoreAligned(this System.Runtime.Intrinsics.Vector64 source, T* destination) where T : unmanaged { throw null; } + [System.CLSCompliantAttribute(false)] + public static unsafe void StoreAlignedNonTemporal(this System.Runtime.Intrinsics.Vector64 source, T* destination) where T : unmanaged { throw null; } + public static void StoreUnsafe(this System.Runtime.Intrinsics.Vector64 source, ref T destination) where T : struct { throw null; } + [System.CLSCompliantAttribute(false)] + public static void StoreUnsafe(this System.Runtime.Intrinsics.Vector64 source, ref T destination, nuint elementOffset) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector64 Subtract(System.Runtime.Intrinsics.Vector64 left, System.Runtime.Intrinsics.Vector64 right) where T : struct { throw null; } + public static T Sum(System.Runtime.Intrinsics.Vector64 vector) where T : struct { throw null; } public static T ToScalar(this System.Runtime.Intrinsics.Vector64 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 ToVector128Unsafe(this System.Runtime.Intrinsics.Vector64 vector) where T : struct { throw null; } public static System.Runtime.Intrinsics.Vector128 ToVector128(this System.Runtime.Intrinsics.Vector64 vector) where T : struct { throw null; } diff --git a/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector128Tests.cs b/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector128Tests.cs index 7fa5060680f49..67ab0317761f9 100644 --- a/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector128Tests.cs +++ b/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector128Tests.cs @@ -1,13 +1,3822 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; +using System.Runtime.InteropServices; using Xunit; namespace System.Runtime.Intrinsics.Tests.Vectors { public sealed class Vector128Tests { + [Fact] + public unsafe void Vector128ByteExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80 + ); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010_10101010u, result); + } + + [Fact] + public unsafe void Vector128DoubleExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + +1.0, + -0.0 + ); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + + [Fact] + public unsafe void Vector128Int16ExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000 + ).AsInt16(); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + + [Fact] + public unsafe void Vector128Int32ExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U + ).AsInt32(); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + + [Fact] + public unsafe void Vector128Int64ExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + 0x0000000000000001UL, + 0x8000000000000000UL + ).AsInt64(); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + + [Fact] + public unsafe void Vector128NIntExtractMostSignificantBitsTest() + { + if (Environment.Is64BitProcess) + { + Vector128 vector = Vector128.Create( + 0x0000000000000001UL, + 0x8000000000000000UL + ).AsNInt(); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + else + { + Vector128 vector = Vector128.Create( + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U + ).AsNInt(); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + } + + [Fact] + public unsafe void Vector128NUIntExtractMostSignificantBitsTest() + { + if (Environment.Is64BitProcess) + { + Vector128 vector = Vector128.Create( + 0x0000000000000001UL, + 0x8000000000000000UL + ).AsNUInt(); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + else + { + Vector128 vector = Vector128.Create( + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U + ).AsNUInt(); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + } + + [Fact] + public unsafe void Vector128SByteExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80 + ).AsSByte(); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010_10101010u, result); + } + + [Fact] + public unsafe void Vector128SingleExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + +1.0f, + -0.0f, + +1.0f, + -0.0f + ); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + + [Fact] + public unsafe void Vector128UInt16ExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000 + ); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + + [Fact] + public unsafe void Vector128UInt32ExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U + ); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + + [Fact] + public unsafe void Vector128UInt64ExtractMostSignificantBitsTest() + { + Vector128 vector = Vector128.Create( + 0x0000000000000001UL, + 0x8000000000000000UL + ); + + uint result = Vector128.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + + [Fact] + public unsafe void Vector128ByteLoadTest() + { + byte* value = stackalloc byte[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128DoubleLoadTest() + { + double* value = stackalloc double[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int16LoadTest() + { + short* value = stackalloc short[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int32LoadTest() + { + int* value = stackalloc int[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int64LoadTest() + { + long* value = stackalloc long[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128NIntLoadTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector128NUIntLoadTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector128SByteLoadTest() + { + sbyte* value = stackalloc sbyte[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128SingleLoadTest() + { + float* value = stackalloc float[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt16LoadTest() + { + ushort* value = stackalloc ushort[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt32LoadTest() + { + uint* value = stackalloc uint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt64LoadTest() + { + ulong* value = stackalloc ulong[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.Load(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128ByteLoadAlignedTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128DoubleLoadAlignedTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int16LoadAlignedTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int32LoadAlignedTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int64LoadAlignedTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128NIntLoadAlignedTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128NUIntLoadAlignedTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128SByteLoadAlignedTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128SingleLoadAlignedTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt16LoadAlignedTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt32LoadAlignedTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt64LoadAlignedTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128 vector = Vector128.LoadAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128ByteLoadAlignedNonTemporalTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128DoubleLoadAlignedNonTemporalTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int16LoadAlignedNonTemporalTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int32LoadAlignedNonTemporalTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int64LoadAlignedNonTemporalTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128NIntLoadAlignedNonTemporalTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128NUIntLoadAlignedNonTemporalTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128SByteLoadAlignedNonTemporalTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128SingleLoadAlignedNonTemporalTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt16LoadAlignedNonTemporalTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt32LoadAlignedNonTemporalTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt64LoadAlignedNonTemporalTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128 vector = Vector128.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128ByteLoadUnsafeTest() + { + byte* value = stackalloc byte[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128DoubleLoadUnsafeTest() + { + double* value = stackalloc double[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int16LoadUnsafeTest() + { + short* value = stackalloc short[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int32LoadUnsafeTest() + { + int* value = stackalloc int[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int64LoadUnsafeTest() + { + long* value = stackalloc long[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128NIntLoadUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector128NUIntLoadUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector128SByteLoadUnsafeTest() + { + sbyte* value = stackalloc sbyte[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128SingleLoadUnsafeTest() + { + float* value = stackalloc float[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt16LoadUnsafeTest() + { + ushort* value = stackalloc ushort[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt32LoadUnsafeTest() + { + uint* value = stackalloc uint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt64LoadUnsafeTest() + { + ulong* value = stackalloc ulong[2] { + 0, + 1, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128ByteLoadUnsafeIndexTest() + { + byte* value = stackalloc byte[16 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128DoubleLoadUnsafeIndexTest() + { + double* value = stackalloc double[2 + 1] { + 0, + 1, + 2, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int16LoadUnsafeIndexTest() + { + short* value = stackalloc short[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int32LoadUnsafeIndexTest() + { + int* value = stackalloc int[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128Int64LoadUnsafeIndexTest() + { + long* value = stackalloc long[2 + 1] { + 0, + 1, + 2, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128NIntLoadUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[2 + 1] { + 0, + 1, + 2, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)(index + 1), vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)(index + 1), vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector128NUIntLoadUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[2 + 1] { + 0, + 1, + 2, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)(index + 1), vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)(index + 1), vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector128SByteLoadUnsafeIndexTest() + { + sbyte* value = stackalloc sbyte[16 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128SingleLoadUnsafeIndexTest() + { + float* value = stackalloc float[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt16LoadUnsafeIndexTest() + { + ushort* value = stackalloc ushort[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt32LoadUnsafeIndexTest() + { + uint* value = stackalloc uint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128UInt64LoadUnsafeIndexTest() + { + ulong* value = stackalloc ulong[2 + 1] { + 0, + 1, + 2, + }; + + Vector128 vector = Vector128.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public void Vector128ByteShiftLeftTest() + { + Vector128 vector = Vector128.Create((byte)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int16ShiftLeftTest() + { + Vector128 vector = Vector128.Create((short)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int32ShiftLeftTest() + { + Vector128 vector = Vector128.Create((int)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int64ShiftLeftTest() + { + Vector128 vector = Vector128.Create((long)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128NIntShiftLeftTest() + { + Vector128 vector = Vector128.Create((nint)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128NUIntShiftLeftTest() + { + Vector128 vector = Vector128.Create((nuint)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128SByteShiftLeftTest() + { + Vector128 vector = Vector128.Create((sbyte)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128UInt16ShiftLeftTest() + { + Vector128 vector = Vector128.Create((ushort)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128UInt32ShiftLeftTest() + { + Vector128 vector = Vector128.Create((uint)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128UInt64ShiftLeftTest() + { + Vector128 vector = Vector128.Create((ulong)0x01); + vector = Vector128.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int16ShiftRightArithmeticTest() + { + Vector128 vector = Vector128.Create(unchecked((short)0x8000)); + vector = Vector128.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((short)0xF800), vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int32ShiftRightArithmeticTest() + { + Vector128 vector = Vector128.Create(unchecked((int)0x80000000)); + vector = Vector128.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((int)0xF8000000), vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int64ShiftRightArithmeticTest() + { + Vector128 vector = Vector128.Create(unchecked((long)0x8000000000000000)); + vector = Vector128.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((long)0xF800000000000000), vector.GetElement(index)); + } + } + + [Fact] + public void Vector128NIntShiftRightArithmeticTest() + { + if (Environment.Is64BitProcess) + { + Vector128 vector = Vector128.Create(unchecked((nint)0x8000000000000000)); + vector = Vector128.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((nint)0xF800000000000000), vector.GetElement(index)); + } + } + else + { + Vector128 vector = Vector128.Create(unchecked((nint)0x80000000)); + vector = Vector128.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((nint)0xF8000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector128SByteShiftRightArithmeticTest() + { + Vector128 vector = Vector128.Create(unchecked((sbyte)0x80)); + vector = Vector128.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((sbyte)0xF8), vector.GetElement(index)); + } + } + + [Fact] + public void Vector128ByteShiftRightLogicalTest() + { + Vector128 vector = Vector128.Create((byte)0x80); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)0x08, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int16ShiftRightLogicalTest() + { + Vector128 vector = Vector128.Create(unchecked((short)0x8000)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)0x0800, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int32ShiftRightLogicalTest() + { + Vector128 vector = Vector128.Create(unchecked((int)0x80000000)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)0x08000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128Int64ShiftRightLogicalTest() + { + Vector128 vector = Vector128.Create(unchecked((long)0x8000000000000000)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)0x0800000000000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128NIntShiftRightLogicalTest() + { + if (Environment.Is64BitProcess) + { + Vector128 vector = Vector128.Create(unchecked((nint)0x8000000000000000)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((nint)0x0800000000000000), vector.GetElement(index)); + } + } + else + { + Vector128 vector = Vector128.Create(unchecked((nint)0x80000000)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((nint)0x08000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector128NUIntShiftRightLogicalTest() + { + if (Environment.Is64BitProcess) + { + Vector128 vector = Vector128.Create(unchecked((nuint)0x8000000000000000)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((nuint)0x0800000000000000), vector.GetElement(index)); + } + } + else + { + Vector128 vector = Vector128.Create(unchecked((nuint)0x80000000)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal(unchecked((nuint)0x08000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector128SByteShiftRightLogicalTest() + { + Vector128 vector = Vector128.Create(unchecked((sbyte)0x80)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)0x08, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128UInt16ShiftRightLogicalTest() + { + Vector128 vector = Vector128.Create(unchecked((ushort)0x8000)); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)0x0800, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128UInt32ShiftRightLogicalTest() + { + Vector128 vector = Vector128.Create(0x80000000); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)0x08000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector128UInt64ShiftRightLogicalTest() + { + Vector128 vector = Vector128.Create(0x8000000000000000); + vector = Vector128.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)0x0800000000000000, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector128ByteStoreTest() + { + byte* value = stackalloc byte[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector128.Create((byte)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128DoubleStoreTest() + { + double* value = stackalloc double[2] { + 0, + 1, + }; + + Vector128.Create((double)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128Int16StoreTest() + { + short* value = stackalloc short[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector128.Create((short)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128Int32StoreTest() + { + int* value = stackalloc int[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((int)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128Int64StoreTest() + { + long* value = stackalloc long[2] { + 0, + 1, + }; + + Vector128.Create((long)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128NIntStoreTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[2] { + 0, + 1, + }; + + Vector128.Create((nint)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + else + { + nint* value = stackalloc nint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((nint)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector128NUIntStoreTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[2] { + 0, + 1, + }; + + Vector128.Create((nuint)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + else + { + nuint* value = stackalloc nuint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((nuint)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector128SByteStoreTest() + { + sbyte* value = stackalloc sbyte[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector128.Create((sbyte)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128SingleStoreTest() + { + float* value = stackalloc float[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((float)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128UInt16StoreTest() + { + ushort* value = stackalloc ushort[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector128.Create((ushort)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128UInt32StoreTest() + { + uint* value = stackalloc uint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((uint)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128UInt64StoreTest() + { + ulong* value = stackalloc ulong[2] { + 0, + 1, + }; + + Vector128.Create((ulong)0x1).Store(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128ByteStoreAlignedTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector128.Create((byte)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128DoubleStoreAlignedTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128.Create((double)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int16StoreAlignedTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector128.Create((short)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int32StoreAlignedTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128.Create((int)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int64StoreAlignedTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128.Create((long)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128NIntStoreAlignedTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + + Vector128.Create((nint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128NUIntStoreAlignedTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + + Vector128.Create((nuint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128SByteStoreAlignedTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector128.Create((sbyte)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128SingleStoreAlignedTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128.Create((float)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt16StoreAlignedTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector128.Create((ushort)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt32StoreAlignedTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128.Create((uint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt64StoreAlignedTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128.Create((ulong)0x1).StoreAligned(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128ByteStoreAlignedNonTemporalTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector128.Create((byte)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128DoubleStoreAlignedNonTemporalTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128.Create((double)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int16StoreAlignedNonTemporalTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector128.Create((short)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int32StoreAlignedNonTemporalTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128.Create((int)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128Int64StoreAlignedNonTemporalTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128.Create((long)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128NIntStoreAlignedNonTemporalTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + + Vector128.Create((nint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128NUIntStoreAlignedNonTemporalTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + + Vector128.Create((nuint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128SByteStoreAlignedNonTemporalTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector128.Create((sbyte)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128SingleStoreAlignedNonTemporalTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128.Create((float)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt16StoreAlignedNonTemporalTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector128.Create((ushort)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt32StoreAlignedNonTemporalTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector128.Create((uint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128UInt64StoreAlignedNonTemporalTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 16, alignment: 16); + + value[0] = 0; + value[1] = 1; + + Vector128.Create((ulong)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector128ByteStoreUnsafeTest() + { + byte* value = stackalloc byte[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector128.Create((byte)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128DoubleStoreUnsafeTest() + { + double* value = stackalloc double[2] { + 0, + 1, + }; + + Vector128.Create((double)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128Int16StoreUnsafeTest() + { + short* value = stackalloc short[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector128.Create((short)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128Int32StoreUnsafeTest() + { + int* value = stackalloc int[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((int)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128Int64StoreUnsafeTest() + { + long* value = stackalloc long[2] { + 0, + 1, + }; + + Vector128.Create((long)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128NIntStoreUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[2] { + 0, + 1, + }; + + Vector128.Create((nint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + else + { + nint* value = stackalloc nint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((nint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector128NUIntStoreUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[2] { + 0, + 1, + }; + + Vector128.Create((nuint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + else + { + nuint* value = stackalloc nuint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((nuint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector128SByteStoreUnsafeTest() + { + sbyte* value = stackalloc sbyte[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector128.Create((sbyte)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128SingleStoreUnsafeTest() + { + float* value = stackalloc float[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((float)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128UInt16StoreUnsafeTest() + { + ushort* value = stackalloc ushort[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector128.Create((ushort)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128UInt32StoreUnsafeTest() + { + uint* value = stackalloc uint[4] { + 0, + 1, + 2, + 3, + }; + + Vector128.Create((uint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128UInt64StoreUnsafeTest() + { + ulong* value = stackalloc ulong[2] { + 0, + 1, + }; + + Vector128.Create((ulong)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector128ByteStoreUnsafeIndexTest() + { + byte* value = stackalloc byte[16 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + }; + + Vector128.Create((byte)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((byte)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128DoubleStoreUnsafeIndexTest() + { + double* value = stackalloc double[2 + 1] { + 0, + 1, + 2, + }; + + Vector128.Create((double)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((double)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128Int16StoreUnsafeIndexTest() + { + short* value = stackalloc short[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector128.Create((short)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((short)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128Int32StoreUnsafeIndexTest() + { + int* value = stackalloc int[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128.Create((int)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((int)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128Int64StoreUnsafeIndexTest() + { + long* value = stackalloc long[2 + 1] { + 0, + 1, + 2, + }; + + Vector128.Create((long)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((long)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128NIntStoreUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[2 + 1] { + 0, + 1, + 2, + }; + + Vector128.Create((nint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x1, value[index + 1]); + } + } + else + { + nint* value = stackalloc nint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128.Create((nint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nint)0x1, value[index + 1]); + } + } + } + + [Fact] + public unsafe void Vector128NUIntStoreUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[2 + 1] { + 0, + 1, + 2, + }; + + Vector128.Create((nuint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x1, value[index + 1]); + } + } + else + { + nuint* value = stackalloc nuint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128.Create((nuint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((nuint)0x1, value[index + 1]); + } + } + } + + [Fact] + public unsafe void Vector128SByteStoreUnsafeIndexTest() + { + sbyte* value = stackalloc sbyte[16 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + }; + + Vector128.Create((sbyte)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128SingleStoreUnsafeIndexTest() + { + float* value = stackalloc float[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128.Create((float)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((float)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128UInt16StoreUnsafeIndexTest() + { + ushort* value = stackalloc ushort[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector128.Create((ushort)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ushort)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128UInt32StoreUnsafeIndexTest() + { + uint* value = stackalloc uint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector128.Create((uint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((uint)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector128UInt64StoreUnsafeIndexTest() + { + ulong* value = stackalloc ulong[2 + 1] { + 0, + 1, + 2, + }; + + Vector128.Create((ulong)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector128.Count; index++) + { + Assert.Equal((ulong)0x1, value[index + 1]); + } + } + + [Fact] + public void Vector128ByteSumTest() + { + Vector128 vector = Vector128.Create((byte)0x01); + Assert.Equal((byte)16, Vector128.Sum(vector)); + } + + [Fact] + public void Vector128DoubleSumTest() + { + Vector128 vector = Vector128.Create((double)0x01); + Assert.Equal(2.0, Vector128.Sum(vector)); + } + + [Fact] + public void Vector128Int16SumTest() + { + Vector128 vector = Vector128.Create((short)0x01); + Assert.Equal((short)8, Vector128.Sum(vector)); + } + + [Fact] + public void Vector128Int32SumTest() + { + Vector128 vector = Vector128.Create((int)0x01); + Assert.Equal((int)4, Vector128.Sum(vector)); + } + + [Fact] + public void Vector128Int64SumTest() + { + Vector128 vector = Vector128.Create((long)0x01); + Assert.Equal((long)2, Vector128.Sum(vector)); + } + + [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/63746", TestPlatforms.tvOS)] + public void Vector128NIntSumTest() + { + Vector128 vector = Vector128.Create((nint)0x01); + + if (Environment.Is64BitProcess) + { + Assert.Equal((nint)2, Vector128.Sum(vector)); + } + else + { + Assert.Equal((nint)4, Vector128.Sum(vector)); + } + } + + [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/63746", TestPlatforms.tvOS)] + public void Vector128NUIntSumTest() + { + Vector128 vector = Vector128.Create((nuint)0x01); + + if (Environment.Is64BitProcess) + { + Assert.Equal((nuint)2, Vector128.Sum(vector)); + } + else + { + Assert.Equal((nuint)4, Vector128.Sum(vector)); + } + } + + [Fact] + public void Vector128SByteSumTest() + { + Vector128 vector = Vector128.Create((sbyte)0x01); + Assert.Equal((sbyte)16, Vector128.Sum(vector)); + } + + [Fact] + public void Vector128SingleSumTest() + { + Vector128 vector = Vector128.Create((float)0x01); + Assert.Equal(4.0f, Vector128.Sum(vector)); + } + + [Fact] + public void Vector128UInt16SumTest() + { + Vector128 vector = Vector128.Create((ushort)0x01); + Assert.Equal((ushort)8, Vector128.Sum(vector)); + } + + [Fact] + public void Vector128UInt32SumTest() + { + Vector128 vector = Vector128.Create((uint)0x01); + Assert.Equal((uint)4, Vector128.Sum(vector)); + } + + [Fact] + public void Vector128UInt64SumTest() + { + Vector128 vector = Vector128.Create((ulong)0x01); + Assert.Equal((ulong)2, Vector128.Sum(vector)); + } + [Theory] [InlineData(0, 0, 0, 0)] [InlineData(1, 1, 1, 1)] diff --git a/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector256Tests.cs b/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector256Tests.cs index e14349c5cdd43..13727baa13dc1 100644 --- a/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector256Tests.cs +++ b/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector256Tests.cs @@ -1,13 +1,4678 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; +using System.Runtime.InteropServices; using Xunit; namespace System.Runtime.Intrinsics.Tests.Vectors { public sealed class Vector256Tests { + [Fact] + public unsafe void Vector256ByteExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80 + ); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010_10101010_10101010_10101010u, result); + } + + [Fact] + public unsafe void Vector256DoubleExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + +1.0, + -0.0, + +1.0, + -0.0 + ); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + + [Fact] + public unsafe void Vector256Int16ExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000 + ).AsInt16(); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010_10101010u, result); + } + + [Fact] + public unsafe void Vector256Int32ExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U + ).AsInt32(); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + + [Fact] + public unsafe void Vector256Int64ExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + 0x0000000000000001UL, + 0x8000000000000000UL, + 0x0000000000000001UL, + 0x8000000000000000UL + ).AsInt64(); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + + [Fact] + public unsafe void Vector256NIntExtractMostSignificantBitsTest() + { + if (Environment.Is64BitProcess) + { + Vector256 vector = Vector256.Create( + 0x0000000000000001UL, + 0x8000000000000000UL, + 0x0000000000000001UL, + 0x8000000000000000UL + ).AsNInt(); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + else + { + Vector256 vector = Vector256.Create( + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U + ).AsNInt(); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + } + + [Fact] + public unsafe void Vector256NUIntExtractMostSignificantBitsTest() + { + if (Environment.Is64BitProcess) + { + Vector256 vector = Vector256.Create( + 0x0000000000000001UL, + 0x8000000000000000UL, + 0x0000000000000001UL, + 0x8000000000000000UL + ).AsNUInt(); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + else + { + Vector256 vector = Vector256.Create( + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U + ).AsNUInt(); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + } + + [Fact] + public unsafe void Vector256SByteExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80 + ).AsSByte(); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010_10101010_10101010_10101010u, result); + } + + [Fact] + public unsafe void Vector256SingleExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + +1.0f, + -0.0f, + +1.0f, + -0.0f, + +1.0f, + -0.0f, + +1.0f, + -0.0f + ); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + + [Fact] + public unsafe void Vector256UInt16ExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000, + 0x0001, + 0x8000 + ); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010_10101010u, result); + } + + [Fact] + public unsafe void Vector256UInt32ExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U, + 0x00000001U, + 0x80000000U + ); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + + [Fact] + public unsafe void Vector256UInt64ExtractMostSignificantBitsTest() + { + Vector256 vector = Vector256.Create( + 0x0000000000000001UL, + 0x8000000000000000UL, + 0x0000000000000001UL, + 0x8000000000000000UL + ); + + uint result = Vector256.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + + [Fact] + public unsafe void Vector256ByteLoadTest() + { + byte* value = stackalloc byte[32] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256DoubleLoadTest() + { + double* value = stackalloc double[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int16LoadTest() + { + short* value = stackalloc short[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int32LoadTest() + { + int* value = stackalloc int[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int64LoadTest() + { + long* value = stackalloc long[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256NIntLoadTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector256NUIntLoadTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector256SByteLoadTest() + { + sbyte* value = stackalloc sbyte[32] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256SingleLoadTest() + { + float* value = stackalloc float[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt16LoadTest() + { + ushort* value = stackalloc ushort[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt32LoadTest() + { + uint* value = stackalloc uint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt64LoadTest() + { + ulong* value = stackalloc ulong[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.Load(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256ByteLoadAlignedTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + value[16] = 16; + value[17] = 17; + value[18] = 18; + value[19] = 19; + value[20] = 20; + value[21] = 21; + value[22] = 22; + value[23] = 23; + value[24] = 24; + value[25] = 25; + value[26] = 26; + value[27] = 27; + value[28] = 28; + value[29] = 29; + value[30] = 30; + value[31] = 31; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256DoubleLoadAlignedTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int16LoadAlignedTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int32LoadAlignedTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int64LoadAlignedTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256NIntLoadAlignedTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + } + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256NUIntLoadAlignedTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + } + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256SByteLoadAlignedTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + value[16] = 16; + value[17] = 17; + value[18] = 18; + value[19] = 19; + value[20] = 20; + value[21] = 21; + value[22] = 22; + value[23] = 23; + value[24] = 24; + value[25] = 25; + value[26] = 26; + value[27] = 27; + value[28] = 28; + value[29] = 29; + value[30] = 30; + value[31] = 31; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256SingleLoadAlignedTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt16LoadAlignedTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt32LoadAlignedTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt64LoadAlignedTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256 vector = Vector256.LoadAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256ByteLoadAlignedNonTemporalTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + value[16] = 16; + value[17] = 17; + value[18] = 18; + value[19] = 19; + value[20] = 20; + value[21] = 21; + value[22] = 22; + value[23] = 23; + value[24] = 24; + value[25] = 25; + value[26] = 26; + value[27] = 27; + value[28] = 28; + value[29] = 29; + value[30] = 30; + value[31] = 31; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256DoubleLoadAlignedNonTemporalTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int16LoadAlignedNonTemporalTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int32LoadAlignedNonTemporalTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int64LoadAlignedNonTemporalTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256NIntLoadAlignedNonTemporalTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + } + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256NUIntLoadAlignedNonTemporalTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + } + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256SByteLoadAlignedNonTemporalTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + value[16] = 16; + value[17] = 17; + value[18] = 18; + value[19] = 19; + value[20] = 20; + value[21] = 21; + value[22] = 22; + value[23] = 23; + value[24] = 24; + value[25] = 25; + value[26] = 26; + value[27] = 27; + value[28] = 28; + value[29] = 29; + value[30] = 30; + value[31] = 31; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256SingleLoadAlignedNonTemporalTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt16LoadAlignedNonTemporalTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt32LoadAlignedNonTemporalTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt64LoadAlignedNonTemporalTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256 vector = Vector256.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256ByteLoadUnsafeTest() + { + byte* value = stackalloc byte[32] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256DoubleLoadUnsafeTest() + { + double* value = stackalloc double[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int16LoadUnsafeTest() + { + short* value = stackalloc short[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int32LoadUnsafeTest() + { + int* value = stackalloc int[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int64LoadUnsafeTest() + { + long* value = stackalloc long[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256NIntLoadUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector256NUIntLoadUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector256SByteLoadUnsafeTest() + { + sbyte* value = stackalloc sbyte[32] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256SingleLoadUnsafeTest() + { + float* value = stackalloc float[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt16LoadUnsafeTest() + { + ushort* value = stackalloc ushort[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt32LoadUnsafeTest() + { + uint* value = stackalloc uint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt64LoadUnsafeTest() + { + ulong* value = stackalloc ulong[4] { + 0, + 1, + 2, + 3, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256ByteLoadUnsafeIndexTest() + { + byte* value = stackalloc byte[32 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256DoubleLoadUnsafeIndexTest() + { + double* value = stackalloc double[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int16LoadUnsafeIndexTest() + { + short* value = stackalloc short[16 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int32LoadUnsafeIndexTest() + { + int* value = stackalloc int[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256Int64LoadUnsafeIndexTest() + { + long* value = stackalloc long[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256NIntLoadUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)(index + 1), vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)(index + 1), vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector256NUIntLoadUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)(index + 1), vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)(index + 1), vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector256SByteLoadUnsafeIndexTest() + { + sbyte* value = stackalloc sbyte[32 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256SingleLoadUnsafeIndexTest() + { + float* value = stackalloc float[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt16LoadUnsafeIndexTest() + { + ushort* value = stackalloc ushort[16 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt32LoadUnsafeIndexTest() + { + uint* value = stackalloc uint[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256UInt64LoadUnsafeIndexTest() + { + ulong* value = stackalloc ulong[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256 vector = Vector256.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public void Vector256ByteShiftLeftTest() + { + Vector256 vector = Vector256.Create((byte)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int16ShiftLeftTest() + { + Vector256 vector = Vector256.Create((short)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int32ShiftLeftTest() + { + Vector256 vector = Vector256.Create((int)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int64ShiftLeftTest() + { + Vector256 vector = Vector256.Create((long)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256NIntShiftLeftTest() + { + Vector256 vector = Vector256.Create((nint)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256NUIntShiftLeftTest() + { + Vector256 vector = Vector256.Create((nuint)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256SByteShiftLeftTest() + { + Vector256 vector = Vector256.Create((sbyte)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256UInt16ShiftLeftTest() + { + Vector256 vector = Vector256.Create((ushort)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256UInt32ShiftLeftTest() + { + Vector256 vector = Vector256.Create((uint)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256UInt64ShiftLeftTest() + { + Vector256 vector = Vector256.Create((ulong)0x01); + vector = Vector256.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int16ShiftRightArithmeticTest() + { + Vector256 vector = Vector256.Create(unchecked((short)0x8000)); + vector = Vector256.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((short)0xF800), vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int32ShiftRightArithmeticTest() + { + Vector256 vector = Vector256.Create(unchecked((int)0x80000000)); + vector = Vector256.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((int)0xF8000000), vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int64ShiftRightArithmeticTest() + { + Vector256 vector = Vector256.Create(unchecked((long)0x8000000000000000)); + vector = Vector256.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((long)0xF800000000000000), vector.GetElement(index)); + } + } + + [Fact] + public void Vector256NIntShiftRightArithmeticTest() + { + if (Environment.Is64BitProcess) + { + Vector256 vector = Vector256.Create(unchecked((nint)0x8000000000000000)); + vector = Vector256.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((nint)0xF800000000000000), vector.GetElement(index)); + } + } + else + { + Vector256 vector = Vector256.Create(unchecked((nint)0x80000000)); + vector = Vector256.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((nint)0xF8000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector256SByteShiftRightArithmeticTest() + { + Vector256 vector = Vector256.Create(unchecked((sbyte)0x80)); + vector = Vector256.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((sbyte)0xF8), vector.GetElement(index)); + } + } + + [Fact] + public void Vector256ByteShiftRightLogicalTest() + { + Vector256 vector = Vector256.Create((byte)0x80); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)0x08, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int16ShiftRightLogicalTest() + { + Vector256 vector = Vector256.Create(unchecked((short)0x8000)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)0x0800, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int32ShiftRightLogicalTest() + { + Vector256 vector = Vector256.Create(unchecked((int)0x80000000)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)0x08000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256Int64ShiftRightLogicalTest() + { + Vector256 vector = Vector256.Create(unchecked((long)0x8000000000000000)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)0x0800000000000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256NIntShiftRightLogicalTest() + { + if (Environment.Is64BitProcess) + { + Vector256 vector = Vector256.Create(unchecked((nint)0x8000000000000000)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((nint)0x0800000000000000), vector.GetElement(index)); + } + } + else + { + Vector256 vector = Vector256.Create(unchecked((nint)0x80000000)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((nint)0x08000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector256NUIntShiftRightLogicalTest() + { + if (Environment.Is64BitProcess) + { + Vector256 vector = Vector256.Create(unchecked((nuint)0x8000000000000000)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((nuint)0x0800000000000000), vector.GetElement(index)); + } + } + else + { + Vector256 vector = Vector256.Create(unchecked((nuint)0x80000000)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal(unchecked((nuint)0x08000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector256SByteShiftRightLogicalTest() + { + Vector256 vector = Vector256.Create(unchecked((sbyte)0x80)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)0x08, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256UInt16ShiftRightLogicalTest() + { + Vector256 vector = Vector256.Create(unchecked((ushort)0x8000)); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)0x0800, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256UInt32ShiftRightLogicalTest() + { + Vector256 vector = Vector256.Create(0x80000000); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)0x08000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector256UInt64ShiftRightLogicalTest() + { + Vector256 vector = Vector256.Create(0x8000000000000000); + vector = Vector256.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)0x0800000000000000, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector256ByteStoreTest() + { + byte* value = stackalloc byte[32] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + }; + + Vector256.Create((byte)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256DoubleStoreTest() + { + double* value = stackalloc double[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((double)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256Int16StoreTest() + { + short* value = stackalloc short[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector256.Create((short)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256Int32StoreTest() + { + int* value = stackalloc int[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((int)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256Int64StoreTest() + { + long* value = stackalloc long[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((long)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256NIntStoreTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((nint)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + else + { + nint* value = stackalloc nint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((nint)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector256NUIntStoreTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((nuint)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + else + { + nuint* value = stackalloc nuint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((nuint)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector256SByteStoreTest() + { + sbyte* value = stackalloc sbyte[32] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + }; + + Vector256.Create((sbyte)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256SingleStoreTest() + { + float* value = stackalloc float[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((float)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256UInt16StoreTest() + { + ushort* value = stackalloc ushort[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector256.Create((ushort)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256UInt32StoreTest() + { + uint* value = stackalloc uint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((uint)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256UInt64StoreTest() + { + ulong* value = stackalloc ulong[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((ulong)0x1).Store(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256ByteStoreAlignedTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + value[16] = 16; + value[17] = 17; + value[18] = 18; + value[19] = 19; + value[20] = 20; + value[21] = 21; + value[22] = 22; + value[23] = 23; + value[24] = 24; + value[25] = 25; + value[26] = 26; + value[27] = 27; + value[28] = 28; + value[29] = 29; + value[30] = 30; + value[31] = 31; + + Vector256.Create((byte)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256DoubleStoreAlignedTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256.Create((double)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int16StoreAlignedTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector256.Create((short)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int32StoreAlignedTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256.Create((int)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int64StoreAlignedTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256.Create((long)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256NIntStoreAlignedTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + } + + Vector256.Create((nint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256NUIntStoreAlignedTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + } + + Vector256.Create((nuint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256SByteStoreAlignedTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + value[16] = 16; + value[17] = 17; + value[18] = 18; + value[19] = 19; + value[20] = 20; + value[21] = 21; + value[22] = 22; + value[23] = 23; + value[24] = 24; + value[25] = 25; + value[26] = 26; + value[27] = 27; + value[28] = 28; + value[29] = 29; + value[30] = 30; + value[31] = 31; + + Vector256.Create((sbyte)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256SingleStoreAlignedTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256.Create((float)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt16StoreAlignedTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector256.Create((ushort)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt32StoreAlignedTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256.Create((uint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt64StoreAlignedTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256.Create((ulong)0x1).StoreAligned(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256ByteStoreAlignedNonTemporalTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + value[16] = 16; + value[17] = 17; + value[18] = 18; + value[19] = 19; + value[20] = 20; + value[21] = 21; + value[22] = 22; + value[23] = 23; + value[24] = 24; + value[25] = 25; + value[26] = 26; + value[27] = 27; + value[28] = 28; + value[29] = 29; + value[30] = 30; + value[31] = 31; + + Vector256.Create((byte)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256DoubleStoreAlignedNonTemporalTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256.Create((double)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int16StoreAlignedNonTemporalTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector256.Create((short)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int32StoreAlignedNonTemporalTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256.Create((int)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256Int64StoreAlignedNonTemporalTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256.Create((long)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256NIntStoreAlignedNonTemporalTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + } + + Vector256.Create((nint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256NUIntStoreAlignedNonTemporalTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + } + else + { + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + } + + Vector256.Create((nuint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256SByteStoreAlignedNonTemporalTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + value[16] = 16; + value[17] = 17; + value[18] = 18; + value[19] = 19; + value[20] = 20; + value[21] = 21; + value[22] = 22; + value[23] = 23; + value[24] = 24; + value[25] = 25; + value[26] = 26; + value[27] = 27; + value[28] = 28; + value[29] = 29; + value[30] = 30; + value[31] = 31; + + Vector256.Create((sbyte)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256SingleStoreAlignedNonTemporalTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256.Create((float)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt16StoreAlignedNonTemporalTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + value[8] = 8; + value[9] = 9; + value[10] = 10; + value[11] = 11; + value[12] = 12; + value[13] = 13; + value[14] = 14; + value[15] = 15; + + Vector256.Create((ushort)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt32StoreAlignedNonTemporalTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector256.Create((uint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256UInt64StoreAlignedNonTemporalTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 32, alignment: 32); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector256.Create((ulong)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector256ByteStoreUnsafeTest() + { + byte* value = stackalloc byte[32] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + }; + + Vector256.Create((byte)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256DoubleStoreUnsafeTest() + { + double* value = stackalloc double[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((double)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256Int16StoreUnsafeTest() + { + short* value = stackalloc short[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector256.Create((short)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256Int32StoreUnsafeTest() + { + int* value = stackalloc int[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((int)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256Int64StoreUnsafeTest() + { + long* value = stackalloc long[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((long)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256NIntStoreUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((nint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + else + { + nint* value = stackalloc nint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((nint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector256NUIntStoreUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((nuint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + else + { + nuint* value = stackalloc nuint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((nuint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector256SByteStoreUnsafeTest() + { + sbyte* value = stackalloc sbyte[32] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + }; + + Vector256.Create((sbyte)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256SingleStoreUnsafeTest() + { + float* value = stackalloc float[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((float)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256UInt16StoreUnsafeTest() + { + ushort* value = stackalloc ushort[16] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + }; + + Vector256.Create((ushort)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256UInt32StoreUnsafeTest() + { + uint* value = stackalloc uint[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector256.Create((uint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256UInt64StoreUnsafeTest() + { + ulong* value = stackalloc ulong[4] { + 0, + 1, + 2, + 3, + }; + + Vector256.Create((ulong)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector256ByteStoreUnsafeIndexTest() + { + byte* value = stackalloc byte[32 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + }; + + Vector256.Create((byte)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((byte)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256DoubleStoreUnsafeIndexTest() + { + double* value = stackalloc double[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256.Create((double)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((double)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256Int16StoreUnsafeIndexTest() + { + short* value = stackalloc short[16 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + }; + + Vector256.Create((short)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((short)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256Int32StoreUnsafeIndexTest() + { + int* value = stackalloc int[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256.Create((int)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((int)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256Int64StoreUnsafeIndexTest() + { + long* value = stackalloc long[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256.Create((long)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((long)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256NIntStoreUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256.Create((nint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x1, value[index + 1]); + } + } + else + { + nint* value = stackalloc nint[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256.Create((nint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nint)0x1, value[index + 1]); + } + } + } + + [Fact] + public unsafe void Vector256NUIntStoreUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256.Create((nuint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x1, value[index + 1]); + } + } + else + { + nuint* value = stackalloc nuint[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256.Create((nuint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((nuint)0x1, value[index + 1]); + } + } + } + + [Fact] + public unsafe void Vector256SByteStoreUnsafeIndexTest() + { + sbyte* value = stackalloc sbyte[32 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 31, + 32, + }; + + Vector256.Create((sbyte)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256SingleStoreUnsafeIndexTest() + { + float* value = stackalloc float[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256.Create((float)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((float)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256UInt16StoreUnsafeIndexTest() + { + ushort* value = stackalloc ushort[16 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + }; + + Vector256.Create((ushort)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ushort)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256UInt32StoreUnsafeIndexTest() + { + uint* value = stackalloc uint[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector256.Create((uint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((uint)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector256UInt64StoreUnsafeIndexTest() + { + ulong* value = stackalloc ulong[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector256.Create((ulong)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector256.Count; index++) + { + Assert.Equal((ulong)0x1, value[index + 1]); + } + } + + [Fact] + public void Vector256ByteSumTest() + { + Vector256 vector = Vector256.Create((byte)0x01); + Assert.Equal((byte)32, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256DoubleSumTest() + { + Vector256 vector = Vector256.Create((double)0x01); + Assert.Equal(4.0, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256Int16SumTest() + { + Vector256 vector = Vector256.Create((short)0x01); + Assert.Equal((short)16, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256Int32SumTest() + { + Vector256 vector = Vector256.Create((int)0x01); + Assert.Equal((int)8, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256Int64SumTest() + { + Vector256 vector = Vector256.Create((long)0x01); + Assert.Equal((long)4, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256NIntSumTest() + { + Vector256 vector = Vector256.Create((nint)0x01); + + if (Environment.Is64BitProcess) + { + Assert.Equal((nint)4, Vector256.Sum(vector)); + } + else + { + Assert.Equal((nint)8, Vector256.Sum(vector)); + } + } + + [Fact] + public void Vector256NUIntSumTest() + { + Vector256 vector = Vector256.Create((nuint)0x01); + + if (Environment.Is64BitProcess) + { + Assert.Equal((nuint)4, Vector256.Sum(vector)); + } + else + { + Assert.Equal((nuint)8, Vector256.Sum(vector)); + } + } + + [Fact] + public void Vector256SByteSumTest() + { + Vector256 vector = Vector256.Create((sbyte)0x01); + Assert.Equal((sbyte)32, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256SingleSumTest() + { + Vector256 vector = Vector256.Create((float)0x01); + Assert.Equal(8.0f, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256UInt16SumTest() + { + Vector256 vector = Vector256.Create((ushort)0x01); + Assert.Equal((ushort)16, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256UInt32SumTest() + { + Vector256 vector = Vector256.Create((uint)0x01); + Assert.Equal((uint)8, Vector256.Sum(vector)); + } + + [Fact] + public void Vector256UInt64SumTest() + { + Vector256 vector = Vector256.Create((ulong)0x01); + Assert.Equal((ulong)4, Vector256.Sum(vector)); + } + [Theory] [InlineData(0, 0, 0, 0, 0, 0, 0, 0)] [InlineData(1, 1, 1, 1, 1, 1, 1, 1)] diff --git a/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector64Tests.cs b/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector64Tests.cs index 49cd5b6887b61..30297c8b23fe8 100644 --- a/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector64Tests.cs +++ b/src/libraries/System.Runtime.Intrinsics/tests/Vectors/Vector64Tests.cs @@ -1,13 +1,3426 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Linq; +using System.Runtime.InteropServices; using Xunit; namespace System.Runtime.Intrinsics.Tests.Vectors { public sealed class Vector64Tests { + [Fact] + public unsafe void Vector64ByteExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80 + ); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + + [Fact] + public unsafe void Vector64DoubleExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + +1.0 + ); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b0u, result); + + vector = Vector64.Create( + -0.0 + ); + + result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b1u, result); + } + + [Fact] + public unsafe void Vector64Int16ExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + 0x0001, + 0x8000, + 0x0001, + 0x8000 + ).AsInt16(); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + + [Fact] + public unsafe void Vector64Int32ExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + 0x00000001U, + 0x80000000U + ).AsInt32(); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + + [Fact] + public unsafe void Vector64Int64ExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + 0x0000000000000001UL + ).AsInt64(); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b0u, result); + + vector = Vector64.Create( + 0x8000000000000000UL + ).AsInt64(); + + result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b1u, result); + } + + [Fact] + public unsafe void Vector64NIntExtractMostSignificantBitsTest() + { + if (Environment.Is64BitProcess) + { + Vector64 vector = Vector64.Create( + 0x0000000000000001UL + ).AsNInt(); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b0u, result); + + vector = Vector64.Create( + 0x8000000000000000UL + ).AsNInt(); + + result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b1u, result); + } + else + { + Vector64 vector = Vector64.Create( + 0x00000001U, + 0x80000000U + ).AsNInt(); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + } + + [Fact] + public unsafe void Vector64NUIntExtractMostSignificantBitsTest() + { + if (Environment.Is64BitProcess) + { + Vector64 vector = Vector64.Create( + 0x0000000000000001UL + ).AsNUInt(); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b0u, result); + + vector = Vector64.Create( + 0x8000000000000000UL + ).AsNUInt(); + + result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b1u, result); + } + else + { + Vector64 vector = Vector64.Create( + 0x00000001U, + 0x80000000U + ).AsNUInt(); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + } + + [Fact] + public unsafe void Vector64SByteExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80, + 0x01, + 0x80 + ).AsSByte(); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b10101010u, result); + } + + [Fact] + public unsafe void Vector64SingleExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + +1.0f, + -0.0f + ); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + + [Fact] + public unsafe void Vector64UInt16ExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + 0x0001, + 0x8000, + 0x0001, + 0x8000 + ); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b1010u, result); + } + + [Fact] + public unsafe void Vector64UInt32ExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + 0x00000001U, + 0x80000000U + ); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b10u, result); + } + + [Fact] + public unsafe void Vector64UInt64ExtractMostSignificantBitsTest() + { + Vector64 vector = Vector64.Create( + 0x0000000000000001UL + ); + + uint result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b0u, result); + + vector = Vector64.Create( + 0x8000000000000000UL + ); + + result = Vector64.ExtractMostSignificantBits(vector); + Assert.Equal(0b1u, result); + } + + [Fact] + public unsafe void Vector64ByteLoadTest() + { + byte* value = stackalloc byte[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64DoubleLoadTest() + { + double* value = stackalloc double[1] { + 0, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int16LoadTest() + { + short* value = stackalloc short[4] { + 0, + 1, + 2, + 3, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int32LoadTest() + { + int* value = stackalloc int[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int64LoadTest() + { + long* value = stackalloc long[1] { + 0, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64NIntLoadTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[1] { + 0, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector64NUIntLoadTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[1] { + 0, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector64SByteLoadTest() + { + sbyte* value = stackalloc sbyte[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64SingleLoadTest() + { + float* value = stackalloc float[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt16LoadTest() + { + ushort* value = stackalloc ushort[4] { + 0, + 1, + 2, + 3, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt32LoadTest() + { + uint* value = stackalloc uint[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt64LoadTest() + { + ulong* value = stackalloc ulong[1] { + 0, + }; + + Vector64 vector = Vector64.Load(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64ByteLoadAlignedTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64DoubleLoadAlignedTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int16LoadAlignedTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int32LoadAlignedTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int64LoadAlignedTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64NIntLoadAlignedTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + } + else + { + value[0] = 0; + value[1] = 1; + } + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64NUIntLoadAlignedTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + } + else + { + value[0] = 0; + value[1] = 1; + } + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64SByteLoadAlignedTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64SingleLoadAlignedTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt16LoadAlignedTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt32LoadAlignedTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt64LoadAlignedTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64 vector = Vector64.LoadAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64ByteLoadAlignedNonTemporalTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64DoubleLoadAlignedNonTemporalTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int16LoadAlignedNonTemporalTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int32LoadAlignedNonTemporalTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int64LoadAlignedNonTemporalTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64NIntLoadAlignedNonTemporalTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + } + else + { + value[0] = 0; + value[1] = 1; + } + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64NUIntLoadAlignedNonTemporalTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + } + else + { + value[0] = 0; + value[1] = 1; + } + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64SByteLoadAlignedNonTemporalTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64SingleLoadAlignedNonTemporalTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt16LoadAlignedNonTemporalTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt32LoadAlignedNonTemporalTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt64LoadAlignedNonTemporalTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64 vector = Vector64.LoadAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64ByteLoadUnsafeTest() + { + byte* value = stackalloc byte[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64DoubleLoadUnsafeTest() + { + double* value = stackalloc double[1] { + 0, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int16LoadUnsafeTest() + { + short* value = stackalloc short[4] { + 0, + 1, + 2, + 3, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int32LoadUnsafeTest() + { + int* value = stackalloc int[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int64LoadUnsafeTest() + { + long* value = stackalloc long[1] { + 0, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64NIntLoadUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[1] { + 0, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector64NUIntLoadUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[1] { + 0, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)index, vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector64SByteLoadUnsafeTest() + { + sbyte* value = stackalloc sbyte[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64SingleLoadUnsafeTest() + { + float* value = stackalloc float[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt16LoadUnsafeTest() + { + ushort* value = stackalloc ushort[4] { + 0, + 1, + 2, + 3, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt32LoadUnsafeTest() + { + uint* value = stackalloc uint[2] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt64LoadUnsafeTest() + { + ulong* value = stackalloc ulong[1] { + 0, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)index, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64ByteLoadUnsafeIndexTest() + { + byte* value = stackalloc byte[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64DoubleLoadUnsafeIndexTest() + { + double* value = stackalloc double[1 + 1] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int16LoadUnsafeIndexTest() + { + short* value = stackalloc short[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int32LoadUnsafeIndexTest() + { + int* value = stackalloc int[2 + 1] { + 0, + 1, + 2, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64Int64LoadUnsafeIndexTest() + { + long* value = stackalloc long[1 + 1] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64NIntLoadUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[1 + 1] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)(index + 1), vector.GetElement(index)); + } + } + else + { + nint* value = stackalloc nint[2 + 1] { + 0, + 1, + 2, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)(index + 1), vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector64NUIntLoadUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[1 + 1] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)(index + 1), vector.GetElement(index)); + } + } + else + { + nuint* value = stackalloc nuint[2 + 1] { + 0, + 1, + 2, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)(index + 1), vector.GetElement(index)); + } + } + } + + [Fact] + public unsafe void Vector64SByteLoadUnsafeIndexTest() + { + sbyte* value = stackalloc sbyte[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64SingleLoadUnsafeIndexTest() + { + float* value = stackalloc float[2 + 1] { + 0, + 1, + 2, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt16LoadUnsafeIndexTest() + { + ushort* value = stackalloc ushort[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt32LoadUnsafeIndexTest() + { + uint* value = stackalloc uint[2 + 1] { + 0, + 1, + 2, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64UInt64LoadUnsafeIndexTest() + { + ulong* value = stackalloc ulong[1 + 1] { + 0, + 1, + }; + + Vector64 vector = Vector64.LoadUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)(index + 1), vector.GetElement(index)); + } + } + + [Fact] + public void Vector64ByteShiftLeftTest() + { + Vector64 vector = Vector64.Create((byte)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int16ShiftLeftTest() + { + Vector64 vector = Vector64.Create((short)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int32ShiftLeftTest() + { + Vector64 vector = Vector64.Create((int)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int64ShiftLeftTest() + { + Vector64 vector = Vector64.Create((long)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64NIntShiftLeftTest() + { + Vector64 vector = Vector64.Create((nint)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64NUIntShiftLeftTest() + { + Vector64 vector = Vector64.Create((nuint)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64SByteShiftLeftTest() + { + Vector64 vector = Vector64.Create((sbyte)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64UInt16ShiftLeftTest() + { + Vector64 vector = Vector64.Create((ushort)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64UInt32ShiftLeftTest() + { + Vector64 vector = Vector64.Create((uint)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64UInt64ShiftLeftTest() + { + Vector64 vector = Vector64.Create((ulong)0x01); + vector = Vector64.ShiftLeft(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)0x10, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int16ShiftRightArithmeticTest() + { + Vector64 vector = Vector64.Create(unchecked((short)0x8000)); + vector = Vector64.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((short)0xF800), vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int32ShiftRightArithmeticTest() + { + Vector64 vector = Vector64.Create(unchecked((int)0x80000000)); + vector = Vector64.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((int)0xF8000000), vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int64ShiftRightArithmeticTest() + { + Vector64 vector = Vector64.Create(unchecked((long)0x8000000000000000)); + vector = Vector64.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((long)0xF800000000000000), vector.GetElement(index)); + } + } + + [Fact] + public void Vector64NIntShiftRightArithmeticTest() + { + if (Environment.Is64BitProcess) + { + Vector64 vector = Vector64.Create(unchecked((nint)0x8000000000000000)); + vector = Vector64.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((nint)0xF800000000000000), vector.GetElement(index)); + } + } + else + { + Vector64 vector = Vector64.Create(unchecked((nint)0x80000000)); + vector = Vector64.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((nint)0xF8000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector64SByteShiftRightArithmeticTest() + { + Vector64 vector = Vector64.Create(unchecked((sbyte)0x80)); + vector = Vector64.ShiftRightArithmetic(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((sbyte)0xF8), vector.GetElement(index)); + } + } + + [Fact] + public void Vector64ByteShiftRightLogicalTest() + { + Vector64 vector = Vector64.Create((byte)0x80); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)0x08, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int16ShiftRightLogicalTest() + { + Vector64 vector = Vector64.Create(unchecked((short)0x8000)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)0x0800, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int32ShiftRightLogicalTest() + { + Vector64 vector = Vector64.Create(unchecked((int)0x80000000)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)0x08000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64Int64ShiftRightLogicalTest() + { + Vector64 vector = Vector64.Create(unchecked((long)0x8000000000000000)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)0x0800000000000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64NIntShiftRightLogicalTest() + { + if (Environment.Is64BitProcess) + { + Vector64 vector = Vector64.Create(unchecked((nint)0x8000000000000000)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((nint)0x0800000000000000), vector.GetElement(index)); + } + } + else + { + Vector64 vector = Vector64.Create(unchecked((nint)0x80000000)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((nint)0x08000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector64NUIntShiftRightLogicalTest() + { + if (Environment.Is64BitProcess) + { + Vector64 vector = Vector64.Create(unchecked((nuint)0x8000000000000000)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((nuint)0x0800000000000000), vector.GetElement(index)); + } + } + else + { + Vector64 vector = Vector64.Create(unchecked((nuint)0x80000000)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal(unchecked((nuint)0x08000000), vector.GetElement(index)); + } + } + } + + [Fact] + public void Vector64SByteShiftRightLogicalTest() + { + Vector64 vector = Vector64.Create(unchecked((sbyte)0x80)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)0x08, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64UInt16ShiftRightLogicalTest() + { + Vector64 vector = Vector64.Create(unchecked((ushort)0x8000)); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)0x0800, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64UInt32ShiftRightLogicalTest() + { + Vector64 vector = Vector64.Create(0x80000000); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)0x08000000, vector.GetElement(index)); + } + } + + [Fact] + public void Vector64UInt64ShiftRightLogicalTest() + { + Vector64 vector = Vector64.Create(0x8000000000000000); + vector = Vector64.ShiftRightLogical(vector, 4); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)0x0800000000000000, vector.GetElement(index)); + } + } + + [Fact] + public unsafe void Vector64ByteStoreTest() + { + byte* value = stackalloc byte[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector64.Create((byte)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64DoubleStoreTest() + { + double* value = stackalloc double[1] { + 0, + }; + + Vector64.Create((double)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64Int16StoreTest() + { + short* value = stackalloc short[4] { + 0, + 1, + 2, + 3, + }; + + Vector64.Create((short)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64Int32StoreTest() + { + int* value = stackalloc int[2] { + 0, + 1, + }; + + Vector64.Create((int)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64Int64StoreTest() + { + long* value = stackalloc long[1] { + 0, + }; + + Vector64.Create((long)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64NIntStoreTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[1] { + 0, + }; + + Vector64.Create((nint)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + else + { + nint* value = stackalloc nint[2] { + 0, + 1, + }; + + Vector64.Create((nint)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector64NUIntStoreTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[1] { + 0, + }; + + Vector64.Create((nuint)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + else + { + nuint* value = stackalloc nuint[2] { + 0, + 1, + }; + + Vector64.Create((nuint)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector64SByteStoreTest() + { + sbyte* value = stackalloc sbyte[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector64.Create((sbyte)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64SingleStoreTest() + { + float* value = stackalloc float[2] { + 0, + 1, + }; + + Vector64.Create((float)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64UInt16StoreTest() + { + ushort* value = stackalloc ushort[4] { + 0, + 1, + 2, + 3, + }; + + Vector64.Create((ushort)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64UInt32StoreTest() + { + uint* value = stackalloc uint[2] { + 0, + 1, + }; + + Vector64.Create((uint)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64UInt64StoreTest() + { + ulong* value = stackalloc ulong[1] { + 0, + }; + + Vector64.Create((ulong)0x1).Store(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64ByteStoreAlignedTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector64.Create((byte)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64DoubleStoreAlignedTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64.Create((double)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int16StoreAlignedTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector64.Create((short)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int32StoreAlignedTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64.Create((int)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int64StoreAlignedTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64.Create((long)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64NIntStoreAlignedTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + } + else + { + value[0] = 0; + value[1] = 1; + } + + Vector64.Create((nint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64NUIntStoreAlignedTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + } + else + { + value[0] = 0; + value[1] = 1; + } + + Vector64.Create((nuint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64SByteStoreAlignedTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector64.Create((sbyte)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64SingleStoreAlignedTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64.Create((float)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt16StoreAlignedTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector64.Create((ushort)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt32StoreAlignedTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64.Create((uint)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt64StoreAlignedTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64.Create((ulong)0x1).StoreAligned(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64ByteStoreAlignedNonTemporalTest() + { + byte* value = null; + + try + { + value = (byte*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector64.Create((byte)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64DoubleStoreAlignedNonTemporalTest() + { + double* value = null; + + try + { + value = (double*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64.Create((double)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int16StoreAlignedNonTemporalTest() + { + short* value = null; + + try + { + value = (short*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector64.Create((short)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int32StoreAlignedNonTemporalTest() + { + int* value = null; + + try + { + value = (int*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64.Create((int)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64Int64StoreAlignedNonTemporalTest() + { + long* value = null; + + try + { + value = (long*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64.Create((long)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64NIntStoreAlignedNonTemporalTest() + { + nint* value = null; + + try + { + value = (nint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + } + else + { + value[0] = 0; + value[1] = 1; + } + + Vector64.Create((nint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64NUIntStoreAlignedNonTemporalTest() + { + nuint* value = null; + + try + { + value = (nuint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + if (Environment.Is64BitProcess) + { + value[0] = 0; + } + else + { + value[0] = 0; + value[1] = 1; + } + + Vector64.Create((nuint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64SByteStoreAlignedNonTemporalTest() + { + sbyte* value = null; + + try + { + value = (sbyte*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + value[4] = 4; + value[5] = 5; + value[6] = 6; + value[7] = 7; + + Vector64.Create((sbyte)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64SingleStoreAlignedNonTemporalTest() + { + float* value = null; + + try + { + value = (float*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64.Create((float)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt16StoreAlignedNonTemporalTest() + { + ushort* value = null; + + try + { + value = (ushort*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + value[2] = 2; + value[3] = 3; + + Vector64.Create((ushort)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt32StoreAlignedNonTemporalTest() + { + uint* value = null; + + try + { + value = (uint*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + value[1] = 1; + + Vector64.Create((uint)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64UInt64StoreAlignedNonTemporalTest() + { + ulong* value = null; + + try + { + value = (ulong*)NativeMemory.AlignedAlloc(byteCount: 8, alignment: 8); + + value[0] = 0; + + Vector64.Create((ulong)0x1).StoreAlignedNonTemporal(value); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + finally + { + NativeMemory.AlignedFree(value); + } + } + + [Fact] + public unsafe void Vector64ByteStoreUnsafeTest() + { + byte* value = stackalloc byte[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector64.Create((byte)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64DoubleStoreUnsafeTest() + { + double* value = stackalloc double[1] { + 0, + }; + + Vector64.Create((double)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64Int16StoreUnsafeTest() + { + short* value = stackalloc short[4] { + 0, + 1, + 2, + 3, + }; + + Vector64.Create((short)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64Int32StoreUnsafeTest() + { + int* value = stackalloc int[2] { + 0, + 1, + }; + + Vector64.Create((int)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64Int64StoreUnsafeTest() + { + long* value = stackalloc long[1] { + 0, + }; + + Vector64.Create((long)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64NIntStoreUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[1] { + 0, + }; + + Vector64.Create((nint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + else + { + nint* value = stackalloc nint[2] { + 0, + 1, + }; + + Vector64.Create((nint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector64NUIntStoreUnsafeTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[1] { + 0, + }; + + Vector64.Create((nuint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + else + { + nuint* value = stackalloc nuint[2] { + 0, + 1, + }; + + Vector64.Create((nuint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x1, value[index]); + } + } + } + + [Fact] + public unsafe void Vector64SByteStoreUnsafeTest() + { + sbyte* value = stackalloc sbyte[8] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + }; + + Vector64.Create((sbyte)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64SingleStoreUnsafeTest() + { + float* value = stackalloc float[2] { + 0, + 1, + }; + + Vector64.Create((float)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64UInt16StoreUnsafeTest() + { + ushort* value = stackalloc ushort[4] { + 0, + 1, + 2, + 3, + }; + + Vector64.Create((ushort)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64UInt32StoreUnsafeTest() + { + uint* value = stackalloc uint[2] { + 0, + 1, + }; + + Vector64.Create((uint)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64UInt64StoreUnsafeTest() + { + ulong* value = stackalloc ulong[1] { + 0, + }; + + Vector64.Create((ulong)0x1).StoreUnsafe(ref value[0]); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)0x1, value[index]); + } + } + + [Fact] + public unsafe void Vector64ByteStoreUnsafeIndexTest() + { + byte* value = stackalloc byte[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector64.Create((byte)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((byte)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64DoubleStoreUnsafeIndexTest() + { + double* value = stackalloc double[1 + 1] { + 0, + 1, + }; + + Vector64.Create((double)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((double)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64Int16StoreUnsafeIndexTest() + { + short* value = stackalloc short[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector64.Create((short)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((short)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64Int32StoreUnsafeIndexTest() + { + int* value = stackalloc int[2 + 1] { + 0, + 1, + 2, + }; + + Vector64.Create((int)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((int)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64Int64StoreUnsafeIndexTest() + { + long* value = stackalloc long[1 + 1] { + 0, + 1, + }; + + Vector64.Create((long)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((long)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64NIntStoreUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nint* value = stackalloc nint[1 + 1] { + 0, + 1, + }; + + Vector64.Create((nint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x1, value[index + 1]); + } + } + else + { + nint* value = stackalloc nint[2 + 1] { + 0, + 1, + 2, + }; + + Vector64.Create((nint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nint)0x1, value[index + 1]); + } + } + } + + [Fact] + public unsafe void Vector64NUIntStoreUnsafeIndexTest() + { + if (Environment.Is64BitProcess) + { + nuint* value = stackalloc nuint[1 + 1] { + 0, + 1, + }; + + Vector64.Create((nuint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x1, value[index + 1]); + } + } + else + { + nuint* value = stackalloc nuint[2 + 1] { + 0, + 1, + 2, + }; + + Vector64.Create((nuint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((nuint)0x1, value[index + 1]); + } + } + } + + [Fact] + public unsafe void Vector64SByteStoreUnsafeIndexTest() + { + sbyte* value = stackalloc sbyte[8 + 1] { + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + }; + + Vector64.Create((sbyte)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((sbyte)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64SingleStoreUnsafeIndexTest() + { + float* value = stackalloc float[2 + 1] { + 0, + 1, + 2, + }; + + Vector64.Create((float)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((float)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64UInt16StoreUnsafeIndexTest() + { + ushort* value = stackalloc ushort[4 + 1] { + 0, + 1, + 2, + 3, + 4, + }; + + Vector64.Create((ushort)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ushort)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64UInt32StoreUnsafeIndexTest() + { + uint* value = stackalloc uint[2 + 1] { + 0, + 1, + 2, + }; + + Vector64.Create((uint)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((uint)0x1, value[index + 1]); + } + } + + [Fact] + public unsafe void Vector64UInt64StoreUnsafeIndexTest() + { + ulong* value = stackalloc ulong[1 + 1] { + 0, + 1, + }; + + Vector64.Create((ulong)0x1).StoreUnsafe(ref value[0], 1); + + for (int index = 0; index < Vector64.Count; index++) + { + Assert.Equal((ulong)0x1, value[index + 1]); + } + } + + [Fact] + public void Vector64ByteSumTest() + { + Vector64 vector = Vector64.Create((byte)0x01); + Assert.Equal((byte)8, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64DoubleSumTest() + { + Vector64 vector = Vector64.Create((double)0x01); + Assert.Equal(1.0, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64Int16SumTest() + { + Vector64 vector = Vector64.Create((short)0x01); + Assert.Equal((short)4, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64Int32SumTest() + { + Vector64 vector = Vector64.Create((int)0x01); + Assert.Equal((int)2, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64Int64SumTest() + { + Vector64 vector = Vector64.Create((long)0x01); + Assert.Equal((long)1, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64NIntSumTest() + { + Vector64 vector = Vector64.Create((nint)0x01); + + if (Environment.Is64BitProcess) + { + Assert.Equal((nint)1, Vector64.Sum(vector)); + } + else + { + Assert.Equal((nint)2, Vector64.Sum(vector)); + } + } + + [Fact] + public void Vector64NUIntSumTest() + { + Vector64 vector = Vector64.Create((nuint)0x01); + + if (Environment.Is64BitProcess) + { + Assert.Equal((nuint)1, Vector64.Sum(vector)); + } + else + { + Assert.Equal((nuint)2, Vector64.Sum(vector)); + } + } + + [Fact] + public void Vector64SByteSumTest() + { + Vector64 vector = Vector64.Create((sbyte)0x01); + Assert.Equal((sbyte)8, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64SingleSumTest() + { + Vector64 vector = Vector64.Create((float)0x01); + Assert.Equal(2.0f, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64UInt16SumTest() + { + Vector64 vector = Vector64.Create((ushort)0x01); + Assert.Equal((ushort)4, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64UInt32SumTest() + { + Vector64 vector = Vector64.Create((uint)0x01); + Assert.Equal((uint)2, Vector64.Sum(vector)); + } + + [Fact] + public void Vector64UInt64SumTest() + { + Vector64 vector = Vector64.Create((ulong)0x01); + Assert.Equal((ulong)1, Vector64.Sum(vector)); + } + [Theory] [InlineData(0, 0)] [InlineData(1, 1)] diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/AddLambdaCapturingThis.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/AddLambdaCapturingThis.cs index 186144e290e35..a5ec0d11b1f5c 100644 --- a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/AddLambdaCapturingThis.cs +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/AddLambdaCapturingThis.cs @@ -7,19 +7,21 @@ namespace System.Reflection.Metadata.ApplyUpdate.Test { public class AddLambdaCapturingThis { - public AddLambdaCapturingThis () { - field = "abcd"; - } + public AddLambdaCapturingThis() + { + field = "abcd"; + } - public string GetField => field; + public string GetField => field; - private string field; + private string field; - public string TestMethod () { - // capture 'this' but no locals - Func fn = s => field; - return "123"; - } + public string TestMethod() + { + // capture 'this' but no locals + Func fn = s => field; + return "123"; + } } } diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/AddLambdaCapturingThis_v1.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/AddLambdaCapturingThis_v1.cs index 22dd869021dc3..44ff73ab1d591 100644 --- a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/AddLambdaCapturingThis_v1.cs +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis/AddLambdaCapturingThis_v1.cs @@ -7,23 +7,21 @@ namespace System.Reflection.Metadata.ApplyUpdate.Test { public class AddLambdaCapturingThis { - public AddLambdaCapturingThis () { - field = "abcd"; - } + public AddLambdaCapturingThis() + { + field = "abcd"; + } - public string GetField => field; + public string GetField => field; - private string field; - - public string TestMethod () { - // capture 'this' but no locals - Func fn = s => NewMethod (s + field, 42); - return fn ("123"); - } - - private string NewMethod (string s, int i) { - return i.ToString() + s; - } + private string field; + public string TestMethod() + { + // capture 'this' but no locals + Func fn = s => field; + Func fn2 = s => "42" + s + field; + return fn2 ("123"); + } } } diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/AddNestedClass.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/AddNestedClass.cs new file mode 100644 index 0000000000000..d5bd6ce27fd0e --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/AddNestedClass.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +using System; + + +namespace System.Reflection.Metadata.ApplyUpdate.Test +{ + public class AddNestedClass + { + public AddNestedClass() + { + } + + public string TestMethod() + { + return "123"; + } + + } +} diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/AddNestedClass_v1.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/AddNestedClass_v1.cs new file mode 100644 index 0000000000000..04fc6992631d9 --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/AddNestedClass_v1.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +using System; + + +namespace System.Reflection.Metadata.ApplyUpdate.Test +{ + public class AddNestedClass + { + public AddNestedClass() + { + } + + public string TestMethod() + { + var n = new Nested(); + n.f = "123"; + return n.M(); + } + + private class Nested { + public Nested() { } + internal string f; + public string M () { + return f + "456"; + } + } + } +} diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass.csproj b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass.csproj new file mode 100644 index 0000000000000..26f3348462094 --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass.csproj @@ -0,0 +1,11 @@ + + + System.Runtime.Loader.Tests + $(NetCoreAppCurrent) + true + deltascript.json + + + + + diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/deltascript.json b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/deltascript.json new file mode 100644 index 0000000000000..e70a3b3bbafbc --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass/deltascript.json @@ -0,0 +1,6 @@ +{ + "changes": [ + {"document": "AddNestedClass.cs", "update": "AddNestedClass_v1.cs"}, + ] +} + diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/AddStaticField.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/AddStaticField.cs new file mode 100644 index 0000000000000..6ac1360c3581b --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/AddStaticField.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +using System; + + +namespace System.Reflection.Metadata.ApplyUpdate.Test +{ + public class AddStaticField + { + public AddStaticField () { + } + + public string GetField => s_field; + + private static string s_field; + + public void TestMethod () { + s_field = "abcd"; + } + + } +} diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/AddStaticField_v1.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/AddStaticField_v1.cs new file mode 100644 index 0000000000000..f9282469a4fce --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/AddStaticField_v1.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +using System; + + +namespace System.Reflection.Metadata.ApplyUpdate.Test +{ + public class AddStaticField + { + public AddStaticField () { + } + + public string GetField => s_field2; + + private static string s_field; + + private static string s_field2; + + public void TestMethod () { + s_field = "spqr"; + s_field2 = "4567"; + } + + } +} diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField.csproj b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField.csproj new file mode 100644 index 0000000000000..0a3f60146cac3 --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField.csproj @@ -0,0 +1,11 @@ + + + System.Runtime.Loader.Tests + $(NetCoreAppCurrent) + true + deltascript.json + + + + + diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/deltascript.json b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/deltascript.json new file mode 100644 index 0000000000000..3c0d7a0fc6866 --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField/deltascript.json @@ -0,0 +1,6 @@ +{ + "changes": [ + {"document": "AddStaticField.cs", "update": "AddStaticField_v1.cs"}, + ] +} + diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/AddStaticLambda.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/AddStaticLambda.cs new file mode 100644 index 0000000000000..9e759e6075b5b --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/AddStaticLambda.cs @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +using System; + + +namespace System.Reflection.Metadata.ApplyUpdate.Test +{ + public class AddStaticLambda + { + public string TestMethod() + { + return "abcd"; + } + + public string Double(Func f) => f("") + f("1"); + + } +} diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/AddStaticLambda_v1.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/AddStaticLambda_v1.cs new file mode 100644 index 0000000000000..6f9e94b08a7f4 --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/AddStaticLambda_v1.cs @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +using System; + + +namespace System.Reflection.Metadata.ApplyUpdate.Test +{ + public class AddStaticLambda + { + public string TestMethod() + { + return Double(static (s) => s + "abcd"); + } + + public string Double(Func f) => f("") + f("1"); + + } +} diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda.csproj b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda.csproj new file mode 100644 index 0000000000000..3b402585aa298 --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda.csproj @@ -0,0 +1,11 @@ + + + System.Runtime.Loader.Tests + $(NetCoreAppCurrent) + true + deltascript.json + + + + + diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/deltascript.json b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/deltascript.json new file mode 100644 index 0000000000000..1d60513f4a43f --- /dev/null +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdate/System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda/deltascript.json @@ -0,0 +1,6 @@ +{ + "changes": [ + {"document": "AddStaticLambda.cs", "update": "AddStaticLambda_v1.cs"}, + ] +} + diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdateTest.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdateTest.cs index dd5c49c396335..9e28894b6bbf3 100644 --- a/src/libraries/System.Runtime.Loader/tests/ApplyUpdateTest.cs +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdateTest.cs @@ -71,6 +71,7 @@ void LambdaBodyChange() [ActiveIssue("https://github.com/dotnet/runtime/issues/54617", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] void LambdaCapturesThis() { + // Tests that changes to the body of a lambda that captures 'this' is supported. ApplyUpdateUtil.TestCase(static () => { var assm = typeof (ApplyUpdate.Test.LambdaCapturesThis).Assembly; @@ -263,25 +264,92 @@ public void AsyncMethodChanges() }); } - [ActiveIssue ("https://github.com/dotnet/runtime/issues/50249", TestRuntimes.Mono)] - [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] - public static void TestAddLambdaCapturingThis() - { - ApplyUpdateUtil.TestCase(static () => - { - var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis).Assembly; + [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] + public static void TestAddLambdaCapturingThis() + { + // Test that adding a lambda that captures 'this' (to a method that already has a lambda that captures 'this') is supported + ApplyUpdateUtil.TestCase(static () => + { + var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis).Assembly; + + var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis(); + + Assert.Equal("123", x.TestMethod()); + + ApplyUpdateUtil.ApplyUpdate(assm); + + string result = x.TestMethod(); + Assert.Equal("42123abcd", result); + }); + } + + [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] + public static void TestAddStaticField() + { + // Test that adding a new static field to an existing class is supported + ApplyUpdateUtil.TestCase(static () => + { + var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField).Assembly; + + var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddStaticField(); + + x.TestMethod(); + + Assert.Equal ("abcd", x.GetField); + + ApplyUpdateUtil.ApplyUpdate(assm); + + x.TestMethod(); + + string result = x.GetField; + Assert.Equal("4567", result); + }); + } + + [ActiveIssue("https://github.com/dotnet/runtime/issues/63643", TestRuntimes.Mono)] + [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] + public static void TestAddNestedClass() + { + // Test that adding a new nested class to an existing class is supported + ApplyUpdateUtil.TestCase(static () => + { + var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass).Assembly; + + var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddNestedClass(); + + var r = x.TestMethod(); + + Assert.Equal ("123", r); + + ApplyUpdateUtil.ApplyUpdate(assm); + + r = x.TestMethod(); - var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddLambdaCapturingThis(); + Assert.Equal("123456", r); + }); + } + + [ConditionalFact(typeof(ApplyUpdateUtil), nameof(ApplyUpdateUtil.IsSupported))] + public static void TestAddStaticLambda() + { + // Test that adding a new static lambda to an existing method body is supported + ApplyUpdateUtil.TestCase(static () => + { + var assm = typeof(System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda).Assembly; - Assert.Equal("123", x.TestMethod()); + var x = new System.Reflection.Metadata.ApplyUpdate.Test.AddStaticLambda(); - ApplyUpdateUtil.ApplyUpdate(assm); + var r = x.TestMethod(); - string result = x.TestMethod(); - Assert.Equal("42123abcd", result); - }); - } + Assert.Equal ("abcd", r); + ApplyUpdateUtil.ApplyUpdate(assm); + + r = x.TestMethod(); + + Assert.Equal("abcd1abcd", r); + }); + } class NonRuntimeAssembly : Assembly { diff --git a/src/libraries/System.Runtime.Loader/tests/ApplyUpdateUtil.cs b/src/libraries/System.Runtime.Loader/tests/ApplyUpdateUtil.cs index beaa4a0e7338b..405afc9f50edb 100644 --- a/src/libraries/System.Runtime.Loader/tests/ApplyUpdateUtil.cs +++ b/src/libraries/System.Runtime.Loader/tests/ApplyUpdateUtil.cs @@ -47,7 +47,7 @@ internal static bool CheckSupportedMonoConfiguration() { // check that interpreter is enabled, and the build has hot reload capabilities enabled. var isInterp = RuntimeFeature.IsDynamicCodeSupported && !RuntimeFeature.IsDynamicCodeCompiled; - return isInterp && HasApplyUpdateCapabilities(); + return isInterp && !PlatformDetection.IsMonoAOT && HasApplyUpdateCapabilities(); } internal static bool HasApplyUpdateCapabilities() diff --git a/src/libraries/System.Runtime.Loader/tests/System.Runtime.Loader.Tests.csproj b/src/libraries/System.Runtime.Loader/tests/System.Runtime.Loader.Tests.csproj index d678320e01740..e21bc7e673f5f 100644 --- a/src/libraries/System.Runtime.Loader/tests/System.Runtime.Loader.Tests.csproj +++ b/src/libraries/System.Runtime.Loader/tests/System.Runtime.Loader.Tests.csproj @@ -53,6 +53,9 @@ + + + diff --git a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs index 671f4af2699be..881028308dff3 100644 --- a/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs +++ b/src/libraries/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs @@ -72,7 +72,7 @@ public BigInteger(long value) } else { - ulong x = 0; + ulong x; if (value < 0) { x = unchecked((ulong)-value); @@ -148,8 +148,7 @@ public BigInteger(double value) int sign, exp; ulong man; - bool fFinite; - NumericsHelpers.GetDoubleParts(value, out sign, out exp, out man, out fFinite); + NumericsHelpers.GetDoubleParts(value, out sign, out exp, out man, out _); Debug.Assert(sign == +1 || sign == -1); if (man == 0) @@ -1542,7 +1541,6 @@ private int WriteTo(Span buffer) else { count = msb + 1; - buffer = buffer.Slice(0, count); } return count; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs index 9e5f11dbce35b..f6613c4e1b3e9 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryFormatterWriter.cs @@ -166,7 +166,7 @@ internal void WriteObject(NameInfo nameInfo, NameInfo? typeNameInfo, int numMemb var assemIdA = new int[numMembers]; for (int i = 0; i < numMembers; i++) { - object? typeInformation = null; + object? typeInformation; binaryTypeEnumA[i] = BinaryTypeConverter.GetBinaryTypeInfo(memberTypes[i], memberObjectInfos[i], null, _objectWriter, out typeInformation, out assemId); typeInformationA[i] = typeInformation; assemIdA[i] = assemId; @@ -208,7 +208,7 @@ internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, var lengthA = new int[1]; lengthA[0] = length; int[]? lowerBoundA = null; - object? typeInformation = null; + object? typeInformation; if (lowerBound == 0) { @@ -290,8 +290,8 @@ internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, var lengthA = new int[1]; lengthA[0] = length; int[]? lowerBoundA = null; - object? typeInformation = null; - int assemId = 0; + object? typeInformation; + int assemId; if (lowerBound == 0) { @@ -320,8 +320,8 @@ internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInf InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum = BinaryArrayTypeEnum.Rectangular; - object? typeInformation = null; - int assemId = 0; + object? typeInformation; + int assemId; BinaryTypeEnum binaryTypeEnum = BinaryTypeConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo._type!, objectInfo, arrayElemTypeNameInfo.NIname, _objectWriter, out typeInformation, out assemId); if (_binaryArray == null) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs index 7d9036a907ebf..bcd5cd84e52ec 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectInfo.cs @@ -94,8 +94,7 @@ internal void InitSerialize(object obj, ISurrogateSelector? surrogateSelector, S InvokeSerializationBinder(binder); objectWriter.ObjectManager.RegisterObject(obj); - ISurrogateSelector surrogateSelectorTemp; - if (surrogateSelector != null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out surrogateSelectorTemp)) != null) + if (surrogateSelector != null && (_serializationSurrogate = surrogateSelector.GetSurrogate(_objectType, context, out _)) != null) { _si = new SerializationInfo(_objectType, converter); if (!_objectType.IsPrimitive) @@ -158,7 +157,7 @@ internal void InitSerialize( if (surrogateSelector != null) { - _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out ISurrogateSelector surrogateSelectorTemp); + _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out _); } if (_serializationSurrogate != null) @@ -185,11 +184,10 @@ internal void InitSerialize( private void InitSiWrite() { - SerializationInfoEnumerator? siEnum = null; + SerializationInfoEnumerator? siEnum; _isSi = true; Debug.Assert(_si != null); - siEnum = _si.GetEnumerator(); - int infoLength = 0; + int infoLength; infoLength = _si.MemberCount; @@ -452,10 +450,9 @@ private void InitReadConstructor(Type objectType, ISurrogateSelector? surrogateS return; } - ISurrogateSelector? surrogateSelectorTemp = null; if (surrogateSelector != null) { - _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out surrogateSelectorTemp); + _serializationSurrogate = surrogateSelector.GetSurrogate(objectType, context, out _); } if (_serializationSurrogate != null) @@ -690,7 +687,7 @@ private int Position(string? name) } Type[] outMemberTypes = new Type[_cache._memberInfos.Length]; - bool isFound = false; + bool isFound; for (int i = 0; i < _cache._memberInfos.Length; i++) { if (!memberMissing && inMemberNames[i].Equals(_cache._memberInfos[i].Name)) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs index ae2f5423c27f2..de852ca940007 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectReader.cs @@ -136,8 +136,7 @@ internal object Deserialize(BinaryParser serParser) } private bool HasSurrogate(Type t) { - ISurrogateSelector ignored; - return _surrogates != null && _surrogates.GetSurrogate(t, _context, out ignored) != null; + return _surrogates != null && _surrogates.GetSurrogate(t, _context, out _) != null; } private void CheckSerializable(Type t) @@ -653,7 +652,7 @@ private void ParseArrayMember(ParseRecord pr) throw new SerializationException(SR.Serialization_ArrayTypeObject); } - object? var = null; + object? var; if (ReferenceEquals(pr._dtType, Converter.s_typeofString)) { @@ -887,7 +886,7 @@ private void RegisterObject(object? obj, ParseRecord pr, ParseRecord? objectPr, { pr._isRegistered = true; - SerializationInfo? si = null; + SerializationInfo? si; long parentId = 0; MemberInfo? memberInfo = null; int[]? indexMap = null; @@ -944,7 +943,7 @@ internal long GetId(long objectId) _valTypeObjectIdTable = new IntSizedArray(); } - long tempObjId = 0; + long tempObjId; if ((tempObjId = _valTypeObjectIdTable[(int)objectId]) == 0) { tempObjId = ThresholdForValueTypeIds + objectId; @@ -993,7 +992,7 @@ internal sealed class TypeNAssembly } Assembly? assm = null; - AssemblyName? assmName = null; + AssemblyName? assmName; try { diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs index cf57a01929bb1..26a6a41c7c7e9 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryObjectWriter.cs @@ -64,9 +64,8 @@ internal void Serialize(object graph, BinaryFormatterWriter serWriter) _serWriter = serWriter; serWriter.WriteBegin(); - long headerId = 0; + long headerId; object? obj; - bool isNew; // allocations if methodCall or methodResponse and no graph _idGenerator = new ObjectIDGenerator(); @@ -74,14 +73,14 @@ internal void Serialize(object graph, BinaryFormatterWriter serWriter) _formatterConverter = new FormatterConverter(); _serObjectInfoInit = new SerObjectInfoInit(); - _topId = InternalGetId(graph, false, null, out isNew); + _topId = InternalGetId(graph, false, null, out _); headerId = -1; WriteSerializedStreamHeader(_topId, headerId); _objectQueue.Enqueue(graph); while ((obj = GetNext(out long objectId)) != null) { - WriteObjectInfo? objectInfo = null; + WriteObjectInfo? objectInfo; // GetNext will return either an object or a WriteObjectInfo. // A WriteObjectInfo is returned if this object was member of another object @@ -587,7 +586,7 @@ private void WriteArrayMember(WriteObjectInfo objectInfo, NameInfo arrayElemType return; } - NameInfo? actualTypeInfo = null; + NameInfo? actualTypeInfo; Type? dataType = null; bool isObjectOnMember = false; @@ -976,7 +975,7 @@ private long GetAssemblyId(WriteObjectInfo objectInfo) _assemblyToIdTable = new Dictionary(); } - long assemId = 0; + long assemId; string assemblyString = objectInfo.GetAssemblyString(); string serializedAssemblyString = assemblyString; @@ -996,7 +995,7 @@ private long GetAssemblyId(WriteObjectInfo objectInfo) // Need to prefix assembly string to separate the string names from the // assemblyName string names. That is a string can have the same value // as an assemblyNameString, but it is serialized differently - bool isNew = false; + bool isNew; if (_assemblyToIdTable.TryGetValue(assemblyString, out assemId)) { isNew = false; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs index 811b74ba96bd5..9774580cb5ef4 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryParser.cs @@ -727,7 +727,7 @@ private void ReadMemberPrimitiveTyped() [RequiresUnreferencedCode(BinaryParserUnreferencedCodeMessage)] private void ReadArray(BinaryHeaderEnum binaryHeaderEnum) { - BinaryAssemblyInfo? assemblyInfo = null; + BinaryAssemblyInfo? assemblyInfo; BinaryArray record = new BinaryArray(binaryHeaderEnum); record.Read(this); diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs index 0ccb8f82e2df1..35b9531b91d72 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/BinaryTypeConverter.cs @@ -44,7 +44,7 @@ internal static BinaryTypeEnum GetBinaryTypeInfo(Type type, WriteObjectInfo? obj switch (primitiveTypeEnum) { case InternalPrimitiveTypeE.Invalid: - string? assembly = null; + string? assembly; if (objectInfo == null) { assembly = type.Assembly.FullName; diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs index b3b924b12128e..c054a013de0f3 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/Formatters/Binary/ObjectMap.cs @@ -72,12 +72,9 @@ internal ObjectMap(string objectName, string[] memberNames, BinaryTypeEnum[] bin for (int i = 0; i < memberNames.Length; i++) { - InternalPrimitiveTypeE primitiveTypeEnum; - bool isVariant; - BinaryTypeConverter.TypeFromInfo( binaryTypeEnumA[i], typeInformationA[i], objectReader, (BinaryAssemblyInfo?)assemIdToAssemblyTable[memberAssemIds[i]], - out primitiveTypeEnum, out string? typeString, out Type? type, out isVariant); + out _, out _, out Type? type, out _); _memberTypes[i] = type; } diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs index 9398d93fb1f42..a3b058fc00bd9 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System/Runtime/Serialization/ObjectManager.cs @@ -400,8 +400,8 @@ internal void CompleteObject(ObjectHolder holder, bool bObjectFullyComplete) FixupHolderList? fixups = holder._missingElements; FixupHolder? currentFixup; SerializationInfo? si; - object? fixupInfo = null; - ObjectHolder? tempObjectHolder = null; + object? fixupInfo; + ObjectHolder? tempObjectHolder; int fixupsPerformed = 0; Debug.Assert(holder != null, "[ObjectManager.CompleteObject]holder.m_object!=null"); diff --git a/src/libraries/System.Runtime/ref/System.Runtime.cs b/src/libraries/System.Runtime/ref/System.Runtime.cs index 41c562ff9d5fe..27cbc4c98d261 100644 --- a/src/libraries/System.Runtime/ref/System.Runtime.cs +++ b/src/libraries/System.Runtime/ref/System.Runtime.cs @@ -13601,6 +13601,61 @@ public sealed partial class SuppressGCTransitionAttribute : System.Attribute { public SuppressGCTransitionAttribute() { } } + public enum UnmanagedType + { + Bool = 2, + I1 = 3, + U1 = 4, + I2 = 5, + U2 = 6, + I4 = 7, + U4 = 8, + I8 = 9, + U8 = 10, + R4 = 11, + R8 = 12, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + [System.ObsoleteAttribute("Marshalling as Currency may be unavailable in future releases.")] + Currency = 15, + BStr = 19, + LPStr = 20, + LPWStr = 21, + LPTStr = 22, + ByValTStr = 23, + IUnknown = 25, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + IDispatch = 26, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + Struct = 27, + Interface = 28, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + SafeArray = 29, + ByValArray = 30, + SysInt = 31, + SysUInt = 32, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + [System.ObsoleteAttribute("Marshalling as VBByRefString may be unavailable in future releases.")] + VBByRefStr = 34, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + [System.ObsoleteAttribute("Marshalling as AnsiBStr may be unavailable in future releases.")] + AnsiBStr = 35, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + [System.ObsoleteAttribute("Marshalling as TBstr may be unavailable in future releases.")] + TBStr = 36, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + VariantBool = 37, + FunctionPtr = 38, + [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] + [System.ObsoleteAttribute("Marshalling arbitrary types may be unavailable in future releases. Specify the type you wish to marshal as.")] + AsAny = 40, + LPArray = 42, + LPStruct = 43, + CustomMarshaler = 44, + Error = 45, + IInspectable = 46, + HString = 47, + LPUTF8Str = 48, + } } namespace System.Runtime.Remoting { diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj b/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj index 92eb65f2c0ebc..801f04ca42ea9 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj +++ b/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj @@ -13,6 +13,9 @@ $(DefineConstants);FEATURE_GENERIC_MATH + + + diff --git a/src/libraries/System.Runtime/tests/System/ActivatorTests.cs b/src/libraries/System.Runtime/tests/System/ActivatorTests.cs index e4338ebdc45ab..3833e79305f25 100644 --- a/src/libraries/System.Runtime/tests/System/ActivatorTests.cs +++ b/src/libraries/System.Runtime/tests/System/ActivatorTests.cs @@ -621,7 +621,7 @@ public void CreateInstance_PublicOnlyValueTypeWithPrivateDefaultConstructor_Thro Assert.Throws(() => Activator.CreateInstance(type, nonPublic: false)); } - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsAssemblyLoadingSupported))] [MemberData(nameof(TestingCreateInstanceFromObjectHandleData))] public static void TestingCreateInstanceFromObjectHandle(string assemblyFile, string type, string returnedFullNameType, Type exceptionType) { @@ -660,8 +660,7 @@ public static void TestingCreateInstanceFromObjectHandle(string assemblyFile, st { "TestLoadAssembly.dll", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException) } }; - - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsAssemblyLoadingSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/51912", typeof(PlatformDetection), nameof(PlatformDetection.IsBuiltWithAggressiveTrimming), nameof(PlatformDetection.IsBrowser))] [MemberData(nameof(TestingCreateInstanceObjectHandleData))] public static void TestingCreateInstanceObjectHandle(string assemblyName, string type, string returnedFullNameType, Type exceptionType, bool returnNull) @@ -718,7 +717,7 @@ public static void TestingCreateInstanceObjectHandle(string assemblyName, string { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "", null, true } }; - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsAssemblyLoadingSupported))] [MemberData(nameof(TestingCreateInstanceFromObjectHandleFullSignatureData))] public static void TestingCreateInstanceFromObjectHandleFullSignature(string assemblyFile, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { @@ -740,7 +739,7 @@ public static IEnumerable TestingCreateInstanceFromObjectHandleFullSig yield return new object[] { "TestLoadAssembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; } - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsAssemblyLoadingSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/51912", typeof(PlatformDetection), nameof(PlatformDetection.IsBuiltWithAggressiveTrimming), nameof(PlatformDetection.IsBrowser))] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureData))] public static void TestingCreateInstanceObjectHandleFullSignature(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType, bool returnNull) diff --git a/src/libraries/System.Runtime/tests/System/AttributeTests.cs b/src/libraries/System.Runtime/tests/System/AttributeTests.cs index 92cb3d7621536..2484d1b9ac81c 100644 --- a/src/libraries/System.Runtime/tests/System/AttributeTests.cs +++ b/src/libraries/System.Runtime/tests/System/AttributeTests.cs @@ -154,6 +154,7 @@ class ChildAttributeWithField : ParentAttribute public int Field = 0; } + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/803", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] [Fact] [StringValue("\uDFFF")] public static void StringArgument_InvalidCodeUnits_FallbackUsed() diff --git a/src/libraries/System.Runtime/tests/System/Attributes.cs b/src/libraries/System.Runtime/tests/System/Attributes.cs index 9265e8f6d9610..e219d30a2bef4 100644 --- a/src/libraries/System.Runtime/tests/System/Attributes.cs +++ b/src/libraries/System.Runtime/tests/System/Attributes.cs @@ -42,6 +42,7 @@ public void TestIsDefined() } [Fact] + [ActiveIssue("https://github.com/dotnet/linker/issues/2078", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot) /* Stripping ComVisible because descriptors tell us so */)] public void IsDefined_PropertyInfo() { PropertyInfo pi = typeof(TestBase).GetProperty("PropBase3"); diff --git a/src/libraries/System.Runtime/tests/System/Diagnostics/StackTraceHiddenAttributeTests.cs b/src/libraries/System.Runtime/tests/System/Diagnostics/StackTraceHiddenAttributeTests.cs index 90371c32bd245..24119e52d2b3c 100644 --- a/src/libraries/System.Runtime/tests/System/Diagnostics/StackTraceHiddenAttributeTests.cs +++ b/src/libraries/System.Runtime/tests/System/Diagnostics/StackTraceHiddenAttributeTests.cs @@ -8,6 +8,7 @@ namespace System.Tests { [ActiveIssue("https://github.com/dotnet/runtime/issues/50957", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/851", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] public class StackTraceHiddenAttributeTests { [Fact] diff --git a/src/libraries/System.Runtime/tests/System/PseudoCustomAttributeTests.cs b/src/libraries/System.Runtime/tests/System/PseudoCustomAttributeTests.cs index 2525b7cf1d522..eddfb3ca5a629 100644 --- a/src/libraries/System.Runtime/tests/System/PseudoCustomAttributeTests.cs +++ b/src/libraries/System.Runtime/tests/System/PseudoCustomAttributeTests.cs @@ -11,6 +11,7 @@ namespace System.Tests { + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/830", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] public static partial class PseudoCustomAttributeTests { [Theory] diff --git a/src/libraries/System.Runtime/tests/System/Reflection/CustomAttributeDataTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/CustomAttributeDataTests.cs index 7be74a370e68a..e02f7dbed8a10 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/CustomAttributeDataTests.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/CustomAttributeDataTests.cs @@ -75,6 +75,7 @@ public static void Test_CustomAttribute_Constructor_CrossAssembly1() [Fact] [ComVisible(false)] + [ActiveIssue("https://github.com/dotnet/linker/issues/2078", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot)) /* Descriptors tell us to remove ComVisibleAttribute */] public static void Test_CustomAttribute_Constructor_CrossAssembly2() { MethodInfo m = (MethodInfo)MethodBase.GetCurrentMethod(); diff --git a/src/libraries/System.Runtime/tests/System/Reflection/InvokeWithRefLikeArgs.cs b/src/libraries/System.Runtime/tests/System/Reflection/InvokeWithRefLikeArgs.cs index 0e15a3ce9b9b9..94556ac76b001 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/InvokeWithRefLikeArgs.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/InvokeWithRefLikeArgs.cs @@ -17,6 +17,7 @@ public static void MethodReturnsRefToRefStruct_ThrowsNSE() } [Fact] + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/155", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] public static void MethodTakesRefStructAsArg_DoesNotCopyValueBack() { MethodInfo mi = GetMethod(nameof(TestClass.TakesRefStructAsArg)); @@ -28,6 +29,7 @@ public static void MethodTakesRefStructAsArg_DoesNotCopyValueBack() } [Fact] + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/155", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] public static void MethodTakesRefStructAsArgWithDefaultValue_DoesNotCopyValueBack() { MethodInfo mi = GetMethod(nameof(TestClass.TakesRefStructAsArgWithDefaultValue)); @@ -78,6 +80,7 @@ public static void PropertyTypedAsRefToRefStruct_AsPropInfo_ThrowsNSE() } [Fact] + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/155", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] public static void PropertyIndexerWithRefStructArg_DoesNotCopyValueBack() { PropertyInfo pi = typeof(TestClassWithIndexerWithRefStructArg).GetProperty("Item"); diff --git a/src/libraries/System.Runtime/tests/System/Reflection/MethodBaseTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/MethodBaseTests.cs index f3d82f82396aa..61c811fbbd8ef 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/MethodBaseTests.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/MethodBaseTests.cs @@ -50,7 +50,7 @@ public static void TestEqualityMethods(string methodName1, BindingFlags bindingF Assert.NotEqual(expected, mb1 != mb2); } - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMethodBodySupported))] public static void TestMethodBody() { MethodBase mbase = typeof(MethodBaseTests).GetMethod("MyOtherMethod", BindingFlags.Static | BindingFlags.Public); diff --git a/src/libraries/System.Runtime/tests/System/Reflection/MethodBodyTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/MethodBodyTests.cs index 8c94139abeb78..16e9a1003ae27 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/MethodBodyTests.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/MethodBodyTests.cs @@ -11,7 +11,7 @@ namespace System.Reflection.Tests { public static class MethodBodyTests { - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMethodBodySupported))] public static void Test_MethodBody_ExceptionHandlingClause() { MethodInfo mi = typeof(MethodBodyTests).GetMethod("MethodBodyExample", BindingFlags.NonPublic | BindingFlags.Static); diff --git a/src/libraries/System.Runtime/tests/System/Reflection/ModuleTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/ModuleTests.cs index 9d44bbce1d012..cbc795b9af3de 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/ModuleTests.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/ModuleTests.cs @@ -245,7 +245,7 @@ public void GetMethods() public static IEnumerable Types => Module.GetTypes(); - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] public void ResolveTypes() { foreach(Type t in Types) @@ -260,7 +260,7 @@ public void ResolveTypes() } .Union(NullTokens); - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] [MemberData(nameof(BadResolveTypes))] public void ResolveTypeFail(int token) { @@ -273,7 +273,7 @@ public void ResolveTypeFail(int token) public static IEnumerable Methods => typeof(ModuleTests).GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly); - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] public void ResolveMethodsByMethodInfo() { foreach(MethodInfo mi in Methods) @@ -289,7 +289,7 @@ public void ResolveMethodsByMethodInfo() } .Union(NullTokens); - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] [MemberData(nameof(BadResolveMethods))] public void ResolveMethodFail(int token) { @@ -302,7 +302,7 @@ public void ResolveMethodFail(int token) public static IEnumerable Fields => typeof(ModuleTests).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly); - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] [ActiveIssue("https://github.com/dotnet/runtime/issues/52072", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void ResolveFieldsByFieldInfo() { @@ -319,7 +319,7 @@ public void ResolveFieldsByFieldInfo() } .Union(NullTokens); - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] [MemberData(nameof(BadResolveFields))] public void ResolveFieldFail(int token) { @@ -338,7 +338,7 @@ public void ResolveFieldFail(int token) } .Union(NullTokens); - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] [MemberData(nameof(BadResolveStrings))] public void ResolveStringFail(int token) { @@ -348,28 +348,28 @@ public void ResolveStringFail(int token) }); } - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] public void ResolveTypesByMemberInfo() { foreach(MemberInfo mi in Types) Assert.Equal(mi, Module.ResolveMember(mi.MetadataToken)); } - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] public void ResolveMethodsByMemberInfo() { foreach (MemberInfo mi in Methods) Assert.Equal(mi, Module.ResolveMember(mi.MetadataToken)); } - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] public void ResolveFieldsByMemberInfo() { foreach (MemberInfo mi in Fields) Assert.Equal(mi, Module.ResolveMember(mi.MetadataToken)); } - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataTokenSupported))] public void ResolveMethodOfGenericClass() { Type t = typeof(Foo<>); diff --git a/src/libraries/System.Runtime/tests/System/Reflection/NullabilityInfoContextTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/NullabilityInfoContextTests.cs index f444a5624c6bb..ce939d4526302 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/NullabilityInfoContextTests.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/NullabilityInfoContextTests.cs @@ -850,6 +850,42 @@ public void AttributedParametersTest() Assert.Equal(NullabilityState.NotNull, nullabilityContext.Create(tryGetOutParameters[0]).ReadState); } + public static IEnumerable NestedGenericsCorrectOrderData() + { + yield return new object[] { + "MethodReturnsNonTupleNonTupleNullStringNullStringNullString", + new[] { NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.Nullable }, + new[] { typeof(Tuple, string>), typeof(Tuple), typeof(string), typeof(string), typeof(string) } + }; + yield return new object[] { + "MethodReturnsNonTupleNonTupleNullStringNullStringNonString", + new[] { NullabilityState.NotNull, NullabilityState.NotNull, NullabilityState.Nullable, NullabilityState.Nullable, NullabilityState.NotNull }, + new[] { typeof(Tuple, string>), typeof(Tuple), typeof(string), typeof(string), typeof(string) } + }; + } + + [Theory] + [MemberData(nameof(NestedGenericsCorrectOrderData))] + [SkipOnMono("Nullability attributes trimmed on Mono")] + public void NestedGenericsCorrectOrderTest(string methodName, NullabilityState[] nullStates, Type[] types) + { + NullabilityInfo parentInfo = nullabilityContext.Create(typeof(TypeWithNotNullContext).GetMethod(methodName)!.ReturnParameter); + var dataIndex = 0; + Examine(parentInfo); + Assert.Equal(nullStates.Length, dataIndex); + Assert.Equal(types.Length, dataIndex); + + void Examine(NullabilityInfo info) + { + Assert.Equal(types[dataIndex], info.Type); + Assert.Equal(nullStates[dataIndex++], info.ReadState); + for (var i = 0; i < info.GenericTypeArguments.Length; i++) + { + Examine(info.GenericTypeArguments[i]); + } + } + } + public static IEnumerable NestedGenericsReturnParameterData() { // public IEnumerable?> MethodReturnsEnumerableNonTupleNonNonNullValueTupleNonNullNon() => null!; @@ -1089,6 +1125,8 @@ public void MethodParametersUnknown(string s, IDictionary dict) public IEnumerable?, int>?>? MethodReturnsEnumerableNullStructNullNonNullTupleNonNullNull() => null; public IEnumerable?, int>?>? MethodReturnsEnumerableNullTupleNullNonNullStructNonNullNull() => null; public IEnumerable<(GenericStruct str, int? count)> MethodReturnsEnumerableNonValueTupleNonNullNonStructNonNullNon() => null!; + public Tuple, string?> MethodReturnsNonTupleNonTupleNullStringNullStringNullString() => null!; + public Tuple, string> MethodReturnsNonTupleNonTupleNullStringNullStringNonString() => null!; public void MethodNullNonNullNonNon(string? s, IDictionary dict) { } public void MethodNonNullNonNullNotNull(string s, [NotNull] IDictionary? dict) { dict = new Dictionary(); } public void MethodNullNonNullNullNon(string? s, IDictionary dict) { } diff --git a/src/libraries/System.Runtime/tests/System/Reflection/ReflectionCacheTests.cs b/src/libraries/System.Runtime/tests/System/Reflection/ReflectionCacheTests.cs index a74262a38d36c..4833893eb3dfe 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/ReflectionCacheTests.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/ReflectionCacheTests.cs @@ -22,7 +22,7 @@ public void GetMethod_MultipleCalls_SameObjects() } [ActiveIssue("https://github.com/dotnet/runtime/issues/50978", TestRuntimes.Mono)] - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataUpdateSupported))] public void InvokeClearCache_NoExceptions() { Action clearCache = GetClearCacheMethod(); @@ -33,7 +33,7 @@ public void InvokeClearCache_NoExceptions() } [ActiveIssue("https://github.com/dotnet/runtime/issues/50978", TestRuntimes.Mono)] - [Theory] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsMetadataUpdateSupported))] [InlineData(false)] [InlineData(true)] public void GetMethod_MultipleCalls_ClearCache_DifferentObjects(bool justSpecificType) diff --git a/src/libraries/System.Runtime/tests/System/Reflection/TypeTests.Get.CornerCases.cs b/src/libraries/System.Runtime/tests/System/Reflection/TypeTests.Get.CornerCases.cs index 2f6ff264c029e..67c99cce94312 100644 --- a/src/libraries/System.Runtime/tests/System/Reflection/TypeTests.Get.CornerCases.cs +++ b/src/libraries/System.Runtime/tests/System/Reflection/TypeTests.Get.CornerCases.cs @@ -282,6 +282,7 @@ public static void HideDetectionHappensBeforeBindingFlagChecks() Assert.Equal(0, properties.Length); } + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/865", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] [Fact] public static void HideDetectionHappensAfterPrivateInBaseClassChecks() { diff --git a/src/libraries/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeFeatureTests.cs b/src/libraries/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeFeatureTests.cs index 1c2bc0a6efea2..e8f19b6e3eb6b 100644 --- a/src/libraries/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeFeatureTests.cs +++ b/src/libraries/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeFeatureTests.cs @@ -33,8 +33,16 @@ public static void DynamicCode() [SkipOnMono("IsDynamicCodeCompiled returns false in cases where mono doesn't support these features")] public static void DynamicCode_Jit() { - Assert.True(RuntimeFeature.IsDynamicCodeSupported); - Assert.True(RuntimeFeature.IsDynamicCodeCompiled); + if (PlatformDetection.IsNativeAot) + { + Assert.False(RuntimeFeature.IsDynamicCodeSupported); + Assert.False(RuntimeFeature.IsDynamicCodeCompiled); + } + else + { + Assert.True(RuntimeFeature.IsDynamicCodeSupported); + Assert.True(RuntimeFeature.IsDynamicCodeCompiled); + } } [Fact] diff --git a/src/libraries/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeHelpersTests.cs b/src/libraries/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeHelpersTests.cs index d9b579c56476a..d1df416805ff1 100644 --- a/src/libraries/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeHelpersTests.cs +++ b/src/libraries/System.Runtime/tests/System/Runtime/CompilerServices/RuntimeHelpersTests.cs @@ -104,7 +104,11 @@ public static void PrepareMethod() RuntimeHelpers.PrepareMethod(m.MethodHandle); Assert.Throws(() => RuntimeHelpers.PrepareMethod(default(RuntimeMethodHandle))); - Assert.ThrowsAny(() => RuntimeHelpers.PrepareMethod(typeof(IList).GetMethod("Add").MethodHandle)); + + if (RuntimeFeature.IsDynamicCodeSupported) + { + Assert.ThrowsAny(() => RuntimeHelpers.PrepareMethod(typeof(IList).GetMethod("Add").MethodHandle)); + } } [Fact] @@ -124,13 +128,16 @@ public static void PrepareGenericMethod() RuntimeHelpers.PrepareMethod(typeof(List).GetMethod("Add").MethodHandle, null); - // Generic definition without instantiation is invalid - Assert.Throws(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, - null)); + if (RuntimeFeature.IsDynamicCodeSupported) + { + // Generic definition without instantiation is invalid + Assert.Throws(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, + null)); - // Wrong instantiation - Assert.Throws(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, - new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle })); + // Wrong instantiation + Assert.Throws(() => RuntimeHelpers.PrepareMethod(typeof(List<>).GetMethod("Add").MethodHandle, + new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle })); + } // // Method instantiations @@ -145,13 +152,16 @@ public static void PrepareGenericMethod() .MakeGenericMethod(new Type[] { typeof(TestStruct) }).MethodHandle, null); - // Generic definition without instantiation is invalid - Assert.Throws(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, - null)); + if (RuntimeFeature.IsDynamicCodeSupported) + { + // Generic definition without instantiation is invalid + Assert.Throws(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, + null)); - // Wrong instantiation - Assert.Throws(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, - new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle })); + // Wrong instantiation + Assert.Throws(() => RuntimeHelpers.PrepareMethod(typeof(Array).GetMethod("Resize").MethodHandle, + new RuntimeTypeHandle[] { typeof(TestStruct).TypeHandle, typeof(TestStruct).TypeHandle })); + } } [Fact] @@ -273,6 +283,7 @@ static ClassWithNormalCctor() } } + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/155", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] [Fact] public static void GetUninitalizedObject_DoesNotRunBeforeFieldInitCctors() { diff --git a/src/libraries/System.Runtime/tests/System/Runtime/JitInfoTests.cs b/src/libraries/System.Runtime/tests/System/Runtime/JitInfoTests.cs index a4fbb789f5e51..da5ff53a9a40f 100644 --- a/src/libraries/System.Runtime/tests/System/Runtime/JitInfoTests.cs +++ b/src/libraries/System.Runtime/tests/System/Runtime/JitInfoTests.cs @@ -37,7 +37,7 @@ private long MakeAndInvokeDynamicSquareMethod(int input) } - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotMonoAOT))] // JitInfo metrics will be 0 in AOT scenarios + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] // JitInfo metrics will be 0 in AOT scenarios [ActiveIssue("https://github.com/dotnet/runtime/issues/55712", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)] public void JitInfoIsPopulated() { @@ -99,7 +99,7 @@ public void JitInfoIsNotPopulated() Assert.True(afterCompiledMethodCount == 0, $"After Compiled method count not eqeual to 0! ({afterCompiledMethodCount})"); } - [Fact] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsReflectionEmitSupported))] [SkipOnMono("Mono does not track thread specific JIT information")] public void JitInfoCurrentThreadIsPopulated() { diff --git a/src/libraries/System.Runtime/tests/System/Type/TypePropertyTests.cs b/src/libraries/System.Runtime/tests/System/Type/TypePropertyTests.cs index 026c53d1bc460..cf1b8d6989d9e 100644 --- a/src/libraries/System.Runtime/tests/System/Type/TypePropertyTests.cs +++ b/src/libraries/System.Runtime/tests/System/Type/TypePropertyTests.cs @@ -147,6 +147,7 @@ public void DeclaringMethod_Get_ReturnsExpected() } } + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/864", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] [Fact] public void GenericTypeArguments_Get_ReturnsExpected() { diff --git a/src/libraries/System.Runtime/tests/System/Type/TypeTests.cs b/src/libraries/System.Runtime/tests/System/Type/TypeTests.cs index c125b558b7c60..9872ae4ceea9f 100644 --- a/src/libraries/System.Runtime/tests/System/Type/TypeTests.cs +++ b/src/libraries/System.Runtime/tests/System/Type/TypeTests.cs @@ -527,6 +527,7 @@ public void GetTypeByName_Invalid(string typeName, Type expectedException, bool } [Fact] + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/155", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] [ActiveIssue("https://github.com/dotnet/runtime/issues/52393", typeof(PlatformDetection), nameof(PlatformDetection.IsBrowser), nameof(PlatformDetection.IsMonoAOT))] public void GetTypeByName_InvokeViaReflection_Success() { @@ -928,8 +929,15 @@ public void MakeGenericType_NonRuntimeType() { foreach (Type nonRuntimeType in Helpers.NonRuntimeTypes) { - Type t = typeof(List<>).MakeGenericType(nonRuntimeType); - Assert.NotNull(t); + if (PlatformDetection.IsReflectionEmitSupported) + { + Type t = typeof(List<>).MakeGenericType(nonRuntimeType); + Assert.NotNull(t); + } + else + { + Assert.Throws(() => typeof(List<>).MakeGenericType(nonRuntimeType)); + } } } @@ -1030,6 +1038,7 @@ public static IEnumerable GetInterfaceMap_TestData() }; } + [ActiveIssue("https://github.com/dotnet/runtimelab/issues/861", typeof(PlatformDetection), nameof(PlatformDetection.IsNativeAot))] [Theory] [MemberData(nameof(GetInterfaceMap_TestData))] public void GetInterfaceMap(Type interfaceType, Type classType, Tuple[] expectedMap) diff --git a/src/libraries/System.Runtime/tests/default.rd.xml b/src/libraries/System.Runtime/tests/default.rd.xml new file mode 100644 index 0000000000000..72b0a4a60950b --- /dev/null +++ b/src/libraries/System.Runtime/tests/default.rd.xml @@ -0,0 +1,505 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs index 16dd918e4b959..d6c4a5175f980 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs @@ -1008,7 +1008,6 @@ private void QuickSort(int left, int right, bool isDacl) { GenericAce pivot; int leftHold, rightHold; - int pivotIndex; if (left >= right) { @@ -1019,7 +1018,6 @@ private void QuickSort(int left, int right, bool isDacl) rightHold = right; pivot = _acl[left]; - pivotIndex = left; while (left < right) { @@ -1049,7 +1047,7 @@ private void QuickSort(int left, int right, bool isDacl) } _acl[left] = pivot; - pivotIndex = left; + int pivotIndex = left; left = leftHold; right = rightHold; @@ -1386,8 +1384,6 @@ private bool GetAccessMaskForRemoval(QualifiedAce ace, ObjectAceFlags objectFlag if (ace is ObjectAce objectAce) { - bool commonAccessBitsWithObjectTypeExist = true; - // // if what we are trying to remove has an object type // but the existing ace does not then this is an invalid case @@ -1403,7 +1399,7 @@ private bool GetAccessMaskForRemoval(QualifiedAce ace, ObjectAceFlags objectFlag // if object types match (since at this point we have ensured that both have object types present) // then we have common access bits with object type // - commonAccessBitsWithObjectTypeExist = ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) == 0) || + bool commonAccessBitsWithObjectTypeExist = ((objectFlags & ObjectAceFlags.ObjectAceTypePresent) == 0) || objectAce.ObjectTypesMatch(objectFlags, objectType); if (!commonAccessBitsWithObjectTypeExist) { @@ -1442,8 +1438,6 @@ private bool GetInheritanceFlagsForRemoval(QualifiedAce ace, ObjectAceFlags obje if (ace is ObjectAce objectAce) { - bool commonInheritanceFlagsExist = true; - // // if what we are trying to remove has an inherited object type // but the existing ace does not then this is an invalid case @@ -1458,7 +1452,7 @@ private bool GetInheritanceFlagsForRemoval(QualifiedAce ace, ObjectAceFlags obje // if what we are trying to remove has no inherited object type or // if inherited object types match then we have common inheritance flags // - commonInheritanceFlagsExist = ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) == 0) || + bool commonInheritanceFlagsExist = ((objectFlags & ObjectAceFlags.InheritedObjectAceTypePresent) == 0) || objectAce.InheritedObjectTypesMatch(objectFlags, inheritedObjectType); if (!commonInheritanceFlagsExist) { diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs index e03dd2ca45f62..81fa5c2dab998 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs @@ -446,8 +446,7 @@ protected void AddAccessRule(AccessRule rule) try { - bool modified; - ModifyAccess(AccessControlModification.Add, rule, out modified); + ModifyAccess(AccessControlModification.Add, rule, out _); } finally { @@ -466,8 +465,7 @@ protected void SetAccessRule(AccessRule rule) try { - bool modified; - ModifyAccess(AccessControlModification.Set, rule, out modified); + ModifyAccess(AccessControlModification.Set, rule, out _); } finally { @@ -486,8 +484,7 @@ protected void ResetAccessRule(AccessRule rule) try { - bool modified; - ModifyAccess(AccessControlModification.Reset, rule, out modified); + ModifyAccess(AccessControlModification.Reset, rule, out _); } finally { @@ -513,8 +510,7 @@ protected bool RemoveAccessRule(AccessRule rule) return true; } - bool modified; - return ModifyAccess(AccessControlModification.Remove, rule, out modified); + return ModifyAccess(AccessControlModification.Remove, rule, out _); } finally { @@ -538,8 +534,7 @@ protected void RemoveAccessRuleAll(AccessRule rule) return; } - bool modified; - ModifyAccess(AccessControlModification.RemoveAll, rule, out modified); + ModifyAccess(AccessControlModification.RemoveAll, rule, out _); } finally { @@ -565,8 +560,7 @@ protected void RemoveAccessRuleSpecific(AccessRule rule) return; } - bool modified; - ModifyAccess(AccessControlModification.RemoveSpecific, rule, out modified); + ModifyAccess(AccessControlModification.RemoveSpecific, rule, out _); } finally { @@ -585,8 +579,7 @@ protected void AddAuditRule(AuditRule rule) try { - bool modified; - ModifyAudit(AccessControlModification.Add, rule, out modified); + ModifyAudit(AccessControlModification.Add, rule, out _); } finally { @@ -605,8 +598,7 @@ protected void SetAuditRule(AuditRule rule) try { - bool modified; - ModifyAudit(AccessControlModification.Set, rule, out modified); + ModifyAudit(AccessControlModification.Set, rule, out _); } finally { @@ -625,8 +617,7 @@ protected bool RemoveAuditRule(AuditRule rule) try { - bool modified; - return ModifyAudit(AccessControlModification.Remove, rule, out modified); + return ModifyAudit(AccessControlModification.Remove, rule, out _); } finally { @@ -645,8 +636,7 @@ protected void RemoveAuditRuleAll(AuditRule rule) try { - bool modified; - ModifyAudit(AccessControlModification.RemoveAll, rule, out modified); + ModifyAudit(AccessControlModification.RemoveAll, rule, out _); } finally { @@ -665,8 +655,7 @@ protected void RemoveAuditRuleSpecific(AuditRule rule) try { - bool modified; - ModifyAudit(AccessControlModification.RemoveSpecific, rule, out modified); + ModifyAudit(AccessControlModification.RemoveSpecific, rule, out _); } finally { diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs index 80e6780f977a8..6c4a290db11df 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/SecurityDescriptor.cs @@ -385,7 +385,6 @@ public void GetBinaryForm(byte[] binaryForm, int offset) { MarshalInt(binaryForm, daclOffset, offset - originalOffset); GenericDacl.GetBinaryForm(binaryForm, offset); - offset += GenericDacl.BinaryLength; } else { diff --git a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs index 2126308dc518d..6da13d9a9bf80 100644 --- a/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs +++ b/src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.cs @@ -841,7 +841,7 @@ protected virtual void WriteTo(BinaryWriter writer, byte[]? userData) if (_bootstrapContext != null) { - if (_bootstrapContext is string rawData) + if (_bootstrapContext is string) { mask |= SerializationMask.BootstrapConext; numberOfPropertiesWritten++; diff --git a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/Helpers.cs b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/Helpers.cs index 12494c06a9607..3cbf93ae7510d 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/Helpers.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/Helpers.cs @@ -140,9 +140,8 @@ public static IntPtr GetPropertyAsIntPtr(this SafeNCryptHandle ncryptHandle, str { unsafe { - int numBytesNeeded; IntPtr value; - ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, &value, IntPtr.Size, out numBytesNeeded, options); + ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty(ncryptHandle, propertyName, &value, IntPtr.Size, out _, options); if (errorCode == ErrorCode.NTE_NOT_FOUND) return IntPtr.Zero; if (errorCode != ErrorCode.ERROR_SUCCESS) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Import.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Import.cs index 94a16df59de9b..6b4950fe4ce14 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Import.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Import.cs @@ -122,7 +122,7 @@ internal static CngKey Import( throw new ArgumentNullException(nameof(provider)); SafeNCryptProviderHandle providerHandle = provider.OpenStorageProvider(); - SafeNCryptKeyHandle? keyHandle = null; + SafeNCryptKeyHandle? keyHandle; ErrorCode errorCode; if (curveName == null) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Properties.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Properties.cs index 5da2553d01f08..998690be8ea3a 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Properties.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/CngKey.Properties.cs @@ -40,8 +40,7 @@ public bool HasProperty(string name, CngPropertyOptions options) unsafe { - int numBytesNeeded; - ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty(_keyHandle, name, null, 0, out numBytesNeeded, options); + ErrorCode errorCode = Interop.NCrypt.NCryptGetProperty(_keyHandle, name, null, 0, out _, options); if (errorCode == ErrorCode.NTE_NOT_FOUND) return false; if (errorCode != ErrorCode.ERROR_SUCCESS) diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs index defa12719ebf3..baf5046f242e3 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDiffieHellmanCng.Key.cs @@ -68,7 +68,7 @@ public override void GenerateKey(ECCurve curve) } else { - int keySize = 0; + int keySize; // Get the proper KeySize from algorithm name if (alg == CngAlgorithm.ECDiffieHellmanP256) keySize = 256; @@ -108,10 +108,9 @@ private CngKey GetKey() else { CngAlgorithm algorithm; - int keySize = 0; // Map the current key size to a CNG algorithm name - keySize = KeySize; + int keySize = KeySize; switch (keySize) { case 256: diff --git a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.Key.cs b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.Key.cs index 549e1e9aeaf99..aabaf16795753 100644 --- a/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.Key.cs +++ b/src/libraries/System.Security.Cryptography.Cng/src/System/Security/Cryptography/ECDsaCng.Key.cs @@ -57,7 +57,7 @@ public override void GenerateKey(ECCurve curve) } else { - int keySize = 0; + int keySize; // Get the proper KeySize from algorithm name if (alg == CngAlgorithm.ECDsaP256) keySize = 256; @@ -87,7 +87,7 @@ public override void GenerateKey(ECCurve curve) private CngKey GetKey() { - CngKey? key = null; + CngKey key; if (_core.IsKeyGeneratedNamedCurve()) { @@ -96,11 +96,10 @@ private CngKey GetKey() } else { - CngAlgorithm? algorithm = null; - int keySize = 0; + CngAlgorithm algorithm; // Map the current key size to a CNG algorithm name - keySize = KeySize; + int keySize = KeySize; switch (keySize) { case 256: algorithm = CngAlgorithm.ECDsaP256; break; diff --git a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Unix/HashAlgorithmNames.cs b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Unix/HashAlgorithmNames.cs index 05ef0d091e1cb..9645cee8c6120 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Unix/HashAlgorithmNames.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/Internal/Cryptography/Unix/HashAlgorithmNames.cs @@ -51,7 +51,7 @@ public static HashAlgorithmName ObjToHashAlgorithmName(object hashAlg) public static HashAlgorithmName NameOrOidToHashAlgorithmName(string nameOrOid) { - HashAlgorithmName? name = null; + HashAlgorithmName? name; if (nameOrOid == null) { diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.DSA.Shared.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.DSA.Shared.cs index 4e6b8e0577889..67a22cd75d116 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.DSA.Shared.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.DSA.Shared.cs @@ -310,7 +310,7 @@ private static void WriteKeyBlobHeader(DSAParameters dsaParameters, BinaryWriter private static void ReadDSSSeed(DSAParameters dsaParameters, BinaryReader br, bool isV3) { - bool hasSeed = false; + bool hasSeed; int counter = br.ReadInt32(); if (isV3) diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs index b8d4841fee8b5..48c6a78764fa6 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/CapiHelper.Windows.cs @@ -366,7 +366,7 @@ public static object GetProviderParameter(SafeProvHandle safeProvHandle, int key byte[] impType = new byte[Constants.SIZE_OF_DWORD]; int cb = sizeof(byte) * Constants.SIZE_OF_DWORD; SafeKeyHandle safeKeyHandle = SafeKeyHandle.InvalidHandle; - int impTypeReturn = 0; + int impTypeReturn; int returnType = 0; //using 0 for bool and 1 for string return types bool retVal = false; string? retStr = null; diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/MD5CryptoServiceProvider.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/MD5CryptoServiceProvider.cs index 1adf8231508a7..8b0a74d682f8e 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/MD5CryptoServiceProvider.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/MD5CryptoServiceProvider.cs @@ -10,21 +10,20 @@ namespace System.Security.Cryptography [EditorBrowsable(EditorBrowsableState.Never)] public sealed class MD5CryptoServiceProvider : MD5 { - private const int HashSizeBits = 128; private readonly IncrementalHash _incrementalHash; private bool _running; public MD5CryptoServiceProvider() { _incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.MD5); - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public override void Initialize() { if (_running) { - Span destination = stackalloc byte[HashSizeBits / 8]; + Span destination = stackalloc byte[HashSizeInBytes]; if (!_incrementalHash.TryGetHashAndReset(destination, out _)) { diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA1CryptoServiceProvider.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA1CryptoServiceProvider.cs index d04fab61a30b7..633db195df429 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA1CryptoServiceProvider.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA1CryptoServiceProvider.cs @@ -13,21 +13,20 @@ namespace System.Security.Cryptography [EditorBrowsable(EditorBrowsableState.Never)] public sealed class SHA1CryptoServiceProvider : SHA1 { - private const int HashSizeBits = 160; private readonly IncrementalHash _incrementalHash; private bool _running; public SHA1CryptoServiceProvider() { _incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1); - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public override void Initialize() { if (_running) { - Span destination = stackalloc byte[HashSizeBits / 8]; + Span destination = stackalloc byte[HashSizeInBytes]; if (!_incrementalHash.TryGetHashAndReset(destination, out _)) { diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA256CryptoServiceProvider.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA256CryptoServiceProvider.cs index 066f47937630d..6f33a0ccf1536 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA256CryptoServiceProvider.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA256CryptoServiceProvider.cs @@ -13,21 +13,20 @@ namespace System.Security.Cryptography [EditorBrowsable(EditorBrowsableState.Never)] public sealed class SHA256CryptoServiceProvider : SHA256 { - private const int HashSizeBits = 256; private readonly IncrementalHash _incrementalHash; private bool _running; public SHA256CryptoServiceProvider() { _incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public override void Initialize() { if (_running) { - Span destination = stackalloc byte[HashSizeBits / 8]; + Span destination = stackalloc byte[HashSizeInBytes]; if (!_incrementalHash.TryGetHashAndReset(destination, out _)) { diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA384CryptoServiceProvider.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA384CryptoServiceProvider.cs index 4734eb0f29a30..5d5a9aceccf82 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA384CryptoServiceProvider.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA384CryptoServiceProvider.cs @@ -13,21 +13,20 @@ namespace System.Security.Cryptography [EditorBrowsable(EditorBrowsableState.Never)] public sealed class SHA384CryptoServiceProvider : SHA384 { - private const int HashSizeBits = 384; private readonly IncrementalHash _incrementalHash; private bool _running; public SHA384CryptoServiceProvider() { _incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA384); - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public override void Initialize() { if (_running) { - Span destination = stackalloc byte[HashSizeBits / 8]; + Span destination = stackalloc byte[HashSizeInBytes]; if (!_incrementalHash.TryGetHashAndReset(destination, out _)) { diff --git a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA512CryptoServiceProvider.cs b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA512CryptoServiceProvider.cs index 338090eae1949..0b565697fe183 100644 --- a/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA512CryptoServiceProvider.cs +++ b/src/libraries/System.Security.Cryptography.Csp/src/System/Security/Cryptography/SHA512CryptoServiceProvider.cs @@ -13,21 +13,20 @@ namespace System.Security.Cryptography [EditorBrowsable(EditorBrowsableState.Never)] public sealed class SHA512CryptoServiceProvider : SHA512 { - private const int HashSizeBits = 512; private readonly IncrementalHash _incrementalHash; private bool _running; public SHA512CryptoServiceProvider() { _incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA512); - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public override void Initialize() { if (_running) { - Span destination = stackalloc byte[HashSizeBits / 8]; + Span destination = stackalloc byte[HashSizeInBytes]; if (!_incrementalHash.TryGetHashAndReset(destination, out _)) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs index 3c8bc809921ca..150e3a73a7d23 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Decrypt.cs @@ -205,7 +205,6 @@ private static byte[] GetAsnSequenceWithContentNoValidation(ReadOnlySpan c finally { CryptoPool.Return(encryptedContentArray, encryptedContentLength); - encryptedContentArray = null; } } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs index dd275fb1e6ebb..4a69b15ad7084 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/HelpersWindows.cs @@ -119,7 +119,7 @@ public static ContentInfo GetContentInfo(this SafeCryptMsgHandle hCryptMsg) public static X509Certificate2Collection GetOriginatorCerts(this SafeCryptMsgHandle hCryptMsg) { - int numCertificates = 0; + int numCertificates; int cbNumCertificates = sizeof(int); if (!Interop.Crypt32.CryptMsgGetParam(hCryptMsg, CryptMsgParamType.CMSG_CERT_COUNT_PARAM, 0, out numCertificates, ref cbNumCertificates)) throw Marshal.GetLastWin32Error().ToCryptographicException(); diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.OSX/ChainPal.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.OSX/ChainPal.cs index 306cfbed4b9ec..2a26d06f80580 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.OSX/ChainPal.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.OSX/ChainPal.cs @@ -490,7 +490,6 @@ private X509ChainElement BuildElement(X509Certificate2 cert, int dwStatus) } else { - osStatus = mapping.OSStatus; errorString = mapping.ErrorString; } diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/CrlCache.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/CrlCache.cs index eddad467f171b..4dd122871b0a7 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/CrlCache.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/CrlCache.cs @@ -212,7 +212,7 @@ private static string GetCrlFileName(SafeX509Handle cert, string crlUrl) } uint persistentHash = unchecked((uint)persistentHashLong); - Span hash = stackalloc byte[256 >> 3]; + Span hash = stackalloc byte[SHA256.HashSizeInBytes]; // Endianness isn't important, it just needs to be consistent. // (Even if the same storage was used for two different endianness systems it'd stabilize at two files). diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/PkcsFormatReader.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/PkcsFormatReader.cs index f73b59373233d..b7f10c81a8c66 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/PkcsFormatReader.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/PkcsFormatReader.cs @@ -79,30 +79,22 @@ internal static bool IsPkcs7Pem(SafeBioHandle fileBio) internal static bool TryReadPkcs7Der(ReadOnlySpan rawData, out ICertificatePal? certPal) { - List? ignored; - - return TryReadPkcs7Der(rawData, true, out certPal, out ignored); + return TryReadPkcs7Der(rawData, true, out certPal, out _); } internal static bool TryReadPkcs7Der(SafeBioHandle bio, out ICertificatePal? certPal) { - List? ignored; - - return TryReadPkcs7Der(bio, true, out certPal, out ignored); + return TryReadPkcs7Der(bio, true, out certPal, out _); } internal static bool TryReadPkcs7Der(ReadOnlySpan rawData, [NotNullWhen(true)] out List? certPals) { - ICertificatePal? ignored; - - return TryReadPkcs7Der(rawData, false, out ignored, out certPals); + return TryReadPkcs7Der(rawData, false, out _, out certPals); } internal static bool TryReadPkcs7Der(SafeBioHandle bio, [NotNullWhen(true)] out List? certPals) { - ICertificatePal? ignored; - - return TryReadPkcs7Der(bio, false, out ignored, out certPals); + return TryReadPkcs7Der(bio, false, out _, out certPals); } private static bool TryReadPkcs7Der( @@ -147,30 +139,22 @@ private static bool TryReadPkcs7Der( internal static bool TryReadPkcs7Pem(ReadOnlySpan rawData, out ICertificatePal? certPal) { - List? ignored; - - return TryReadPkcs7Pem(rawData, true, out certPal, out ignored); + return TryReadPkcs7Pem(rawData, true, out certPal, out _); } internal static bool TryReadPkcs7Pem(SafeBioHandle bio, out ICertificatePal? certPal) { - List? ignored; - - return TryReadPkcs7Pem(bio, true, out certPal, out ignored); + return TryReadPkcs7Pem(bio, true, out certPal, out _); } internal static bool TryReadPkcs7Pem(ReadOnlySpan rawData, [NotNullWhen(true)] out List? certPals) { - ICertificatePal? ignored; - - return TryReadPkcs7Pem(rawData, false, out ignored, out certPals); + return TryReadPkcs7Pem(rawData, false, out _, out certPals); } internal static bool TryReadPkcs7Pem(SafeBioHandle bio, [NotNullWhen(true)] out List? certPals) { - ICertificatePal? ignored; - - return TryReadPkcs7Pem(bio, false, out ignored, out certPals); + return TryReadPkcs7Pem(bio, false, out _, out certPals); } private static bool TryReadPkcs7Pem( @@ -260,15 +244,13 @@ internal static bool TryReadPkcs12( [NotNullWhen(true)] out ICertificatePal? certPal, out Exception? openSslException) { - List? ignored; - return TryReadPkcs12( rawData, password, single: true, ephemeralSpecified, out certPal!, - out ignored, + out _, out openSslException); } @@ -279,14 +261,12 @@ internal static bool TryReadPkcs12( [NotNullWhen(true)] out List? certPals, out Exception? openSslException) { - ICertificatePal? ignored; - return TryReadPkcs12( rawData, password, single: false, ephemeralSpecified, - out ignored, + out _, out certPals!, out openSslException); } diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/UnixExportProvider.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/UnixExportProvider.cs index 0ad2762dd9457..a6e50de9d4407 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/UnixExportProvider.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/UnixExportProvider.cs @@ -481,10 +481,9 @@ private static unsafe byte[] MacAndEncode( ReadOnlyMemory encodedAuthSafe, ReadOnlySpan passwordSpan) { - const int MacSize = 160 / 8; // HMAC-SHA1 is 160 bits. - Span macKey = stackalloc byte[MacSize]; - Span macSalt = stackalloc byte[MacSize]; - Span macSpan = stackalloc byte[MacSize]; + Span macKey = stackalloc byte[HMACSHA1.HashSizeInBytes]; + Span macSalt = stackalloc byte[HMACSHA1.HashSizeInBytes]; + Span macSpan = stackalloc byte[HMACSHA1.HashSizeInBytes]; RandomNumberGenerator.Fill(macSalt); Pkcs12Kdf.DeriveMacKey( @@ -496,9 +495,9 @@ private static unsafe byte[] MacAndEncode( int bytesWritten = HMACSHA1.HashData(macKey, encodedAuthSafe.Span, macSpan); - if (bytesWritten != MacSize) + if (bytesWritten != HMACSHA1.HashSizeInBytes) { - Debug.Fail($"HMACSHA1.HashData wrote {bytesWritten} of {MacSize} bytes"); + Debug.Fail($"HMACSHA1.HashData wrote {bytesWritten} of {HMACSHA1.HashSizeInBytes} bytes"); throw new CryptographicException(); } diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs index 95210c8f2ce0b..264079d50d9d1 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs @@ -75,7 +75,7 @@ public bool HasPrivateKey public ICertificatePal CopyWithPrivateKey(DSA dsa) { DSACng? dsaCng = dsa as DSACng; - ICertificatePal? clone = null; + ICertificatePal? clone; if (dsaCng != null) { @@ -163,7 +163,7 @@ public ICertificatePal CopyWithPrivateKey(ECDiffieHellman ecdh) public ICertificatePal CopyWithPrivateKey(RSA rsa) { RSACng? rsaCng = rsa as RSACng; - ICertificatePal? clone = null; + ICertificatePal? clone; if (rsaCng != null) { diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs index f8020c96e050d..a6fc4c8e57a90 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs @@ -29,9 +29,8 @@ public static ICertificatePal FromHandle(IntPtr handle) if (safeCertContextHandle.IsInvalid) throw ErrorCode.HRESULT_INVALID_HANDLE.ToCryptographicException(); - Interop.Crypt32.DATA_BLOB dataBlob; int cbData = 0; - bool deleteKeyContainer = Interop.Crypt32.CertGetCertificateContextProperty(safeCertContextHandle, Interop.Crypt32.CertContextPropId.CERT_CLR_DELETE_KEY_PROP_ID, out dataBlob, ref cbData); + bool deleteKeyContainer = Interop.Crypt32.CertGetCertificateContextProperty(safeCertContextHandle, Interop.Crypt32.CertContextPropId.CERT_CLR_DELETE_KEY_PROP_ID, out Interop.Crypt32.DATA_BLOB _, ref cbData); return new CertificatePal(safeCertContextHandle, deleteKeyContainer); } diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs index bbabcba73603c..13dcd63f4f91f 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs @@ -149,7 +149,7 @@ private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyB { string blobFormatString = blobFormat.Format; - int numBytesNeeded = 0; + int numBytesNeeded; NTSTATUS ntStatus = Interop.BCrypt.BCryptExportKey(bCryptKeyHandle, IntPtr.Zero, blobFormatString, null, 0, out numBytesNeeded, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw new CryptographicException(Interop.Kernel32.GetMessage((int)ntStatus)); diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.iOS/ApplePkcs12CertLoader.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.iOS/ApplePkcs12CertLoader.cs index ac420ca1c2423..8de11e24f7d80 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.iOS/ApplePkcs12CertLoader.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.iOS/ApplePkcs12CertLoader.cs @@ -39,7 +39,6 @@ public void MoveTo(X509Certificate2Collection collection) { foreach (UnixPkcs12Reader.CertAndKey certAndKey in _pkcs12.EnumerateAll()) { - AppleCertificatePal pal = (AppleCertificatePal)certAndKey.Cert!; collection.Add(new X509Certificate2(AppleCertificatePal.ImportPkcs12(certAndKey))); } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs index 362ad7412ce1e..0bbafb6db14ca 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/AncestralNamespaceContextManager.cs @@ -22,7 +22,7 @@ internal NamespaceFrame GetCurrentScope() protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) { - XmlAttribute attr = null; + XmlAttribute attr; depth = -1; for (int i = _ancestorStack.Count - 1; i >= 0; i--) { @@ -37,7 +37,7 @@ protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPr protected XmlAttribute GetNearestUnrenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth) { - XmlAttribute attr = null; + XmlAttribute attr; depth = -1; for (int i = _ancestorStack.Count - 1; i >= 0; i--) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs index 9eb170965b7e5..8dcde4c2298d3 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/C14NAncestralNamespaceContextManager.cs @@ -55,7 +55,7 @@ private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, internal override void GetNamespacesToRender(XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared) { - XmlAttribute attrib = null; + XmlAttribute attrib; object[] attrs = new object[nsLocallyDeclared.Count]; nsLocallyDeclared.Values.CopyTo(attrs, 0); foreach (object a in attrs) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs index 78786591c25c5..15315fd464eda 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs @@ -193,7 +193,7 @@ private byte[] GetCipherValue(CipherData cipherData) { if (cipherData.CipherReference.CipherValue != null) return cipherData.CipherReference.CipherValue; - Stream decInputStream = null; + Stream decInputStream; if (cipherData.CipherReference.Uri == null) { throw new CryptographicException(SR.Cryptography_Xml_UriNotSupported); @@ -269,7 +269,7 @@ public virtual byte[] GetDecryptionIV(EncryptedData encryptedData, string symmet if (encryptedData == null) throw new ArgumentNullException(nameof(encryptedData)); - int initBytesSize = 0; + int initBytesSize; // If the Uri is not provided by the application, try to get it from the EncryptionMethod if (symmetricAlgorithmUri == null) { @@ -397,8 +397,8 @@ public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) KeyInfoX509Data kiX509Data; KeyInfoRetrievalMethod kiRetrievalMethod; KeyInfoEncryptedKey kiEncKey; - EncryptedKey ek = null; - bool fOAEP = false; + EncryptedKey ek; + bool fOAEP; while (keyInfoEnum.MoveNext()) { @@ -691,7 +691,7 @@ public byte[] EncryptData(byte[] plaintext, SymmetricAlgorithm symmetricAlgorith symmetricAlgorithm.Padding = origPadding; } - byte[] output = null; + byte[] output; if (_mode == CipherMode.ECB) { output = cipher; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs index eadbdbf565ed9..4c5738fcf69ff 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/ExcAncestralNamespaceContextManager.cs @@ -19,10 +19,9 @@ internal ExcAncestralNamespaceContextManager(string inclusiveNamespacesPrefixLis private bool HasNonRedundantInclusivePrefix(XmlAttribute attr) { - int tmp; string nsPrefix = Utils.GetNamespacePrefix(attr); return _inclusivePrefixSet.ContainsKey(nsPrefix) && - Utils.IsNonRedundantNamespaceDecl(attr, GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out tmp)); + Utils.IsNonRedundantNamespaceDecl(attr, GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out _)); } private void GatherNamespaceToRender(string nsPrefix, SortedList nsListToRender, Hashtable nsLocallyDeclared) diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs index d1127b33f7000..545c42499cb85 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/KeyInfoX509Data.cs @@ -45,8 +45,8 @@ public KeyInfoX509Data(X509Certificate cert, X509IncludeOption includeOption) throw new ArgumentNullException(nameof(cert)); X509Certificate2 certificate = new X509Certificate2(cert); - X509ChainElementCollection elements = null; - X509Chain chain = null; + X509ChainElementCollection elements; + X509Chain chain; switch (includeOption) { case X509IncludeOption.ExcludeRoot: diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs index 2ad68d28dd83f..fbedd3a907cdd 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs @@ -242,8 +242,7 @@ public void AddObject(DataObject dataObject) public bool CheckSignature() { - AsymmetricAlgorithm signingKey; - return CheckSignatureReturningKey(out signingKey); + return CheckSignatureReturningKey(out _); } public bool CheckSignatureReturningKey(out AsymmetricAlgorithm signingKey) @@ -252,7 +251,7 @@ public bool CheckSignatureReturningKey(out AsymmetricAlgorithm signingKey) signingKey = null; bool bRet = false; - AsymmetricAlgorithm key = null; + AsymmetricAlgorithm key; if (!CheckSignatureFormat()) { @@ -643,7 +642,7 @@ private bool DoesSignatureUseTruncatedHmac() } // Figure out how many bits the signature is using - int actualSignatureSize = 0; + int actualSignatureSize; if (!int.TryParse(SignedInfo.SignatureLength, out actualSignatureSize)) { // If the value wasn't a valid integer, then we'll conservatively reject it all together @@ -917,7 +916,7 @@ private bool CheckDigestedReferences() } SignedXmlDebugLog.LogVerifyReference(this, digestedReference); - byte[] calculatedHash = null; + byte[] calculatedHash; try { calculatedHash = digestedReference.CalculateHashValue(_containingDocument, m_signature.ReferencedItems); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs index e70615426c2bb..895837406b6b5 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXmlDebugLog.cs @@ -219,7 +219,7 @@ private static string GetKeyName(object key) // * All others -> hash code // - string keyName = null; + string keyName; #pragma warning disable CA1416 // This call site is reachable on all platforms. 'CspKeyContainerInfo.KeyContainerName' is supported on: 'windows'. if (cspKey != null && cspKey.CspKeyContainerInfo.KeyContainerName != null) { @@ -586,7 +586,7 @@ internal static Stream LogReferenceData(Reference reference, Stream data) // First read the input stream into our temporary stream byte[] buffer = new byte[4096]; - int readBytes = 0; + int readBytes; do { readBytes = data.Read(buffer, 0, buffer.Length); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs index e293e109b2133..2bbc23cc66612 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs @@ -359,7 +359,7 @@ internal static string ExtractIdFromLocalUri(string uri) internal static void RemoveAllChildren(XmlElement inputElement) { XmlNode child = inputElement.FirstChild; - XmlNode sibling = null; + XmlNode sibling; while (child != null) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs index 812d84800cdf0..ed1b2b16db26e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDsigBase64Transform.cs @@ -68,7 +68,7 @@ private void LoadStreamInput(Stream inputStream) bytesRead = inputStream.Read(buffer, 0, 1024); if (bytesRead > 0) { - int i = 0; + int i; int j = 0; while ((j < bytesRead) && (!char.IsWhiteSpace((char)buffer[j]))) j++; i = j; j++; @@ -99,7 +99,7 @@ private void LoadXmlNodeListInput(XmlNodeList nodeList) } UTF8Encoding utf8 = new UTF8Encoding(false); byte[] buffer = utf8.GetBytes(sb.ToString()); - int i = 0; + int i; int j = 0; while ((j < buffer.Length) && (!char.IsWhiteSpace((char)buffer[j]))) j++; i = j; j++; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs index 3edd81816ae3f..7222346b85b4e 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlLicenseTransform.cs @@ -39,12 +39,12 @@ public IRelDecryptor Decryptor private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecryptor decryptor) { - XmlElement encryptionMethod = null; - XmlElement keyInfo = null; - XmlElement cipherData = null; - EncryptionMethod encryptionMethodObj = null; - KeyInfo keyInfoObj = null; - CipherData cipherDataObj = null; + XmlElement encryptionMethod; + XmlElement keyInfo; + XmlElement cipherData; + EncryptionMethod encryptionMethodObj; + KeyInfo keyInfoObj; + CipherData cipherDataObj; for (int i = 0, count = encryptedGrantList.Count; i < count; i++) { @@ -92,15 +92,7 @@ private void DecryptEncryptedGrants(XmlNodeList encryptedGrantList, IRelDecrypto if (streamReader != null) streamReader.Close(); } - - encryptionMethodObj = null; - keyInfoObj = null; - cipherDataObj = null; } - - encryptionMethod = null; - keyInfo = null; - cipherData = null; } } @@ -143,9 +135,9 @@ public override void LoadInput(object obj) _namespaceManager.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); _namespaceManager.AddNamespace("r", NamespaceUriCore); - XmlElement currentIssuerContext = null; - XmlElement currentLicenseContext = null; - XmlNode signatureNode = null; + XmlElement currentIssuerContext; + XmlElement currentLicenseContext; + XmlNode signatureNode; // Get the nearest issuer node currentIssuerContext = Context.SelectSingleNode("ancestor-or-self::r:issuer[1]", _namespaceManager) as XmlElement; diff --git a/src/libraries/System.Security.Cryptography/ref/System.Security.Cryptography.cs b/src/libraries/System.Security.Cryptography/ref/System.Security.Cryptography.cs index 649f897e50af5..be3a8b7bb3b0b 100644 --- a/src/libraries/System.Security.Cryptography/ref/System.Security.Cryptography.cs +++ b/src/libraries/System.Security.Cryptography/ref/System.Security.Cryptography.cs @@ -672,6 +672,8 @@ public override void Initialize() { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public partial class HMACMD5 : System.Security.Cryptography.HMAC { + public const int HashSizeInBits = 128; + public const int HashSizeInBytes = 16; public HMACMD5() { } public HMACMD5(byte[] key) { } public override byte[] Key { get { throw null; } set { } } @@ -689,6 +691,8 @@ public override void Initialize() { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public partial class HMACSHA1 : System.Security.Cryptography.HMAC { + public const int HashSizeInBits = 160; + public const int HashSizeInBytes = 20; public HMACSHA1() { } public HMACSHA1(byte[] key) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] @@ -709,6 +713,8 @@ public override void Initialize() { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public partial class HMACSHA256 : System.Security.Cryptography.HMAC { + public const int HashSizeInBits = 256; + public const int HashSizeInBytes = 32; public HMACSHA256() { } public HMACSHA256(byte[] key) { } public override byte[] Key { get { throw null; } set { } } @@ -726,6 +732,8 @@ public override void Initialize() { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public partial class HMACSHA384 : System.Security.Cryptography.HMAC { + public const int HashSizeInBits = 384; + public const int HashSizeInBytes = 48; public HMACSHA384() { } public HMACSHA384(byte[] key) { } public override byte[] Key { get { throw null; } set { } } @@ -745,6 +753,8 @@ public override void Initialize() { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public partial class HMACSHA512 : System.Security.Cryptography.HMAC { + public const int HashSizeInBits = 512; + public const int HashSizeInBytes = 64; public HMACSHA512() { } public HMACSHA512(byte[] key) { } public override byte[] Key { get { throw null; } set { } } @@ -817,6 +827,8 @@ protected MaskGenerationMethod() { } [System.Runtime.Versioning.UnsupportedOSPlatformAttribute("browser")] public abstract partial class MD5 : System.Security.Cryptography.HashAlgorithm { + public const int HashSizeInBits = 128; + public const int HashSizeInBytes = 16; protected MD5() { } public static new System.Security.Cryptography.MD5 Create() { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("The default algorithm implementations might be removed, use strong type references like 'RSA.Create()' instead.")] @@ -1178,6 +1190,8 @@ public enum RSASignaturePaddingMode } public abstract partial class SHA1 : System.Security.Cryptography.HashAlgorithm { + public const int HashSizeInBits = 160; + public const int HashSizeInBytes = 20; protected SHA1() { } public static new System.Security.Cryptography.SHA1 Create() { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("The default algorithm implementations might be removed, use strong type references like 'RSA.Create()' instead.")] @@ -1201,6 +1215,8 @@ public sealed override void Initialize() { } } public abstract partial class SHA256 : System.Security.Cryptography.HashAlgorithm { + public const int HashSizeInBits = 256; + public const int HashSizeInBytes = 32; protected SHA256() { } public static new System.Security.Cryptography.SHA256 Create() { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("The default algorithm implementations might be removed, use strong type references like 'RSA.Create()' instead.")] @@ -1224,6 +1240,8 @@ public sealed override void Initialize() { } } public abstract partial class SHA384 : System.Security.Cryptography.HashAlgorithm { + public const int HashSizeInBits = 384; + public const int HashSizeInBytes = 48; protected SHA384() { } public static new System.Security.Cryptography.SHA384 Create() { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("The default algorithm implementations might be removed, use strong type references like 'RSA.Create()' instead.")] @@ -1247,6 +1265,8 @@ public sealed override void Initialize() { } } public abstract partial class SHA512 : System.Security.Cryptography.HashAlgorithm { + public const int HashSizeInBits = 512; + public const int HashSizeInBytes = 64; protected SHA512() { } public static new System.Security.Cryptography.SHA512 Create() { throw null; } [System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("The default algorithm implementations might be removed, use strong type references like 'RSA.Create()' instead.")] diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs index e0abfac53baaf..e3cb8b85b3bda 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoStream.cs @@ -717,7 +717,6 @@ private async Task CopyToAsyncInternal(Stream destination, int bufferSize, Cance pinHandle.Free(); } ArrayPool.Shared.Return(rentedBuffer); - rentedBuffer = null; } private void CheckCopyToArguments(Stream destination, int bufferSize) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECCngKey.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECCngKey.cs index 19a678d5c1587..9da73eeb398a3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECCngKey.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ECCngKey.cs @@ -112,7 +112,7 @@ internal void GenerateKey(ECCurve curve) } string algorithm; - int keySize = 0; + int keySize; if (curve.IsNamed) { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACMD5.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACMD5.cs index c66fcaab601cf..97067a63b3f93 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACMD5.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACMD5.cs @@ -15,8 +15,15 @@ namespace System.Security.Cryptography [UnsupportedOSPlatform("browser")] public class HMACMD5 : HMAC { - private const int HmacSizeBits = 128; - private const int HmacSizeBytes = HmacSizeBits / 8; + /// + /// The hash size produced by the HMAC MD5 algorithm, in bits. + /// + public const int HashSizeInBits = 128; + + /// + /// The hash size produced by the HMAC MD5 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; public HMACMD5() : this(RandomNumberGenerator.GetBytes(BlockSize)) @@ -37,7 +44,7 @@ public HMACMD5(byte[] key) // we just want to be explicit in all HMAC extended classes BlockSizeValue = BlockSize; HashSizeValue = _hMacCommon.HashSizeInBits; - Debug.Assert(HashSizeValue == HmacSizeBits); + Debug.Assert(HashSizeValue == HashSizeInBits); } public override byte[] Key @@ -99,7 +106,7 @@ public static byte[] HashData(byte[] key, byte[] source) /// The HMAC of the data. public static byte[] HashData(ReadOnlySpan key, ReadOnlySpan source) { - byte[] buffer = new byte[HmacSizeBytes]; + byte[] buffer = new byte[HashSizeInBytes]; int written = HashData(key, source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -143,14 +150,14 @@ public static int HashData(ReadOnlySpan key, ReadOnlySpan source, Sp /// public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HmacSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.MacData(HashAlgorithmNames.MD5, key, source, destination); - Debug.Assert(bytesWritten == HmacSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA1.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA1.cs index 424cec12e8313..006898d72c6ac 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA1.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA1.cs @@ -17,8 +17,15 @@ namespace System.Security.Cryptography [UnsupportedOSPlatform("browser")] public class HMACSHA1 : HMAC { - private const int HmacSizeBits = 160; - private const int HmacSizeBytes = HmacSizeBits / 8; + /// + /// The hash size produced by the HMAC SHA1 algorithm, in bits. + /// + public const int HashSizeInBits = 160; + + /// + /// The hash size produced by the HMAC SHA1 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; public HMACSHA1() : this(RandomNumberGenerator.GetBytes(BlockSize)) @@ -39,7 +46,7 @@ public HMACSHA1(byte[] key) // we just want to be explicit in all HMAC extended classes BlockSizeValue = BlockSize; HashSizeValue = _hMacCommon.HashSizeInBits; - Debug.Assert(HashSizeValue == HmacSizeBits); + Debug.Assert(HashSizeValue == HashSizeInBits); } [EditorBrowsable(EditorBrowsableState.Never)] @@ -108,7 +115,7 @@ public static byte[] HashData(byte[] key, byte[] source) /// The HMAC of the data. public static byte[] HashData(ReadOnlySpan key, ReadOnlySpan source) { - byte[] buffer = new byte[HmacSizeBytes]; + byte[] buffer = new byte[HashSizeInBytes]; int written = HashData(key, source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -152,14 +159,14 @@ public static int HashData(ReadOnlySpan key, ReadOnlySpan source, Sp /// public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HmacSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.MacData(HashAlgorithmNames.SHA1, key, source, destination); - Debug.Assert(bytesWritten == HmacSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA256.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA256.cs index 598c4c2a6ffa3..0cb3ff2ab423d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA256.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA256.cs @@ -16,8 +16,15 @@ namespace System.Security.Cryptography [UnsupportedOSPlatform("browser")] public class HMACSHA256 : HMAC { - private const int HmacSizeBits = 256; - private const int HmacSizeBytes = HmacSizeBits / 8; + /// + /// The hash size produced by the HMAC SHA256 algorithm, in bits. + /// + public const int HashSizeInBits = 256; + + /// + /// The hash size produced by the HMAC SHA256 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; public HMACSHA256() : this(RandomNumberGenerator.GetBytes(BlockSize)) @@ -38,7 +45,7 @@ public HMACSHA256(byte[] key) // we just want to be explicit in all HMAC extended classes BlockSizeValue = BlockSize; HashSizeValue = _hMacCommon.HashSizeInBits; - Debug.Assert(HashSizeValue == HmacSizeBits); + Debug.Assert(HashSizeValue == HashSizeInBits); } public override byte[] Key @@ -100,7 +107,7 @@ public static byte[] HashData(byte[] key, byte[] source) /// The HMAC of the data. public static byte[] HashData(ReadOnlySpan key, ReadOnlySpan source) { - byte[] buffer = new byte[HmacSizeBytes]; + byte[] buffer = new byte[HashSizeInBytes]; int written = HashData(key, source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -144,14 +151,14 @@ public static int HashData(ReadOnlySpan key, ReadOnlySpan source, Sp /// public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HmacSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.MacData(HashAlgorithmNames.SHA256, key, source, destination); - Debug.Assert(bytesWritten == HmacSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA384.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA384.cs index b5b5ea33a9e99..db9781f1fea2b 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA384.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA384.cs @@ -17,8 +17,15 @@ namespace System.Security.Cryptography [UnsupportedOSPlatform("browser")] public class HMACSHA384 : HMAC { - private const int HmacSizeBits = 384; - private const int HmacSizeBytes = HmacSizeBits / 8; + /// + /// The hash size produced by the HMAC SHA384 algorithm, in bits. + /// + public const int HashSizeInBits = 384; + + /// + /// The hash size produced by the HMAC SHA384 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; public HMACSHA384() : this(RandomNumberGenerator.GetBytes(BlockSize)) @@ -38,7 +45,7 @@ public HMACSHA384(byte[] key) // change the default value of BlockSizeValue to 128 instead of 64 BlockSizeValue = BlockSize; HashSizeValue = _hMacCommon.HashSizeInBits; - Debug.Assert(HashSizeValue == HmacSizeBits); + Debug.Assert(HashSizeValue == HashSizeInBits); } [Obsolete(Obsoletions.ProduceLegacyHmacValuesMessage, DiagnosticId = Obsoletions.ProduceLegacyHmacValuesDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] @@ -118,7 +125,7 @@ public static byte[] HashData(byte[] key, byte[] source) /// The HMAC of the data. public static byte[] HashData(ReadOnlySpan key, ReadOnlySpan source) { - byte[] buffer = new byte[HmacSizeBytes]; + byte[] buffer = new byte[HashSizeInBytes]; int written = HashData(key, source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -162,14 +169,14 @@ public static int HashData(ReadOnlySpan key, ReadOnlySpan source, Sp /// public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HmacSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.MacData(HashAlgorithmNames.SHA384, key, source, destination); - Debug.Assert(bytesWritten == HmacSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA512.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA512.cs index dc1ea8d688b71..ee743669edf8a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA512.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/HMACSHA512.cs @@ -17,8 +17,15 @@ namespace System.Security.Cryptography [UnsupportedOSPlatform("browser")] public class HMACSHA512 : HMAC { - private const int HmacSizeBits = 512; - private const int HmacSizeBytes = HmacSizeBits / 8; + /// + /// The hash size produced by the HMAC SHA512 algorithm, in bits. + /// + public const int HashSizeInBits = 512; + + /// + /// The hash size produced by the HMAC SHA512 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; public HMACSHA512() : this(RandomNumberGenerator.GetBytes(BlockSize)) @@ -115,7 +122,7 @@ public static byte[] HashData(byte[] key, byte[] source) /// The HMAC of the data. public static byte[] HashData(ReadOnlySpan key, ReadOnlySpan source) { - byte[] buffer = new byte[HmacSizeBytes]; + byte[] buffer = new byte[HashSizeInBytes]; int written = HashData(key, source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -159,14 +166,14 @@ public static int HashData(ReadOnlySpan key, ReadOnlySpan source, Sp /// public static bool TryHashData(ReadOnlySpan key, ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HmacSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.MacData(HashAlgorithmNames.SHA512, key, source, destination); - Debug.Assert(bytesWritten == HmacSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/MD5.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/MD5.cs index e10d36adf225d..ce70b333089bc 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/MD5.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/MD5.cs @@ -17,12 +17,19 @@ namespace System.Security.Cryptography [UnsupportedOSPlatform("browser")] public abstract class MD5 : HashAlgorithm { - private const int HashSizeBits = 128; - private const int HashSizeBytes = HashSizeBits / 8; + /// + /// The hash size produced by the MD5 algorithm, in bits. + /// + public const int HashSizeInBits = 128; + + /// + /// The hash size produced by the MD5 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; protected MD5() { - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public static new MD5 Create() => new Implementation(); @@ -53,7 +60,7 @@ public static byte[] HashData(byte[] source) /// The hash of the data. public static byte[] HashData(ReadOnlySpan source) { - byte[] buffer = GC.AllocateUninitializedArray(HashSizeBytes); + byte[] buffer = GC.AllocateUninitializedArray(HashSizeInBytes); int written = HashData(source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -93,14 +100,14 @@ public static int HashData(ReadOnlySpan source, Span destination) /// public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HashSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.HashData(HashAlgorithmNames.MD5, source, destination); - Debug.Assert(bytesWritten == HashSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PemEncoding.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PemEncoding.cs index e350d379f07e2..a253083a7fa17 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PemEncoding.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/PemEncoding.cs @@ -477,7 +477,6 @@ static int WriteBase64(ReadOnlySpan bytes, Span dest, int offset) { charsWritten += WriteBase64(remainingData, destination, charsWritten); charsWritten += Write(NewLine, destination, charsWritten); - remainingData = default; } charsWritten += Write(PostEBPrefix, destination, charsWritten); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs index 5e85bab4a4f3d..79cc9ecd83b64 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RC2Implementation.cs @@ -61,7 +61,7 @@ private ICryptoTransform CreateTransform(byte[] rgbKey, byte[]? rgbIV, bool encr if (rgbKey == null) throw new ArgumentNullException(nameof(rgbKey)); - if (!ValidKeySize(rgbKey.Length, out int keySize)) + if (!ValidKeySize(rgbKey.Length)) throw new ArgumentException(SR.Cryptography_InvalidKeySize, nameof(rgbKey)); if (rgbIV != null) @@ -86,7 +86,7 @@ protected override bool TryDecryptEcbCore( PaddingMode paddingMode, out int bytesWritten) { - if (!ValidKeySize(Key.Length, out int keySize)) + if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); @@ -112,7 +112,7 @@ protected override bool TryEncryptEcbCore( PaddingMode paddingMode, out int bytesWritten) { - if (!ValidKeySize(Key.Length, out int keySize)) + if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); @@ -139,7 +139,7 @@ protected override bool TryEncryptCbcCore( PaddingMode paddingMode, out int bytesWritten) { - if (!ValidKeySize(Key.Length, out int keySize)) + if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); @@ -166,7 +166,7 @@ protected override bool TryDecryptCbcCore( PaddingMode paddingMode, out int bytesWritten) { - if (!ValidKeySize(Key.Length, out int keySize)) + if (!ValidKeySize(Key.Length)) throw new InvalidOperationException(SR.Cryptography_InvalidKeySize); Debug.Assert(EffectiveKeySize == KeySize); @@ -219,15 +219,14 @@ private int GetPaddingSize() return BlockSize / BitsPerByte; } - private bool ValidKeySize(int keySizeBytes, out int keySizeBits) + private new bool ValidKeySize(int keySizeBytes) { if (keySizeBytes > (int.MaxValue / BitsPerByte)) { - keySizeBits = 0; return false; } - keySizeBits = keySizeBytes << 3; + int keySizeBits = keySizeBytes << 3; return keySizeBits.IsLegalSize(LegalKeySizes); } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA1.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA1.cs index e11d49619678b..0a66bc18b2854 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA1.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA1.cs @@ -15,12 +15,19 @@ namespace System.Security.Cryptography public abstract class SHA1 : HashAlgorithm { - private const int HashSizeBits = 160; - private const int HashSizeBytes = HashSizeBits / 8; + /// + /// The hash size produced by the SHA1 algorithm, in bits. + /// + public const int HashSizeInBits = 160; + + /// + /// The hash size produced by the SHA1 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; protected SHA1() { - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } [SuppressMessage("Microsoft.Security", "CA5350", Justification = "This is the implementaton of SHA1")] @@ -52,7 +59,7 @@ public static byte[] HashData(byte[] source) /// The hash of the data. public static byte[] HashData(ReadOnlySpan source) { - byte[] buffer = GC.AllocateUninitializedArray(HashSizeBytes); + byte[] buffer = GC.AllocateUninitializedArray(HashSizeInBytes); int written = HashData(source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -92,14 +99,14 @@ public static int HashData(ReadOnlySpan source, Span destination) /// public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HashSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.HashData(HashAlgorithmNames.SHA1, source, destination); - Debug.Assert(bytesWritten == HashSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA256.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA256.cs index 1b1684c86bbe7..da16eb8606430 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA256.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA256.cs @@ -15,12 +15,19 @@ namespace System.Security.Cryptography public abstract class SHA256 : HashAlgorithm { - private const int HashSizeBits = 256; - private const int HashSizeBytes = HashSizeBits / 8; + /// + /// The hash size produced by the SHA256 algorithm, in bits. + /// + public const int HashSizeInBits = 256; + + /// + /// The hash size produced by the SHA256 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; protected SHA256() { - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public static new SHA256 Create() => new Implementation(); @@ -51,7 +58,7 @@ public static byte[] HashData(byte[] source) /// The hash of the data. public static byte[] HashData(ReadOnlySpan source) { - byte[] buffer = GC.AllocateUninitializedArray(HashSizeBytes); + byte[] buffer = GC.AllocateUninitializedArray(HashSizeInBytes); int written = HashData(source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -92,14 +99,14 @@ public static int HashData(ReadOnlySpan source, Span destination) /// public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HashSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.HashData(HashAlgorithmNames.SHA256, source, destination); - Debug.Assert(bytesWritten == HashSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA384.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA384.cs index 0cf032895d5bf..1ed1b72c04f61 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA384.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA384.cs @@ -15,12 +15,19 @@ namespace System.Security.Cryptography public abstract class SHA384 : HashAlgorithm { - private const int HashSizeBits = 384; - private const int HashSizeBytes = HashSizeBits / 8; + /// + /// The hash size produced by the SHA384 algorithm, in bits. + /// + public const int HashSizeInBits = 384; + + /// + /// The hash size produced by the SHA384 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; protected SHA384() { - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public static new SHA384 Create() => new Implementation(); @@ -51,7 +58,7 @@ public static byte[] HashData(byte[] source) /// The hash of the data. public static byte[] HashData(ReadOnlySpan source) { - byte[] buffer = GC.AllocateUninitializedArray(HashSizeBytes); + byte[] buffer = GC.AllocateUninitializedArray(HashSizeInBytes); int written = HashData(source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -91,14 +98,14 @@ public static int HashData(ReadOnlySpan source, Span destination) /// public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HashSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.HashData(HashAlgorithmNames.SHA384, source, destination); - Debug.Assert(bytesWritten == HashSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA512.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA512.cs index d50f33ebe801e..5c6e52ab9cd9a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA512.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/SHA512.cs @@ -15,12 +15,19 @@ namespace System.Security.Cryptography public abstract class SHA512 : HashAlgorithm { - private const int HashSizeBits = 512; - private const int HashSizeBytes = HashSizeBits / 8; + /// + /// The hash size produced by the SHA512 algorithm, in bits. + /// + public const int HashSizeInBits = 512; + + /// + /// The hash size produced by the SHA512 algorithm, in bytes. + /// + public const int HashSizeInBytes = HashSizeInBits / 8; protected SHA512() { - HashSizeValue = HashSizeBits; + HashSizeValue = HashSizeInBits; } public static new SHA512 Create() => new Implementation(); @@ -51,7 +58,7 @@ public static byte[] HashData(byte[] source) /// The hash of the data. public static byte[] HashData(ReadOnlySpan source) { - byte[] buffer = GC.AllocateUninitializedArray(HashSizeBytes); + byte[] buffer = GC.AllocateUninitializedArray(HashSizeInBytes); int written = HashData(source, buffer.AsSpan()); Debug.Assert(written == buffer.Length); @@ -91,14 +98,14 @@ public static int HashData(ReadOnlySpan source, Span destination) /// public static bool TryHashData(ReadOnlySpan source, Span destination, out int bytesWritten) { - if (destination.Length < HashSizeBytes) + if (destination.Length < HashSizeInBytes) { bytesWritten = 0; return false; } bytesWritten = HashProviderDispenser.OneShotHashProvider.HashData(HashAlgorithmNames.SHA512, source, destination); - Debug.Assert(bytesWritten == HashSizeBytes); + Debug.Assert(bytesWritten == HashSizeInBytes); return true; } diff --git a/src/libraries/System.Security.Cryptography/tests/AsnEncodedDataTests.cs b/src/libraries/System.Security.Cryptography/tests/AsnEncodedDataTests.cs index a72d6814fea80..0e5ba9cb08806 100644 --- a/src/libraries/System.Security.Cryptography/tests/AsnEncodedDataTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/AsnEncodedDataTests.cs @@ -101,11 +101,12 @@ public static void TestSubjectAlternativeName_Unix() sanExtension); string s = asnData.Format(false); + bool isOpenSsl3 = PlatformDetection.IsOpenSsl3; string expected = string.Join( ", ", // Choice[0]: OtherName - "othername:", + isOpenSsl3 ? "othername: UPN::subjectupn1@example.org" : "othername:", // Choice[1]: Rfc822Name (EmailAddress) "email:sanemail1@example.org", // Choice[2]: DnsName @@ -123,7 +124,7 @@ public static void TestSubjectAlternativeName_Unix() // Choice[7]: IPAddress (IPv6) "IP Address:2001:DB8:AC10:FE01:0:0:0:0", // Choice[7]: IPAddress (unknown type) - "IP Address:", + isOpenSsl3 ? "IP Address:" : "IP Address:", // Choice[7]: IPAddress (IPv4, longer string) "IP Address:255.255.255.255", // Choice[7]: IPAddress (IPv4, medium string) diff --git a/src/libraries/System.Security.Cryptography/tests/HmacMD5Tests.cs b/src/libraries/System.Security.Cryptography/tests/HmacMD5Tests.cs index 5890252e8dfa8..99ad3814d0a37 100644 --- a/src/libraries/System.Security.Cryptography/tests/HmacMD5Tests.cs +++ b/src/libraries/System.Security.Cryptography/tests/HmacMD5Tests.cs @@ -39,7 +39,7 @@ public HmacMD5Tests() } protected override int BlockSize => 64; - protected override int MacSize => 16; + protected override int MacSize => HMACMD5.HashSizeInBytes; protected override HMAC Create() => new HMACMD5(); protected override HashAlgorithm CreateHashAlgorithm() => MD5.Create(); diff --git a/src/libraries/System.Security.Cryptography/tests/HmacSha1Tests.cs b/src/libraries/System.Security.Cryptography/tests/HmacSha1Tests.cs index dadae08fea188..61b395d572535 100644 --- a/src/libraries/System.Security.Cryptography/tests/HmacSha1Tests.cs +++ b/src/libraries/System.Security.Cryptography/tests/HmacSha1Tests.cs @@ -39,7 +39,7 @@ public HmacSha1Tests() } protected override int BlockSize => 64; - protected override int MacSize => 20; + protected override int MacSize => HMACSHA1.HashSizeInBytes; protected override HMAC Create() => new HMACSHA1(); protected override HashAlgorithm CreateHashAlgorithm() => SHA1.Create(); diff --git a/src/libraries/System.Security.Cryptography/tests/HmacSha256Tests.cs b/src/libraries/System.Security.Cryptography/tests/HmacSha256Tests.cs index 303c248d5ee3d..f2f1784404675 100644 --- a/src/libraries/System.Security.Cryptography/tests/HmacSha256Tests.cs +++ b/src/libraries/System.Security.Cryptography/tests/HmacSha256Tests.cs @@ -10,7 +10,7 @@ namespace System.Security.Cryptography.Tests public class HmacSha256Tests : Rfc4231HmacTests { protected override int BlockSize => 64; - protected override int MacSize => 32; + protected override int MacSize => HMACSHA256.HashSizeInBytes; protected override HMAC Create() => new HMACSHA256(); protected override HashAlgorithm CreateHashAlgorithm() => SHA256.Create(); diff --git a/src/libraries/System.Security.Cryptography/tests/HmacSha384Tests.cs b/src/libraries/System.Security.Cryptography/tests/HmacSha384Tests.cs index abaeab4dbc6fe..dbff8c26c50bc 100644 --- a/src/libraries/System.Security.Cryptography/tests/HmacSha384Tests.cs +++ b/src/libraries/System.Security.Cryptography/tests/HmacSha384Tests.cs @@ -10,7 +10,7 @@ namespace System.Security.Cryptography.Tests public class HmacSha384Tests : Rfc4231HmacTests { protected override int BlockSize => 128; - protected override int MacSize => 48; + protected override int MacSize => HMACSHA384.HashSizeInBytes; protected override HMAC Create() => new HMACSHA384(); protected override HashAlgorithm CreateHashAlgorithm() => SHA384.Create(); diff --git a/src/libraries/System.Security.Cryptography/tests/HmacSha512Tests.cs b/src/libraries/System.Security.Cryptography/tests/HmacSha512Tests.cs index fa83bd45e2183..7bf5ed6652873 100644 --- a/src/libraries/System.Security.Cryptography/tests/HmacSha512Tests.cs +++ b/src/libraries/System.Security.Cryptography/tests/HmacSha512Tests.cs @@ -10,7 +10,7 @@ namespace System.Security.Cryptography.Tests public class HmacSha512Tests : Rfc4231HmacTests { protected override int BlockSize => 128; - protected override int MacSize => 64; + protected override int MacSize => HMACSHA512.HashSizeInBytes; protected override HMAC Create() => new HMACSHA512(); protected override HashAlgorithm CreateHashAlgorithm() => SHA512.Create(); diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs index e627638c6fe09..0dd3bb702e267 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs @@ -244,13 +244,12 @@ private static SafeAccessTokenHandle DuplicateAccessToken(IntPtr accessToken) } // Find out if the specified token is a valid. - uint dwLength = sizeof(uint); if (!Interop.Advapi32.GetTokenInformation( accessToken, (uint)TokenInformationClass.TokenType, IntPtr.Zero, 0, - out dwLength) && + out _) && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INVALID_HANDLE) { throw new ArgumentException(SR.Argument_InvalidImpersonationToken); @@ -397,7 +396,7 @@ public TokenImpersonationLevel ImpersonationLevel // which is ok. if (!_impersonationLevelInitialized) { - TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None; + TokenImpersonationLevel impersonationLevel; // If this is an anonymous identity if (_safeTokenHandle.IsInvalid) { @@ -884,12 +883,11 @@ private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle private static SafeLocalAllocHandle? GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, bool nullOnInvalidParam = false) { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; - uint dwLength = (uint)sizeof(uint); - bool result = Interop.Advapi32.GetTokenInformation(tokenHandle, + Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, 0, - out dwLength); + out uint dwLength); int dwErrorCode = Marshal.GetLastWin32Error(); switch (dwErrorCode) { @@ -899,11 +897,11 @@ private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle safeLocalAllocHandle.Dispose(); safeLocalAllocHandle = SafeLocalAllocHandle.LocalAlloc(checked((int)dwLength)); - result = Interop.Advapi32.GetTokenInformation(tokenHandle, + bool result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, dwLength, - out dwLength); + out _); if (!result) throw new SecurityException(new Win32Exception().Message); break; diff --git a/src/libraries/System.Speech/src/System.Speech.csproj b/src/libraries/System.Speech/src/System.Speech.csproj index 660dae3003766..bf696506ec7ee 100644 --- a/src/libraries/System.Speech/src/System.Speech.csproj +++ b/src/libraries/System.Speech/src/System.Speech.csproj @@ -5,7 +5,7 @@ - $(NoWarn);CS0649;SA1129;CA1846;CA1847 + $(NoWarn);CS0649;SA1129;CA1846;CA1847;IDE0059 annotations false true diff --git a/src/libraries/System.Text.Encodings.Web/ref/System.Text.Encodings.Web.cs b/src/libraries/System.Text.Encodings.Web/ref/System.Text.Encodings.Web.cs index f38e07bfbb2a5..72e30ff774322 100644 --- a/src/libraries/System.Text.Encodings.Web/ref/System.Text.Encodings.Web.cs +++ b/src/libraries/System.Text.Encodings.Web/ref/System.Text.Encodings.Web.cs @@ -83,6 +83,7 @@ public static partial class UnicodeRanges public static System.Text.Unicode.UnicodeRange AlphabeticPresentationForms { get { throw null; } } public static System.Text.Unicode.UnicodeRange Arabic { get { throw null; } } public static System.Text.Unicode.UnicodeRange ArabicExtendedA { get { throw null; } } + public static System.Text.Unicode.UnicodeRange ArabicExtendedB { get { throw null; } } public static System.Text.Unicode.UnicodeRange ArabicPresentationFormsA { get { throw null; } } public static System.Text.Unicode.UnicodeRange ArabicPresentationFormsB { get { throw null; } } public static System.Text.Unicode.UnicodeRange ArabicSupplement { get { throw null; } } diff --git a/src/libraries/System.Text.Encodings.Web/src/System/Text/Unicode/UnicodeRanges.generated.cs b/src/libraries/System.Text.Encodings.Web/src/System/Text/Unicode/UnicodeRanges.generated.cs index c95e2ebc71bca..5ab03229dc03d 100644 --- a/src/libraries/System.Text.Encodings.Web/src/System/Text/Unicode/UnicodeRanges.generated.cs +++ b/src/libraries/System.Text.Encodings.Web/src/System/Text/Unicode/UnicodeRanges.generated.cs @@ -190,6 +190,15 @@ public static partial class UnicodeRanges public static UnicodeRange SyriacSupplement => _u0860 ?? CreateRange(ref _u0860, first: '\u0860', last: '\u086F'); private static UnicodeRange? _u0860; + /// + /// A corresponding to the 'Arabic Extended-B' Unicode block (U+0870..U+089F). + /// + /// + /// See https://www.unicode.org/charts/PDF/U0870.pdf for the full set of characters in this block. + /// + public static UnicodeRange ArabicExtendedB => _u0870 ?? CreateRange(ref _u0870, first: '\u0870', last: '\u089F'); + private static UnicodeRange? _u0870; + /// /// A corresponding to the 'Arabic Extended-A' Unicode block (U+08A0..U+08FF). /// diff --git a/src/libraries/System.Text.Encodings.Web/tests/UnicodeRangesTests.generated.cs b/src/libraries/System.Text.Encodings.Web/tests/UnicodeRangesTests.generated.cs index fcf41b771ff10..69479ad534768 100644 --- a/src/libraries/System.Text.Encodings.Web/tests/UnicodeRangesTests.generated.cs +++ b/src/libraries/System.Text.Encodings.Web/tests/UnicodeRangesTests.generated.cs @@ -32,6 +32,7 @@ public static partial class UnicodeRangesTests new object[] { '\u0800', '\u083F', nameof(UnicodeRanges.Samaritan) }, new object[] { '\u0840', '\u085F', nameof(UnicodeRanges.Mandaic) }, new object[] { '\u0860', '\u086F', nameof(UnicodeRanges.SyriacSupplement) }, + new object[] { '\u0870', '\u089F', nameof(UnicodeRanges.ArabicExtendedB) }, new object[] { '\u08A0', '\u08FF', nameof(UnicodeRanges.ArabicExtendedA) }, new object[] { '\u0900', '\u097F', nameof(UnicodeRanges.Devanagari) }, new object[] { '\u0980', '\u09FF', nameof(UnicodeRanges.Bengali) }, diff --git a/src/libraries/System.Text.Json/Common/ReflectionExtensions.cs b/src/libraries/System.Text.Json/Common/ReflectionExtensions.cs index 09ecc45077fe0..08bd257f938c0 100644 --- a/src/libraries/System.Text.Json/Common/ReflectionExtensions.cs +++ b/src/libraries/System.Text.Json/Common/ReflectionExtensions.cs @@ -42,16 +42,12 @@ internal static partial class ReflectionExtensions public static Type? GetCompatibleGenericBaseClass( this Type type, Type baseType, - Type? objectType = null, bool sourceGenType = false) { Debug.Assert(baseType.IsGenericType); Debug.Assert(!baseType.IsInterface); Debug.Assert(baseType == baseType.GetGenericTypeDefinition()); - // Work around not being able to use typeof(object) directly during compile-time src gen type analysis. - objectType ??= typeof(object); - Type? baseTypeToCheck = type; while (baseTypeToCheck != null && baseTypeToCheck != typeof(object)) diff --git a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs index 92c60d4ace019..9590a3b90f07d 100644 --- a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs +++ b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs @@ -843,13 +843,13 @@ private TypeGenerationSpec GetOrAddTypeGenerationSpec(Type type, JsonSourceGener collectionType = CollectionType.QueueOfT; valueType = actualTypeToConvert.GetGenericArguments()[0]; } - else if ((actualTypeToConvert = type.GetCompatibleGenericBaseClass(_concurrentStackType, _objectType, sourceGenType: true)) != null) + else if ((actualTypeToConvert = type.GetCompatibleGenericBaseClass(_concurrentStackType, sourceGenType: true)) != null) { classType = ClassType.Enumerable; collectionType = CollectionType.ConcurrentStack; valueType = actualTypeToConvert.GetGenericArguments()[0]; } - else if ((actualTypeToConvert = type.GetCompatibleGenericBaseClass(_concurrentQueueType, _objectType, sourceGenType: true)) != null) + else if ((actualTypeToConvert = type.GetCompatibleGenericBaseClass(_concurrentQueueType, sourceGenType: true)) != null) { classType = ClassType.Enumerable; collectionType = CollectionType.ConcurrentQueue; @@ -1103,7 +1103,7 @@ private bool IsValidDataExtensionPropertyType(Type type) } private Type GetCompatibleGenericBaseClass(Type type, Type baseType) - => type.GetCompatibleGenericBaseClass(baseType, _objectType); + => type.GetCompatibleGenericBaseClass(baseType); private void CacheMember( PropertyGenerationSpec propGenSpec, diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs b/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs index 52804371a9af2..9ba42d2620619 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/BitStack.cs @@ -101,7 +101,7 @@ private void PushToArray(bool value) public bool Pop() { _currentDepth--; - bool inObject = false; + bool inObject; if (_currentDepth < AllocationFreeMaxDepth) { _allocationFreeContainer >>= 1; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.Date.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.Date.cs index 80d4bf1a1d3fd..9ef24e2648604 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.Date.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.Date.cs @@ -117,6 +117,12 @@ public static bool IsValidDateTimeOffsetParseLength(int length) return IsInRangeInclusive(length, JsonConstants.MinimumDateTimeParseLength, JsonConstants.MaximumEscapedDateTimeOffsetParseLength); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValidUnescapedDateTimeOffsetParseLength(int length) + { + return IsInRangeInclusive(length, JsonConstants.MinimumDateTimeParseLength, JsonConstants.MaximumDateTimeOffsetParseLength); + } + /// /// Parse the given UTF-8 as extended ISO 8601 format. /// diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/JsonPropertyDictionary.cs b/src/libraries/System.Text.Json/src/System/Text/Json/JsonPropertyDictionary.cs index 256299c8ea7e7..686fee2afec1e 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/JsonPropertyDictionary.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/JsonPropertyDictionary.cs @@ -113,7 +113,7 @@ public bool Remove(string propertyName) throw new ArgumentNullException(nameof(propertyName)); } - return TryRemoveProperty(propertyName, out T? removedValue); + return TryRemoveProperty(propertyName, out _); } public bool Contains(KeyValuePair item) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs index 13ea3fcba4436..04a64c3e44ef4 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs @@ -32,7 +32,7 @@ public JsonObject(JsonNodeOptions? options = null) : base(options) { } /// /// The properties to be added. /// Options to control the behavior. - public JsonObject(IEnumerable> properties, JsonNodeOptions? options = null) + public JsonObject(IEnumerable> properties, JsonNodeOptions? options = null) : this(options) { foreach (KeyValuePair node in properties) { @@ -64,7 +64,7 @@ public JsonObject(IEnumerable> properties, JsonN throw new InvalidOperationException(SR.Format(SR.NodeElementWrongType, nameof(JsonValueKind.Object))); } - internal JsonObject(JsonElement element, JsonNodeOptions? options = null) : base(options) + internal JsonObject(JsonElement element, JsonNodeOptions? options = null) : this(options) { Debug.Assert(element.ValueKind == JsonValueKind.Object); _jsonElement = element; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfT.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfT.cs index 07b838d48f547..2e2b1b2a2e6f4 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfT.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonValueOfT.cs @@ -61,7 +61,7 @@ public override bool TryGetValue([NotNullWhen(true)] out T value) return true; } - if (_value is JsonElement jsonElement) + if (_value is JsonElement) { return TryConvertJsonElement(out value); } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/JsonReaderHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/JsonReaderHelper.cs index b9d51eff8dae6..8d8c87781af60 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/JsonReaderHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/JsonReaderHelper.cs @@ -260,7 +260,7 @@ public static bool TryGetEscapedDateTime(ReadOnlySpan source, out DateTime sourceUnescaped = sourceUnescaped.Slice(0, written); Debug.Assert(!sourceUnescaped.IsEmpty); - if (sourceUnescaped.Length <= JsonConstants.MaximumDateTimeOffsetParseLength + if (JsonHelpers.IsValidUnescapedDateTimeOffsetParseLength(sourceUnescaped.Length) && JsonHelpers.TryParseAsISO(sourceUnescaped, out DateTime tmp)) { value = tmp; @@ -285,7 +285,7 @@ public static bool TryGetEscapedDateTimeOffset(ReadOnlySpan source, out Da sourceUnescaped = sourceUnescaped.Slice(0, written); Debug.Assert(!sourceUnescaped.IsEmpty); - if (sourceUnescaped.Length <= JsonConstants.MaximumDateTimeOffsetParseLength + if (JsonHelpers.IsValidUnescapedDateTimeOffsetParseLength(sourceUnescaped.Length) && JsonHelpers.TryParseAsISO(sourceUnescaped, out DateTimeOffset tmp)) { value = tmp; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs index 89f269bdb870a..ea4204f82ab12 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs @@ -296,7 +296,7 @@ private bool HasMoreDataMultiSegment(ExceptionResource resource) private bool GetNextSpan() { - ReadOnlyMemory memory = default; + ReadOnlyMemory memory; while (true) { Debug.Assert(!_isMultiSegment || _currentPosition.GetObject() != null); @@ -630,7 +630,7 @@ private int FindMismatch(ReadOnlySpan span, ReadOnlySpan literal) { Debug.Assert(span.Length > 0); - int indexOfFirstMismatch = 0; + int indexOfFirstMismatch; int minLength = Math.Min(span.Length, literal.Length); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs index 42e561d89b0f4..543c9fa5beac2 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs @@ -1552,7 +1552,7 @@ private ConsumeNumberResult ConsumeZero(ref ReadOnlySpan data, ref int i) { Debug.Assert(data[i] == (byte)'0'); i++; - byte nextByte = default; + byte nextByte; if (i < data.Length) { nextByte = data[i]; @@ -2314,7 +2314,7 @@ private bool SkipComment() private bool SkipSingleLineComment(ReadOnlySpan localBuffer, out int idx) { idx = FindLineSeparator(localBuffer); - int toConsume = 0; + int toConsume; if (idx != -1) { toConsume = idx; diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs index c12debeb61856..34877136b20e1 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs @@ -400,8 +400,6 @@ internal sealed override bool OnTryWrite( onSerialized.OnSerialized(); } - value = (T)obj; // unbox - return true; } diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs index e5cd6d024ee1a..a164e71c13993 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs @@ -646,6 +646,12 @@ public static void ThrowInvalidOperationException_ExpectedChar(JsonTokenType tok { throw GetInvalidOperationException("char", tokenType); } + + [DoesNotReturn] + public static void ThrowObjectDisposedException_Utf8JsonWriter() + { + throw new ObjectDisposedException(nameof(Utf8JsonWriter)); + } } internal enum ExceptionResource diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs index 084b7c65c6350..9b22c33ac7d8f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Writer/Utf8JsonWriter.cs @@ -238,7 +238,7 @@ private void CheckNotDisposed() // The conditions are ordered with stream first as that would be the most common mode if (_output == null) { - throw new ObjectDisposedException(nameof(Utf8JsonWriter)); + ThrowHelper.ThrowObjectDisposedException_Utf8JsonWriter(); } } } diff --git a/src/libraries/System.Text.Json/tests/Common/PropertyVisibilityTests.cs b/src/libraries/System.Text.Json/tests/Common/PropertyVisibilityTests.cs index 8c0f57b422a55..302923a104c28 100644 --- a/src/libraries/System.Text.Json/tests/Common/PropertyVisibilityTests.cs +++ b/src/libraries/System.Text.Json/tests/Common/PropertyVisibilityTests.cs @@ -1227,6 +1227,7 @@ public async Task JsonIgnoreAttribute_UnsupportedCollection() } [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/63802", TargetFrameworkMonikers.NetFramework)] public async Task JsonIgnoreAttribute_UnsupportedBigInteger() { string json = @"{""MyBigInteger"":1}"; diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/ContextClasses.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/ContextClasses.cs index c01499f7fef3e..75ada92a87303 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/ContextClasses.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/ContextClasses.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; -using System.Reflection; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; @@ -11,7 +10,7 @@ namespace System.Text.Json.SourceGeneration.Tests public interface ITestContext { public JsonSourceGenerationMode JsonSourceGenerationMode { get; } - public bool IsIncludeFieldsEnabled => GetType().GetCustomAttribute()?.IncludeFields ?? false; + public bool IsIncludeFieldsEnabled { get; } public JsonTypeInfo Location { get; } public JsonTypeInfo NumberTypes { get; } diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs index 7bc91507d9ad5..fd735e182d5fe 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/JsonSerializerContextTests.cs @@ -21,6 +21,7 @@ public static void VariousNestingAndVisibilityLevelsAreSupported() } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] + [ActiveIssue("https://github.com/dotnet/runtime/issues/63802", TargetFrameworkMonikers.NetFramework)] public static void Converters_AndTypeInfoCreator_NotRooted_WhenMetadataNotPresent() { RemoteExecutor.Invoke( diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MetadataAndSerializationContextTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MetadataAndSerializationContextTests.cs index 57abdf04808a0..a8eeee6f8768b 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MetadataAndSerializationContextTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MetadataAndSerializationContextTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Text.Json.Serialization; +using System.Reflection; using Xunit; namespace System.Text.Json.SourceGeneration.Tests @@ -44,6 +45,7 @@ namespace System.Text.Json.SourceGeneration.Tests internal partial class MetadataAndSerializationContext : JsonSerializerContext, ITestContext { public JsonSourceGenerationMode JsonSourceGenerationMode => JsonSourceGenerationMode.Default; + public bool IsIncludeFieldsEnabled => GetType().GetCustomAttribute()?.IncludeFields ?? false; } public sealed class MetadataAndSerializationContextTests : RealWorldContextTests diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MetadataContextTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MetadataContextTests.cs index d0c3023b41ae9..89c5035700bea 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MetadataContextTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MetadataContextTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Text.Json.Serialization; +using System.Reflection; using Xunit; namespace System.Text.Json.SourceGeneration.Tests @@ -43,6 +44,7 @@ namespace System.Text.Json.SourceGeneration.Tests internal partial class MetadataWithPerTypeAttributeContext : JsonSerializerContext, ITestContext { public JsonSourceGenerationMode JsonSourceGenerationMode => JsonSourceGenerationMode.Metadata; + public bool IsIncludeFieldsEnabled => GetType().GetCustomAttribute()?.IncludeFields ?? false; } public sealed class MetadataWithPerTypeAttributeContextTests : RealWorldContextTests @@ -127,6 +129,7 @@ public override void EnsureFastPathGeneratedAsExpected() internal partial class MetadataContext : JsonSerializerContext, ITestContext { public JsonSourceGenerationMode JsonSourceGenerationMode => JsonSourceGenerationMode.Metadata; + public bool IsIncludeFieldsEnabled => GetType().GetCustomAttribute()?.IncludeFields ?? false; } [JsonConverter(typeof(JsonStringEnumConverter))] diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MixedModeContextTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MixedModeContextTests.cs index d547551569935..51e9e23b80d7b 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MixedModeContextTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/MixedModeContextTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Text.Json.Serialization; +using System.Reflection; using Xunit; namespace System.Text.Json.SourceGeneration.Tests @@ -44,6 +45,7 @@ namespace System.Text.Json.SourceGeneration.Tests internal partial class MixedModeContext : JsonSerializerContext, ITestContext { public JsonSourceGenerationMode JsonSourceGenerationMode => JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization; + public bool IsIncludeFieldsEnabled => GetType().GetCustomAttribute()?.IncludeFields ?? false; } public sealed class MixedModeContextTests : RealWorldContextTests diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/PropertyVisibilityTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/PropertyVisibilityTests.cs index a698165e3f967..1c80d9046a7c4 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/PropertyVisibilityTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/PropertyVisibilityTests.cs @@ -249,10 +249,12 @@ public override async Task HonorJsonPropertyName_PrivateSetter() [JsonSerializable(typeof(ClassWithNewSlotAttributedDecimalProperty))] [JsonSerializable(typeof(ClassWithNewSlotDecimalProperty))] [JsonSerializable(typeof(LargeStructWithValueAndReferenceTypes))] +#if !NETFRAMEWORK [JsonSerializable(typeof(ClassWithUnsupportedBigInteger))] [JsonSerializable(typeof(WrapperForClassWithUnsupportedBigInteger))] [JsonSerializable(typeof(ClassWithIgnoredUnsupportedBigInteger))] [JsonSerializable(typeof(WrapperForClassWithIgnoredUnsupportedBigInteger))] +#endif [JsonSerializable(typeof(ClassWithThingsToIgnore))] [JsonSerializable(typeof(ClassWithMixedPropertyAccessors_PropertyAttributes))] [JsonSerializable(typeof(ClassWithPropertyPolicyConflictWhichThrows))] @@ -422,10 +424,12 @@ public override async Task JsonIgnoreCondition_WhenWritingNull_OnValueType_Fail_ [JsonSerializable(typeof(ClassWithNewSlotAttributedDecimalProperty))] [JsonSerializable(typeof(ClassWithNewSlotDecimalProperty))] [JsonSerializable(typeof(LargeStructWithValueAndReferenceTypes))] +#if !NETFRAMEWORK [JsonSerializable(typeof(ClassWithUnsupportedBigInteger))] [JsonSerializable(typeof(WrapperForClassWithUnsupportedBigInteger))] [JsonSerializable(typeof(ClassWithIgnoredUnsupportedBigInteger))] [JsonSerializable(typeof(WrapperForClassWithIgnoredUnsupportedBigInteger))] +#endif [JsonSerializable(typeof(ClassWithThingsToIgnore))] [JsonSerializable(typeof(ClassWithMixedPropertyAccessors_PropertyAttributes))] [JsonSerializable(typeof(ClassWithPropertyPolicyConflictWhichThrows))] diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/SerializationContextTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/SerializationContextTests.cs index b51ba070be188..f955070f74cb5 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/SerializationContextTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/SerializationContextTests.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Text.Json.Serialization; +using System.Reflection; using Xunit; namespace System.Text.Json.SourceGeneration.Tests @@ -44,6 +45,7 @@ namespace System.Text.Json.SourceGeneration.Tests internal partial class SerializationContext : JsonSerializerContext, ITestContext { public JsonSourceGenerationMode JsonSourceGenerationMode => JsonSourceGenerationMode.Serialization; + public bool IsIncludeFieldsEnabled => GetType().GetCustomAttribute()?.IncludeFields ?? false; } [JsonSerializable(typeof(Location), GenerationMode = JsonSourceGenerationMode.Serialization)] @@ -83,6 +85,7 @@ internal partial class SerializationContext : JsonSerializerContext, ITestContex internal partial class SerializationWithPerTypeAttributeContext : JsonSerializerContext, ITestContext { public JsonSourceGenerationMode JsonSourceGenerationMode => JsonSourceGenerationMode.Serialization; + public bool IsIncludeFieldsEnabled => GetType().GetCustomAttribute()?.IncludeFields ?? false; } [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, IncludeFields = true)] @@ -123,6 +126,7 @@ internal partial class SerializationWithPerTypeAttributeContext : JsonSerializer internal partial class SerializationContextWithCamelCase : JsonSerializerContext, ITestContext { public JsonSourceGenerationMode JsonSourceGenerationMode => JsonSourceGenerationMode.Serialization; + public bool IsIncludeFieldsEnabled => GetType().GetCustomAttribute()?.IncludeFields ?? false; } public class SerializationContextTests : RealWorldContextTests diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/System.Text.Json.SourceGeneration.Tests.targets b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/System.Text.Json.SourceGeneration.Tests.targets index 2f977168e8043..16f8d544794b8 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/System.Text.Json.SourceGeneration.Tests.targets +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/System.Text.Json.SourceGeneration.Tests.targets @@ -1,6 +1,6 @@ - $(NetCoreAppCurrent);$(NetFrameworkCurrent) + $(NetCoreAppCurrent);$(NetFrameworkMinimum) true true @@ -86,6 +86,17 @@ + + + + + + + + + + + diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/CompilationHelper.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/CompilationHelper.cs index 485a79cd333cd..4381422afb7f4 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/CompilationHelper.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/CompilationHelper.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; @@ -31,6 +32,7 @@ public static Compilation CreateCompilation( // Bypass System.Runtime error. Assembly systemRuntimeAssembly = Assembly.Load("System.Runtime, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); Assembly systemCollectionsAssembly = Assembly.Load("System.Collections, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); + // Needed on netfx string systemRuntimeAssemblyPath = systemRuntimeAssembly.Location; string systemCollectionsAssemblyPath = systemCollectionsAssembly.Location; @@ -38,9 +40,11 @@ public static Compilation CreateCompilation( MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(Attribute).Assembly.Location), MetadataReference.CreateFromFile(typeof(Type).Assembly.Location), - MetadataReference.CreateFromFile(typeof(KeyValuePair).Assembly.Location), + MetadataReference.CreateFromFile(typeof(KeyValuePair<,>).Assembly.Location), MetadataReference.CreateFromFile(typeof(ContractNamespaceAttribute).Assembly.Location), MetadataReference.CreateFromFile(typeof(JavaScriptEncoder).Assembly.Location), + MetadataReference.CreateFromFile(typeof(GeneratedCodeAttribute).Assembly.Location), + MetadataReference.CreateFromFile(typeof(ReadOnlySpan<>).Assembly.Location), MetadataReference.CreateFromFile(systemRuntimeAssemblyPath), MetadataReference.CreateFromFile(systemCollectionsAssemblyPath), }; diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/JsonSourceGeneratorTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/JsonSourceGeneratorTests.cs index f8c0a34e57c80..f1d5b1973fd6c 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/JsonSourceGeneratorTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/JsonSourceGeneratorTests.cs @@ -450,6 +450,7 @@ public void UsePrivates() } [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/63802", TargetFrameworkMonikers.NetFramework)] public void Record() { // Compile the referenced assembly first. @@ -511,6 +512,7 @@ public record AppRecord(int Id) } [Fact] + [ActiveIssue("https://github.com/dotnet/runtime/issues/63802", TargetFrameworkMonikers.NetFramework)] public void RecordInExternalAssembly() { // Compile the referenced assembly first. diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/System.Text.Json.SourceGeneration.Unit.Tests.targets b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/System.Text.Json.SourceGeneration.Unit.Tests.targets index da4a8b8d65997..08f362de05e7a 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/System.Text.Json.SourceGeneration.Unit.Tests.targets +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Unit.Tests/System.Text.Json.SourceGeneration.Unit.Tests.targets @@ -1,6 +1,6 @@ - $(NetCoreAppCurrent);$(NetFrameworkCurrent) + $(NetCoreAppCurrent);$(NetFrameworkMinimum) true @@ -17,6 +17,10 @@ + + + + diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonDocumentTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonDocumentTests.cs index 5facb8cc71821..e12d31504cfe2 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonDocumentTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonDocumentTests.cs @@ -2047,6 +2047,31 @@ void assertOdd(JsonElement elem) } } + [Theory] + [InlineData(">>")] + [InlineData(">>>")] + [InlineData(">>a")] + [InlineData(">a>")] + public static void TryGetDateTimeAndOffset_InvalidPropertyValue(string testData) + { + string jsonString = JsonSerializer.Serialize(new { DateTimeProperty = testData }); + + byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); + + using (JsonDocument doc = JsonDocument.Parse(dataUtf8, default)) + { + JsonElement root = doc.RootElement; + + Assert.False(root.GetProperty("DateTimeProperty").TryGetDateTime(out DateTime datetimeValue)); + Assert.Equal(default, datetimeValue); + Assert.Throws(() => root.GetProperty("DateTimeProperty").GetDateTime()); + + Assert.False(root.GetProperty("DateTimeProperty").TryGetDateTimeOffset(out DateTimeOffset datetimeOffsetValue)); + Assert.Equal(default, datetimeOffsetValue); + Assert.Throws(() => root.GetProperty("DateTimeProperty").GetDateTimeOffset()); + } + } + [Theory] [InlineData("")] [InlineData(" ")] diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/JsonObjectTests.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/JsonObjectTests.cs index 1f152606a7e7f..f6a22aff6e819 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/JsonObjectTests.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/JsonNode/JsonObjectTests.cs @@ -920,5 +920,41 @@ public static void ChangeCollectionWhileEnumeratingFails(JsonObject jObject, int }); Assert.Equal(1, index); } + + [Fact] + public static void TestJsonNodeOptionsSet() + { + var options = new JsonNodeOptions() + { + PropertyNameCaseInsensitive = true + }; + + // Ctor that takes just options + var obj1 = new JsonObject(options); + obj1["Hello"] = "World"; + + // Ctor that takes props IEnumerable + options + IEnumerable> props = new List> + { + new KeyValuePair("Hello", "World") + }; + var obj2 = new JsonObject(props, options); + + // Create method + using JsonDocument doc = JsonDocument.Parse(@"{""Hello"":""World""}"); + var obj3 = JsonObject.Create(doc.RootElement, options); + + Test(obj1); + Test(obj2); + Test(obj3); + + static void Test(JsonObject jObject) + { + Assert.NotNull(jObject.Options); + Assert.True(jObject.Options.Value.PropertyNameCaseInsensitive); + Assert.Equal("World", (string)jObject["Hello"]); + Assert.Equal("World", (string)jObject["hello"]); // Test case insensitivity + } + } } } diff --git a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.TryGet.Date.cs b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.TryGet.Date.cs index e5bf98633c788..66d912714e639 100644 --- a/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.TryGet.Date.cs +++ b/src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Utf8JsonReaderTests.TryGet.Date.cs @@ -252,5 +252,23 @@ static void Test(string testString, bool isFinalBlock) Test(testString, isFinalBlock: true); Test(testString, isFinalBlock: false); } + + [Theory] + [InlineData(@"""\u001c\u0001""")] + [InlineData(@"""\u001c\u0001\u0001""")] + public static void TryGetDateTimeAndOffset_InvalidPropertyValue(string testString) + { + var dataUtf8 = Encoding.UTF8.GetBytes(testString); + var json = new Utf8JsonReader(dataUtf8); + Assert.True(json.Read()); + + Assert.False(json.TryGetDateTime(out var dateTime)); + Assert.Equal(default, dateTime); + JsonTestHelper.AssertThrows(json, (json) => json.GetDateTime()); + + Assert.False(json.TryGetDateTimeOffset(out var dateTimeOffset)); + Assert.Equal(default, dateTimeOffset); + JsonTestHelper.AssertThrows(json, (json) => json.GetDateTimeOffset()); + } } } diff --git a/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs b/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs index 57ab539a01337..d3b724985d2c1 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs +++ b/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Emitter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System; using System.Buffers.Binary; using System.CodeDom.Compiler; using System.Collections; @@ -11,10 +10,7 @@ using System.Globalization; using System.IO; using System.Linq; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Security.Cryptography; -using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -59,7 +55,7 @@ private static (string, ImmutableArray) EmitRegexType(RegexType rege var parentClasses = new Stack(); while (parent is not null) { - parentClasses.Push($"partial {parent.Keyword} {parent.Name} {parent.Constraints}"); + parentClasses.Push($"partial {parent.Keyword} {parent.Name}"); parent = parent.ParentClass; } while (parentClasses.Count != 0) @@ -70,7 +66,7 @@ private static (string, ImmutableArray) EmitRegexType(RegexType rege } // Emit the direct parent type - writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name} {regexClass.Constraints}"); + writer.WriteLine($"partial {regexClass.Keyword} {regexClass.Name}"); writer.WriteLine("{"); writer.Indent++; @@ -223,7 +219,7 @@ private static ImmutableArray EmitRegexMethod(IndentedTextWriter wri writer.WriteLine(); writer.WriteLine(" // Description:"); - DescribeExpression(writer, rm.Code.Tree.Root.Child(0), " // "); // skip implicit root capture + DescribeExpression(writer, rm.Code.Tree.Root.Child(0), " // ", rm.Code); // skip implicit root capture writer.WriteLine(); writer.WriteLine($" protected override bool FindFirstChar()"); @@ -364,6 +360,12 @@ private static RequiredHelperFunctions EmitFindFirstChar(IndentedTextWriter writ EmitFixedSet(); break; + case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: + Debug.Assert(code.FindOptimizations.LiteralAfterLoop is not null); + additionalDeclarations.Add("global::System.ReadOnlySpan inputSpan = base.runtext;"); + EmitLiteralAfterAtomicLoop(); + break; + default: Debug.Fail($"Unexpected mode: {code.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; @@ -584,6 +586,61 @@ void EmitFixedSet() loopBlock.Dispose(); } + // Emits a search for a literal following a leading atomic single-character loop. + void EmitLiteralAfterAtomicLoop() + { + Debug.Assert(code.FindOptimizations.LiteralAfterLoop is not null); + (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = code.FindOptimizations.LiteralAfterLoop.Value; + + Debug.Assert(target.LoopNode.Type is RegexNode.Setloop or RegexNode.Setlazy or RegexNode.Setloopatomic); + Debug.Assert(target.LoopNode.N == int.MaxValue); + + using (EmitBlock(writer, "while (true)")) + { + writer.WriteLine($"global::System.ReadOnlySpan slice = inputSpan.Slice(pos, end - pos);"); + writer.WriteLine(); + + // Find the literal. If we can't find it, we're done searching. + writer.Write("int i = global::System.MemoryExtensions."); + writer.WriteLine( + target.Literal.String is string literalString ? $"IndexOf(slice, {Literal(literalString)});" : + target.Literal.Chars is not char[] literalChars ? $"IndexOf(slice, {Literal(target.Literal.Char)});" : + literalChars.Length switch + { + 2 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])});", + 3 => $"IndexOfAny(slice, {Literal(literalChars[0])}, {Literal(literalChars[1])}, {Literal(literalChars[2])});", + _ => $"IndexOfAny(slice, {Literal(new string(literalChars))});", + }); + using (EmitBlock(writer, $"if (i < 0)")) + { + writer.WriteLine("break;"); + } + writer.WriteLine(); + + // We found the literal. Walk backwards from it finding as many matches as we can against the loop. + writer.WriteLine("int prev = i;"); + writer.WriteLine($"while ((uint)--prev < (uint)slice.Length && {MatchCharacterClass(hasTextInfo, options, "slice[prev]", target.LoopNode.Str!, caseInsensitive: false, negate: false, additionalDeclarations, ref requiredHelpers)});"); + + if (target.LoopNode.M > 0) + { + // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, + // so we can start from after the last place the literal matched. + writer.WriteLine($"if ((i - prev - 1) < {target.LoopNode.M})"); + writer.WriteLine("{"); + writer.WriteLine(" pos += i + 1;"); + writer.WriteLine(" continue;"); + writer.WriteLine("}"); + } + writer.WriteLine(); + + // We have a winner. The starting position is just after the last position that failed to match the loop. + // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching + // after the loop, so that it doesn't need to re-match the loop. + writer.WriteLine("base.runtextpos = pos + prev + 1;"); + writer.WriteLine("return true;"); + } + } + // If a TextInfo is needed to perform ToLower operations, emits a local initialized to the TextInfo to use. static void EmitTextInfo(IndentedTextWriter writer, ref bool hasTextInfo, RegexMethod rm) { @@ -859,24 +916,69 @@ void EmitAlternation(RegexNode node) } } + // Detect whether every branch begins with one or more unique characters. + const int SetCharsSize = 5; // arbitrary limit (for IgnoreCase, we want this to be at least 3 to handle the vast majority of values) + Span setChars = stackalloc char[SetCharsSize]; if (useSwitchedBranches) { + // Iterate through every branch, seeing if we can easily find a starting One, Multi, or small Set. + // If we can, extract its starting char (or multiple in the case of a set), validate that all such + // starting characters are unique relative to all the branches. var seenChars = new HashSet(); - for (int i = 0; i < childCount; i++) + for (int i = 0; i < childCount && useSwitchedBranches; i++) { - if (node.Child(i).FindBranchOneOrMultiStart() is not RegexNode oneOrMulti || - !seenChars.Add(oneOrMulti.FirstCharOfOneOrMulti())) + // If it's not a One, Multi, or Set, we can't apply this optimization. + // If it's IgnoreCase (and wasn't reduced to a non-IgnoreCase set), also ignore it to keep the logic simple. + if (node.Child(i).FindBranchOneMultiOrSetStart() is not RegexNode oneMultiOrSet || + (oneMultiOrSet.Options & RegexOptions.IgnoreCase) != 0) // TODO: https://github.com/dotnet/runtime/issues/61048 { useSwitchedBranches = false; break; } + + // If it's a One or a Multi, get the first character and add it to the set. + // If it was already in the set, we can't apply this optimization. + if (oneMultiOrSet.Type is RegexNode.One or RegexNode.Multi) + { + if (!seenChars.Add(oneMultiOrSet.FirstCharOfOneOrMulti())) + { + useSwitchedBranches = false; + break; + } + } + else + { + // The branch begins with a set. Make sure it's a set of only a few characters + // and get them. If we can't, we can't apply this optimization. + Debug.Assert(oneMultiOrSet.Type is RegexNode.Set); + int numChars; + if (RegexCharClass.IsNegated(oneMultiOrSet.Str!) || + (numChars = RegexCharClass.GetSetChars(oneMultiOrSet.Str!, setChars)) == 0) + { + useSwitchedBranches = false; + break; + } + + // Check to make sure each of the chars is unique relative to all other branches examined. + foreach (char c in setChars.Slice(0, numChars)) + { + if (!seenChars.Add(c)) + { + useSwitchedBranches = false; + break; + } + } + } } } if (useSwitchedBranches) { // Note: This optimization does not exist with RegexOptions.Compiled. Here we rely on the - // C# compiler to lower the C# switch statement with appropriate optimizations. + // C# compiler to lower the C# switch statement with appropriate optimizations. In some + // cases there are enough branches that the compiler will emit a jump table. In others + // it'll optimize the order of checks in order to minimize the total number in the worst + // case. In any case, we get easier to read and reason about C#. EmitSwitchedBranches(); } else @@ -893,8 +995,9 @@ void EmitSwitchedBranches() writer.WriteLine(); // Emit a switch statement on the first char of each branch. - using (EmitBlock(writer, $"switch ({ToLowerIfNeeded(hasTextInfo, options, $"{sliceSpan}[{sliceStaticPos++}]", IsCaseInsensitive(node))})")) + using (EmitBlock(writer, $"switch ({sliceSpan}[{sliceStaticPos++}])")) { + Span setChars = stackalloc char[SetCharsSize]; // needs to be same size as detection check in caller int startingSliceStaticPos = sliceStaticPos; // Emit a case for each branch. @@ -903,13 +1006,23 @@ void EmitSwitchedBranches() sliceStaticPos = startingSliceStaticPos; RegexNode child = node.Child(i); - Debug.Assert(child.Type is RegexNode.One or RegexNode.Multi or RegexNode.Concatenate, DescribeNode(child)); - Debug.Assert(child.Type is not RegexNode.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Type is RegexNode.One or RegexNode.Multi)); + Debug.Assert(child.Type is RegexNode.One or RegexNode.Multi or RegexNode.Set or RegexNode.Concatenate, DescribeNode(child, rm.Code)); + Debug.Assert(child.Type is not RegexNode.Concatenate || (child.ChildCount() >= 2 && child.Child(0).Type is RegexNode.One or RegexNode.Multi or RegexNode.Set)); - RegexNode? childStart = child.FindBranchOneOrMultiStart(); - Debug.Assert(childStart is not null, DescribeNode(child)); + RegexNode? childStart = child.FindBranchOneMultiOrSetStart(); + Debug.Assert(childStart is not null, "Unexpectedly couldn't find the branch starting node."); + Debug.Assert((childStart.Options & RegexOptions.IgnoreCase) == 0, "Expected only to find non-IgnoreCase branch starts"); - writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:"); + if (childStart.Type is RegexNode.Set) + { + int numChars = RegexCharClass.GetSetChars(childStart.Str!, setChars); + Debug.Assert(numChars != 0); + writer.WriteLine($"case {string.Join(" or ", setChars.Slice(0, numChars).ToArray().Select(c => Literal(c)))}:"); + } + else + { + writer.WriteLine($"case {Literal(childStart.FirstCharOfOneOrMulti())}:"); + } writer.Indent++; // Emit the code for the branch, without the first character that was already matched in the switch. @@ -917,6 +1030,7 @@ void EmitSwitchedBranches() { case RegexNode.Multi: EmitNode(CloneMultiWithoutFirstChar(child)); + writer.WriteLine(); break; case RegexNode.Concatenate: @@ -931,16 +1045,17 @@ void EmitSwitchedBranches() newConcat.AddChild(child.Child(j)); } EmitNode(newConcat.Reduce()); + writer.WriteLine(); break; - static RegexNode CloneMultiWithoutFirstChar(RegexNode node) - { - Debug.Assert(node.Type is RegexNode.Multi); - Debug.Assert(node.Str!.Length >= 2); - return node.Str!.Length == 2 ? - new RegexNode(RegexNode.One, node.Options, node.Str![1]) : - new RegexNode(RegexNode.Multi, node.Options, node.Str!.Substring(1)); - } + static RegexNode CloneMultiWithoutFirstChar(RegexNode node) + { + Debug.Assert(node.Type is RegexNode.Multi); + Debug.Assert(node.Str!.Length >= 2); + return node.Str!.Length == 2 ? + new RegexNode(RegexNode.One, node.Options, node.Str![1]) : + new RegexNode(RegexNode.Multi, node.Options, node.Str!.Substring(1)); + } } // This is only ever used for atomic alternations, so we can simply reset the doneLabel @@ -952,7 +1067,6 @@ static RegexNode CloneMultiWithoutFirstChar(RegexNode node) // Before jumping to the end, we need to zero out sliceStaticPos, so that no // matter what the value is after the branch, whatever follows the alternate // will see the same sliceStaticPos. - writer.WriteLine(); TransferSliceStaticPosToPos(); writer.WriteLine($"break;"); writer.WriteLine(); @@ -1140,7 +1254,7 @@ void EmitBackreference(RegexNode node) // in which case per ECMA 262 section 21.2.2.9 the backreference should succeed. if ((node.Options & RegexOptions.ECMAScript) != 0) { - writer.WriteLine($"// If the {DescribeNonNegative(node.M)} capture hasn't matched, the backreference matches with RegexOptions.ECMAScript rules."); + writer.WriteLine($"// If the {DescribeCapture(node.M, rm.Code)} hasn't matched, the backreference matches with RegexOptions.ECMAScript rules."); using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { EmitWhenHasCapture(); @@ -1148,7 +1262,7 @@ void EmitBackreference(RegexNode node) } else { - writer.WriteLine($"// If the {DescribeNonNegative(node.M)} capture hasn't matched, the backreference doesn't match."); + writer.WriteLine($"// If the {DescribeCapture(node.M, rm.Code)} hasn't matched, the backreference doesn't match."); using (EmitBlock(writer, $"if (!base.IsMatched({capnum}))")) { writer.WriteLine($"goto {doneLabel};"); @@ -1225,7 +1339,7 @@ void EmitBackreferenceConditional(RegexNode node) { using (EmitBlock(writer, $"if (base.IsMatched({capnum}))")) { - writer.WriteLine($"// The {DescribeNonNegative(node.M)} capture group captured a value. Match the first branch."); + writer.WriteLine($"// The {DescribeCapture(node.M, rm.Code)} captured a value. Match the first branch."); EmitNode(yesBranch); writer.WriteLine(); TransferSliceStaticPosToPos(); // make sure sliceStaticPos is 0 after each branch @@ -1702,7 +1816,7 @@ void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthCheck // Put the node's code into its own scope. If the node contains labels that may need to // be visible outside of its scope, the scope is still emitted for clarity but is commented out. - using (EmitScope(writer, DescribeNode(node), faux: PossiblyBacktracks(node) && !node.IsAtomicByParent())) + using (EmitScope(writer, DescribeNode(node, rm.Code), faux: PossiblyBacktracks(node) && !node.IsAtomicByParent())) { switch (node.Type) { @@ -1741,7 +1855,7 @@ void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthCheck case RegexNode.Onelazy: case RegexNode.Notonelazy: case RegexNode.Setlazy: - EmitSingleCharLazy(node, emitLengthChecksIfRequired); + EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNode.Oneloopatomic: @@ -1819,7 +1933,10 @@ void EmitUpdateBumpalong(RegexNode node) Debug.Assert(node.Type is RegexNode.UpdateBumpalong, $"Unexpected type: {node.Type}"); TransferSliceStaticPosToPos(); - writer.WriteLine("base.runtextpos = pos;"); + using (EmitBlock(writer, "if (base.runtextpos < pos)")) + { + writer.WriteLine("base.runtextpos = pos;"); + } } // Emits code for a concatenation @@ -1857,7 +1974,7 @@ void WriteSingleCharChild(RegexNode child, bool includeDescription = true) writer.Write("if ("); } EmitSingleChar(child, emitLengthCheck: false, clauseOnly: true); - prevDescription = includeDescription ? DescribeNode(child) : null; + prevDescription = includeDescription ? DescribeNode(child, rm.Code) : null; wroteClauses = true; } @@ -1901,7 +2018,7 @@ RegexNode.Notoneloop or RegexNode.Notonelazy or RegexNode.Notoneloopatomic && if (i < exclusiveEnd) { - EmitNode(node.Child(i), i + 1 < childCount ? node.Child(i + 1) : subsequent, emitLengthChecksIfRequired: false); + EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: false); if (i < childCount - 1) { writer.WriteLine(); @@ -1915,12 +2032,28 @@ RegexNode.Notoneloop or RegexNode.Notonelazy or RegexNode.Notoneloopatomic && continue; } - EmitNode(node.Child(i), i + 1 < childCount ? node.Child(i + 1) : subsequent, emitLengthChecksIfRequired: emitLengthChecksIfRequired); + EmitNode(node.Child(i), GetSubsequentOrDefault(i, node, subsequent), emitLengthChecksIfRequired: emitLengthChecksIfRequired); if (i < childCount - 1) { writer.WriteLine(); } } + + // Gets the node to treat as the subsequent one to node.Child(index) + static RegexNode? GetSubsequentOrDefault(int index, RegexNode node, RegexNode? defaultNode) + { + int childCount = node.ChildCount(); + for (int i = index + 1; i < childCount; i++) + { + RegexNode next = node.Child(i); + if (next.Type is not RegexNode.UpdateBumpalong) // skip node types that don't have a semantic impact + { + return next; + } + } + + return defaultNode; + } } // Emits the code to handle a single-character match. @@ -2211,33 +2344,28 @@ void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitL if (expressionHasCaptures) { EmitUncaptureUntil(StackPop()); - EmitStackPop(endingPos, startingPos); - } - else - { - EmitStackPop(endingPos, startingPos); } + EmitStackPop(endingPos, startingPos); + writer.WriteLine(); - string originalDoneLabel = doneLabel; - using (EmitBlock(writer, $"if ({startingPos} >= {endingPos})")) - { - writer.WriteLine($"goto {originalDoneLabel};"); - } - doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes - - if (subsequent?.FindStartingCharacter() is char subsequentCharacter) + if (subsequent?.FindStartingCharacterOrString() is ValueTuple literal) { - writer.WriteLine(); - writer.WriteLine($"{endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(subsequentCharacter)});"); - using (EmitBlock(writer, $"if ({endingPos} < 0)")) + writer.WriteLine($"if ({startingPos} >= {endingPos} ||"); + using (EmitBlock(writer, literal.Item2 is not null ? + $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, global::System.Math.Min(inputSpan.Length, {endingPos} + {literal.Item2.Length - 1}) - {startingPos}), {Literal(literal.Item2)})) < 0)" : + $" ({endingPos} = global::System.MemoryExtensions.LastIndexOf(inputSpan.Slice({startingPos}, {endingPos} - {startingPos}), {Literal(literal.Item1)})) < 0)")) { - writer.WriteLine($"goto {originalDoneLabel};"); + writer.WriteLine($"goto {doneLabel};"); } writer.WriteLine($"{endingPos} += {startingPos};"); writer.WriteLine($"pos = {endingPos};"); } else { + using (EmitBlock(writer, $"if ({startingPos} >= {endingPos})")) + { + writer.WriteLine($"goto {doneLabel};"); + } writer.WriteLine($"pos = --{endingPos};"); } @@ -2248,9 +2376,11 @@ void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitL EmitStackPush(expressionHasCaptures ? new[] { startingPos, endingPos, "base.Crawlpos()" } : new[] { startingPos, endingPos }); + + doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } - void EmitSingleCharLazy(RegexNode node, bool emitLengthChecksIfRequired = true) + void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Type is RegexNode.Onelazy or RegexNode.Notonelazy or RegexNode.Setlazy, $"Unexpected type: {node.Type}"); @@ -2337,6 +2467,45 @@ void EmitSingleCharLazy(RegexNode node, bool emitLengthChecksIfRequired = true) SliceInputSpan(writer); EmitSingleChar(node); TransferSliceStaticPosToPos(); + + // Now that we've appropriately advanced by one character and are set for what comes after the loop, + // see if we can skip ahead more iterations by doing a search for a following literal. + if (iterationCount is null && + node.Type is RegexNode.Notonelazy && + !IsCaseInsensitive(node) && + subsequent?.FindStartingCharacterOrString() is ValueTuple literal && + (literal.Item2?[0] ?? literal.Item1) != node.Ch) + { + // e.g. "<[^>]*?>" + // This lazy loop will consume all characters other than node.Ch until the subsequent literal. + // We can implement it to search for either that char or the literal, whichever comes first. + // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). + writer.WriteLine($"{startingPos} = global::System.MemoryExtensions.IndexOfAny({sliceSpan}, {Literal(node.Ch)}, {Literal(literal.Item2?[0] ?? literal.Item1)});"); + using (EmitBlock(writer, $"if ((uint){startingPos} >= (uint){sliceSpan}.Length || {sliceSpan}[{startingPos}] == {Literal(node.Ch)})")) + { + writer.WriteLine($"goto {doneLabel};"); + } + writer.WriteLine($"pos += {startingPos};"); + SliceInputSpan(writer); + } + else if (iterationCount is null && + node.Type is RegexNode.Setlazy && + node.Str == RegexCharClass.AnyClass && + subsequent?.FindStartingCharacterOrString() is ValueTuple literal2) + { + // e.g. ".*?string" with RegexOptions.Singleline + // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal + // isn't found, the loop fails. We can implement it to just search for that literal. + writer.WriteLine($"{startingPos} = global::System.MemoryExtensions.IndexOf({sliceSpan}, {(literal2.Item2 is not null ? Literal(literal2.Item2) : Literal(literal2.Item1))});"); + using (EmitBlock(writer, $"if ({startingPos} < 0)")) + { + writer.WriteLine($"goto {doneLabel};"); + } + writer.WriteLine($"pos += {startingPos};"); + SliceInputSpan(writer); + } + + // Store the position we've left off at in case we need to iterate again. writer.WriteLine($"{startingPos} = pos;"); // Update the done label for everything that comes after this node. This is done after we emit the single char @@ -3395,7 +3564,7 @@ private static string Literal(RegexOptions options) } /// Gets a textual description of the node fit for rendering in a comment in source. - private static string DescribeNode(RegexNode node) => + private static string DescribeNode(RegexNode node, RegexCode regexCode) => node.Type switch { RegexNode.Alternate => $"Match with {node.ChildCount()} alternative expressions{(node.IsAtomicByParent() ? ", atomically" : "")}.", @@ -3403,8 +3572,9 @@ private static string DescribeNode(RegexNode node) => RegexNode.Beginning => "Match if at the beginning of the string.", RegexNode.Bol => "Match if at the beginning of a line.", RegexNode.Boundary => $"Match if at a word boundary.", - RegexNode.Capture when node.N != -1 => $"{DescribeNonNegative(node.M)} capturing group. Uncaptures the {DescribeNonNegative(node.N)} capturing group.", - RegexNode.Capture when node.N == -1 => $"{DescribeNonNegative(node.M)} capturing group.", + RegexNode.Capture when node.M == -1 && node.N != -1 => $"Non-capturing balancing group. Uncaptures the {DescribeCapture(node.N, regexCode)}.", + RegexNode.Capture when node.N != -1 => $"Balancing group. Captures the {DescribeCapture(node.M, regexCode)} and uncaptures the {DescribeCapture(node.N, regexCode)}.", + RegexNode.Capture when node.N == -1 => $"{DescribeCapture(node.M, regexCode)}.", RegexNode.Concatenate => "Match a sequence of expressions.", RegexNode.ECMABoundary => $"Match if at a word boundary (according to ECMAScript rules).", RegexNode.Empty => $"Match an empty string.", @@ -3421,23 +3591,71 @@ private static string DescribeNode(RegexNode node) => RegexNode.One => $"Match {Literal(node.Ch)}.", RegexNode.Oneloop or RegexNode.Oneloopatomic or RegexNode.Onelazy => $"Match {Literal(node.Ch)} {DescribeLoop(node)}.", RegexNode.Prevent => $"Zero-width negative lookahead assertion.", - RegexNode.Ref => $"Match the same text as matched by the {DescribeNonNegative(node.M)} capture group.", + RegexNode.Ref => $"Match the same text as matched by the {DescribeCapture(node.M, regexCode)}.", RegexNode.Require => $"Zero-width positive lookahead assertion.", - RegexNode.Set => $"Match a character in the set {RegexCharClass.SetDescription(node.Str!)}.", - RegexNode.Setloop or RegexNode.Setloopatomic or RegexNode.Setlazy => $"Match a character in the set {RegexCharClass.SetDescription(node.Str!)} {DescribeLoop(node)}.", + RegexNode.Set => $"Match {DescribeSet(node.Str!)}.", + RegexNode.Setloop or RegexNode.Setloopatomic or RegexNode.Setlazy => $"Match {DescribeSet(node.Str!)} {DescribeLoop(node)}.", RegexNode.Start => "Match if at the start position.", RegexNode.Testgroup => $"Conditionally match one of two expressions depending on whether an initial expression matches.", - RegexNode.Testref => $"Conditionally match one of two expressions depending on whether the {DescribeNonNegative(node.M)} capture group matched.", + RegexNode.Testref => $"Conditionally match one of two expressions depending on whether the {DescribeCapture(node.M, regexCode)} matched.", RegexNode.UpdateBumpalong => $"Advance the next matching position.", _ => $"Unknown node type {node.Type}", }; + /// Gets an identifer to describe a capture group. + private static string DescribeCapture(int capNum, RegexCode regexCode) + { + // If we can get a capture name from the captures collection and it's not just a numerical representation of the group, use it. + string name = RegexParser.GroupNameFromNumber(regexCode.Caps, regexCode.Tree.CapsList, regexCode.CapSize, capNum); + if (!string.IsNullOrEmpty(name) && + (!int.TryParse(name, out int id) || id != capNum)) + { + name = Literal(name); + } + else + { + // Otherwise, create a numerical description of the capture group. + int tens = capNum % 10; + name = tens is >= 1 and <= 3 && capNum % 100 is < 10 or > 20 ? // Ends in 1, 2, 3 but not 11, 12, or 13 + tens switch + { + 1 => $"{capNum}st", + 2 => $"{capNum}nd", + _ => $"{capNum}rd", + } : + $"{capNum}th"; + } + + return $"{name} capture group"; + } + + /// Gets a textual description of what characters match a set. + private static string DescribeSet(string charClass) => + charClass switch + { + RegexCharClass.AnyClass => "any character", + RegexCharClass.DigitClass => "a Unicode digit", + RegexCharClass.ECMADigitClass => "'0' through '9'", + RegexCharClass.ECMASpaceClass => "a whitespace character (ECMA)", + RegexCharClass.ECMAWordClass => "a word character (ECMA)", + RegexCharClass.NotDigitClass => "any character other than a Unicode digit", + RegexCharClass.NotECMADigitClass => "any character other than '0' through '9'", + RegexCharClass.NotECMASpaceClass => "any character other than a space character (ECMA)", + RegexCharClass.NotECMAWordClass => "any character other than a word character (ECMA)", + RegexCharClass.NotSpaceClass => "any character other than a space character", + RegexCharClass.NotWordClass => "any character other than a word character", + RegexCharClass.SpaceClass => "a whitespace character", + RegexCharClass.WordClass => "a word character", + _ => $"a character in the set {RegexCharClass.SetDescription(charClass)}", + }; + /// Writes a textual description of the node tree fit for rending in source. /// The writer to which the description should be written. /// The node being written. /// The prefix to write at the beginning of every line, including a "//" for a comment. + /// regex tree /// The depth of the current node. - private static void DescribeExpression(TextWriter writer, RegexNode node, string prefix, int depth = 0) + private static void DescribeExpression(TextWriter writer, RegexNode node, string prefix, RegexCode regexCode, int depth = 0) { bool skip = node.Type switch { @@ -3468,7 +3686,7 @@ RegexNode.Testref when node.Next.Child(1) == node => "Not Matched: ", // Write out the line for the node. const char BulletPoint = '\u25CB'; - writer.WriteLine($"{prefix}{new string(' ', depth * 4)}{BulletPoint} {tag}{DescribeNode(node)}"); + writer.WriteLine($"{prefix}{new string(' ', depth * 4)}{BulletPoint} {tag}{DescribeNode(node, regexCode)}"); } // Recur into each of its children. @@ -3476,29 +3694,10 @@ RegexNode.Testref when node.Next.Child(1) == node => "Not Matched: ", for (int i = 0; i < childCount; i++) { int childDepth = skip ? depth : depth + 1; - DescribeExpression(writer, node.Child(i), prefix, childDepth); + DescribeExpression(writer, node.Child(i), prefix, regexCode, childDepth); } } - /// Gets a textual description of a number, e.g. 3 => "3rd". - private static string DescribeNonNegative(int n) - { - if (n < 0) - { - return n.ToString(CultureInfo.InvariantCulture); - } - - int tens = n % 10; - return tens is >= 1 and <= 3 && n % 100 is < 10 or > 20 ? // Ends in 1, 2, 3 but not 11, 12, or 13 - tens switch - { - 1 => $"{n}st", - 2 => $"{n}nd", - _ => $"{n}rd", - } : - $"{n}th"; - } - /// Gets a textual description of a loop's style and bounds. private static string DescribeLoop(RegexNode node) { diff --git a/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Parser.cs b/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Parser.cs index c8e88bd2c2b38..f5651fdf169c1 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Parser.cs +++ b/src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Parser.cs @@ -202,8 +202,7 @@ private static bool IsSyntaxTargetForGeneration(SyntaxNode node) => regexMethod, typeDec is RecordDeclarationSyntax rds ? $"{typeDec.Keyword.ValueText} {rds.ClassOrStructKeyword}" : typeDec.Keyword.ValueText, ns ?? string.Empty, - $"{typeDec.Identifier}{typeDec.TypeParameterList}", - typeDec.ConstraintClauses.ToString()); + $"{typeDec.Identifier}{typeDec.TypeParameterList}"); RegexType current = regexType; var parent = typeDec.Parent as TypeDeclarationSyntax; @@ -214,8 +213,7 @@ private static bool IsSyntaxTargetForGeneration(SyntaxNode node) => null, parent is RecordDeclarationSyntax rds2 ? $"{parent.Keyword.ValueText} {rds2.ClassOrStructKeyword}" : parent.Keyword.ValueText, ns ?? string.Empty, - $"{parent.Identifier}{parent.TypeParameterList}", - parent.ConstraintClauses.ToString()); + $"{parent.Identifier}{parent.TypeParameterList}"); current = current.ParentClass; parent = parent.Parent as TypeDeclarationSyntax; @@ -235,7 +233,7 @@ static bool IsAllowedKind(SyntaxKind kind) => internal sealed record RegexMethod(MethodDeclarationSyntax MethodSyntax, string MethodName, string Modifiers, string Pattern, RegexOptions Options, int MatchTimeout, RegexCode Code); /// A type holding a regex method. - internal sealed record RegexType(RegexMethod? Method, string Keyword, string Namespace, string Name, string Constraints) + internal sealed record RegexType(RegexMethod? Method, string Keyword, string Namespace, string Name) { public RegexType? ParentClass { get; set; } } diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.cs.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.cs.xlf index 1b24236f5aedd..3907e73e7ca2b 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.cs.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.cs.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + RegexGenerator nemohl vygenerovat úplnou zdrojovou implementaci zadaného regulárního výrazu, protože možnost není podporovaná nebo je regulární výraz příliš složitý. Implementace bude regulární výraz interpretovat za běhu. RegexGenerator limitation reached. - RegexGenerator limitation reached. + Dosáhlo se omezení nástroje RegexGenerator. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.de.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.de.xlf index af011807dac54..67beed526576d 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.de.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.de.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + Der RegexGenerator konnte aufgrund einer nicht unterstützten Option oder eines zu komplexen regulären Ausdrucks keine vollständige Quellimplementierung für den angegebenen regulären Ausdruck generieren. Die Implementierung wird den regulären Ausdruck zur Laufzeit interpretieren. RegexGenerator limitation reached. - RegexGenerator limitation reached. + RegexGenerator-Begrenzung erreicht. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.es.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.es.xlf index 03cd5902030cc..e97ec8feaf1b2 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.es.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.es.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + RegexGenerator no pudo generar una implementación de origen completa para la expresión regular especificada debido a una opción no admitida o a una expresión regular demasiado compleja. La implementación interpretará la expresión regular en tiempo de ejecución. RegexGenerator limitation reached. - RegexGenerator limitation reached. + Se alcanzó la limitación de RegexGenerator. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.fr.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.fr.xlf index 2059255bf3bfb..16efb2d977b0e 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.fr.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.fr.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + RegexGenerator n’a pas pu générer d’implémentation source complète pour l’expression régulière spécifiée en raison d’une option non prise en charge ou d’une expression régulière trop complexe. L’implémentation interprète l’expression régulière au moment de l’exécution. RegexGenerator limitation reached. - RegexGenerator limitation reached. + Limite RegexGenerator atteinte diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.it.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.it.xlf index 7e5f8ef424400..f7d730755b846 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.it.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.it.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + RegexGenerator non è riuscito a generare un'implementazione di origine completa per l'espressione regolare specificata a causa di un'opzione non supportata o di un'espressione regolare troppo complessa. L'implementazione interpreterà l'espressione regolare in fase di esecuzione. RegexGenerator limitation reached. - RegexGenerator limitation reached. + È stata raggiunta la limitazione di RegexGenerator. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ja.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ja.xlf index 7070423342c46..f14f085a8f42c 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ja.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ja.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + オプションがサポートされていないか、または正規表現が複雑すぎるため、RegexGenerator は指定された正規表現の完全なソース実装を生成できませんでした。 実装では、実行時に正規表現が解釈されます。 RegexGenerator limitation reached. - RegexGenerator limitation reached. + RegexGenerator の制限に達しました。 diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ko.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ko.xlf index ebd89b0c6b28b..618b1067b0eba 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ko.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ko.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + 지원되지 않는 옵션 또는 너무 복잡한 정규식으로 인해 RegexGenerator가 지정한 정규식에 대한 전체 소스 구현을 생성할 수 없습니다. 구현에서는 런타임에 정규식을 해석합니다. RegexGenerator limitation reached. - RegexGenerator limitation reached. + RegexGenerator 제한에 도달했습니다. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.pl.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.pl.xlf index d014e1ebb9e90..f8cde42177c71 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.pl.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.pl.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + Obiekt RegexGenerator nie może wygenerować pełnej implementacji źródła dla określonego wyrażenia regularnego z powodu nieobsługiwanych opcji lub zbyt złożonego wyrażenia regularnego. Implementacja będzie interpretować wyrażenie regularne w czasie wykonywania. RegexGenerator limitation reached. - RegexGenerator limitation reached. + Osiągnięto ograniczenie RegexGenerator. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.pt-BR.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.pt-BR.xlf index 97a7fd1efa5c6..6991eccb5b9cf 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.pt-BR.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.pt-BR.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + O RegexGenerator não pôde gerar uma implementação de origem completa para a expressão regular especificada, devido a uma opção sem suporte ou a uma expressão regular muito complexa. A implementação interpretará a expressão regular em tempo de execução. RegexGenerator limitation reached. - RegexGenerator limitation reached. + Limitação de RegexGenerator atingida. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ru.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ru.xlf index 9af130a287194..4f777ba7d0ccd 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ru.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.ru.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + Средству RegexGenerator не удалось создать полную реализацию источника для указанного регулярного выражения, так как параметр не поддерживается или регулярное выражение является слишком сложным. Реализация будет интерпретировать регулярное выражение во время выполнения. RegexGenerator limitation reached. - RegexGenerator limitation reached. + Достигнуто ограничение RegexGenerator. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.tr.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.tr.xlf index f5e6edd464605..c1492d873c5f5 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.tr.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.tr.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + RegexGenerator, desteklenmeyen bir seçenek veya çok karmaşık bir normal ifade nedeniyle belirtilen normal ifade için tam kaynak uygulaması oluşturamadı. Uygulama, normal ifadeyi çalışma zamanında yorumlar. RegexGenerator limitation reached. - RegexGenerator limitation reached. + RegexGenerator sınırına ulaşıldı. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.zh-Hans.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.zh-Hans.xlf index fe30a51365414..8bc7e9656e5be 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.zh-Hans.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.zh-Hans.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + 由于不支持的选项或正则表达式过于复杂,RegexGenerator 无法为指定正则表达式生成完整的源实现。实现将在运行时解释正则表达式。 RegexGenerator limitation reached. - RegexGenerator limitation reached. + 已达到 RegexGenerator 限制。 diff --git a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.zh-Hant.xlf b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.zh-Hant.xlf index 5bbb62ca0363f..4e598383d8266 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.zh-Hant.xlf +++ b/src/libraries/System.Text.RegularExpressions/gen/Resources/xlf/Strings.zh-Hant.xlf @@ -154,12 +154,12 @@ The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. - The RegexGenerator couldn't generate a complete source implementation for the specified regular expression, due to an unsupported option or too complex a regular expression. The implementation will interpret the regular expression at run-time. + RegexGenerator 無法為指定的規則運算式產生完整的來源實作,因為不支援的選項或規則運算式太複雜。實作會在執行時間解譯規則運算式。 RegexGenerator limitation reached. - RegexGenerator limitation reached. + 已達 RegexGenerator 限制。 diff --git a/src/libraries/System.Text.RegularExpressions/gen/System.Text.RegularExpressions.Generator.csproj b/src/libraries/System.Text.RegularExpressions/gen/System.Text.RegularExpressions.Generator.csproj index 8e1ec70d99d6c..56f7899f081db 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/System.Text.RegularExpressions.Generator.csproj +++ b/src/libraries/System.Text.RegularExpressions/gen/System.Text.RegularExpressions.Generator.csproj @@ -42,6 +42,7 @@ + diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs index 284c8647f31f4..9d108abfb8f02 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs @@ -340,18 +340,7 @@ public int[] GetGroupNumbers() /// public string GroupNameFromNumber(int i) { - if (capslist is null) - { - return (uint)i < (uint)capsize ? - ((uint)i).ToString() : - string.Empty; - } - else - { - return caps != null && !caps.TryGetValue(i, out i) ? string.Empty : - (uint)i < (uint)capslist.Length ? capslist[i] : - string.Empty; - } + return RegexParser.GroupNameFromNumber(caps, capslist, capsize, i); } /// diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs index 98957dfb408df..d52e2889786f7 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCharClass.cs @@ -716,9 +716,8 @@ public static bool TryGetSingleRange(string set, out char lowInclusive, out char /// public static int GetSetChars(string set, Span chars) { - // If the set is negated, it's likely to contain a large number of characters, - // so we don't even try. We also get the characters by enumerating the set - // portion, so we validate that it's set up to enable that, e.g. no categories. + // We get the characters by enumerating the set portion, so we validate that it's + // set up to enable that, e.g. no categories. if (!CanEasilyEnumerateSetContents(set)) { return 0; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs index 29875367928e3..07a3d1b927cd3 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs @@ -51,6 +51,7 @@ internal abstract class RegexCompiler private static readonly MethodInfo s_spanIndexOfAnyCharCharChar = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanIndexOfAnySpan = typeof(MemoryExtensions).GetMethod("IndexOfAny", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanLastIndexOfChar = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), Type.MakeGenericMethodParameter(0) })!.MakeGenericMethod(typeof(char)); + private static readonly MethodInfo s_spanLastIndexOfSpan = typeof(MemoryExtensions).GetMethod("LastIndexOf", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); private static readonly MethodInfo s_spanSliceIntMethod = typeof(ReadOnlySpan).GetMethod("Slice", new Type[] { typeof(int) })!; private static readonly MethodInfo s_spanSliceIntIntMethod = typeof(ReadOnlySpan).GetMethod("Slice", new Type[] { typeof(int), typeof(int) })!; private static readonly MethodInfo s_spanStartsWith = typeof(MemoryExtensions).GetMethod("StartsWith", new Type[] { typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(ReadOnlySpan<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) })!.MakeGenericMethod(typeof(char)); @@ -58,6 +59,7 @@ internal abstract class RegexCompiler private static readonly MethodInfo s_stringGetCharsMethod = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) })!; private static readonly MethodInfo s_textInfoToLowerMethod = typeof(TextInfo).GetMethod("ToLower", new Type[] { typeof(char) })!; private static readonly MethodInfo s_arrayResize = typeof(Array).GetMethod("Resize")!.MakeGenericMethod(typeof(int)); + private static readonly MethodInfo s_mathMinIntInt = typeof(Math).GetMethod("Min", new Type[] { typeof(int), typeof(int) })!; /// The ILGenerator currently in use. protected ILGenerator? _ilg; @@ -443,6 +445,11 @@ FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive or EmitFixedSet_LeftToRight(); break; + case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: + Debug.Assert(_code.FindOptimizations.LiteralAfterLoop is not null); + EmitLiteralAfterAtomicLoop(); + break; + default: Debug.Fail($"Unexpected mode: {_code.FindOptimizations.FindMode}"); goto case FindNextStartingPositionMode.NoSearch; @@ -820,6 +827,151 @@ void EmitFixedSet_LeftToRight() BrFar(returnFalse); } } + + // Emits a search for a literal following a leading atomic single-character loop. + void EmitLiteralAfterAtomicLoop() + { + Debug.Assert(_code.FindOptimizations.LiteralAfterLoop is not null); + (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal) target = _code.FindOptimizations.LiteralAfterLoop.Value; + + Debug.Assert(target.LoopNode.Type is RegexNode.Setloop or RegexNode.Setlazy or RegexNode.Setloopatomic); + Debug.Assert(target.LoopNode.N == int.MaxValue); + + // while (true) + Label loopBody = DefineLabel(); + Label loopEnd = DefineLabel(); + MarkLabel(loopBody); + + // ReadOnlySpan slice = inputSpan.Slice(pos, end - pos); + using RentedLocalBuilder slice = RentReadOnlySpanCharLocal(); + Ldloca(inputSpan); + Ldloc(pos); + Ldloc(end); + Ldloc(pos); + Sub(); + Call(s_spanSliceIntIntMethod); + Stloc(slice); + + // Find the literal. If we can't find it, we're done searching. + // int i = slice.IndexOf(literal); + // if (i < 0) break; + using RentedLocalBuilder i = RentInt32Local(); + Ldloc(slice); + if (target.Literal.String is string literalString) + { + Ldstr(literalString); + Call(s_stringAsSpanMethod); + Call(s_spanIndexOfSpan); + } + else if (target.Literal.Chars is not char[] literalChars) + { + Ldc(target.Literal.Char); + Call(s_spanIndexOfChar); + } + else + { + switch (literalChars.Length) + { + case 2: + Ldc(literalChars[0]); + Ldc(literalChars[1]); + Call(s_spanIndexOfAnyCharChar); + break; + case 3: + Ldc(literalChars[0]); + Ldc(literalChars[1]); + Ldc(literalChars[2]); + Call(s_spanIndexOfAnyCharCharChar); + break; + default: + Ldstr(new string(literalChars)); + Call(s_stringAsSpanMethod); + Call(s_spanIndexOfAnySpan); + break; + } + } + Stloc(i); + Ldloc(i); + Ldc(0); + BltFar(loopEnd); + + // We found the literal. Walk backwards from it finding as many matches as we can against the loop. + + // int prev = i; + using RentedLocalBuilder prev = RentInt32Local(); + Ldloc(i); + Stloc(prev); + + // while ((uint)--prev < (uint)slice.Length) && MatchCharClass(slice[prev])); + Label innerLoopBody = DefineLabel(); + Label innerLoopEnd = DefineLabel(); + MarkLabel(innerLoopBody); + Ldloc(prev); + Ldc(1); + Sub(); + Stloc(prev); + Ldloc(prev); + Ldloca(slice); + Call(s_spanGetLengthMethod); + BgeUn(innerLoopEnd); + Ldloca(slice); + Ldloc(prev); + Call(s_spanGetItemMethod); + LdindU2(); + EmitMatchCharacterClass(target.LoopNode.Str!, caseInsensitive: false); + BrtrueFar(innerLoopBody); + MarkLabel(innerLoopEnd); + + if (target.LoopNode.M > 0) + { + // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, + // so we can start from after the last place the literal matched. + // if ((i - prev - 1) < target.LoopNode.M) + // { + // pos += i + 1; + // continue; + // } + Label metMinimum = DefineLabel(); + Ldloc(i); + Ldloc(prev); + Sub(); + Ldc(1); + Sub(); + Ldc(target.LoopNode.M); + Bge(metMinimum); + Ldloc(pos); + Ldloc(i); + Add(); + Ldc(1); + Add(); + Stloc(pos); + BrFar(loopBody); + MarkLabel(metMinimum); + } + + // We have a winner. The starting position is just after the last position that failed to match the loop. + // TODO: It'd be nice to be able to communicate i as a place the matching engine can start matching + // after the loop, so that it doesn't need to re-match the loop. + + // base.runtextpos = pos + prev + 1; + // return true; + Ldthis(); + Ldloc(pos); + Ldloc(prev); + Add(); + Ldc(1); + Add(); + Stfld(s_runtextposField); + Ldc(1); + Ret(); + + // } + MarkLabel(loopEnd); + + // base.runtextpos = end; + // return false; + BrFar(returnFalse); + } } /// Generates the implementation for Go. @@ -1905,7 +2057,7 @@ void EmitNode(RegexNode node, RegexNode? subsequent = null, bool emitLengthCheck case RegexNode.Onelazy: case RegexNode.Notonelazy: case RegexNode.Setlazy: - EmitSingleCharLazy(node, emitLengthChecksIfRequired); + EmitSingleCharLazy(node, subsequent, emitLengthChecksIfRequired); break; case RegexNode.Oneloopatomic: @@ -1997,11 +2149,19 @@ void EmitUpdateBumpalong(RegexNode node) { Debug.Assert(node.Type is RegexNode.UpdateBumpalong, $"Unexpected type: {node.Type}"); - // base.runtextpos = pos; + // if (base.runtextpos < pos) + // { + // base.runtextpos = pos; + // } TransferSliceStaticPosToPos(); + Ldthisfld(s_runtextposField); + Ldloc(pos); + Label skipUpdate = DefineLabel(); + Bge(skipUpdate); Ldthis(); Ldloc(pos); Stfld(s_runtextposField); + MarkLabel(skipUpdate); } // Emits code for a concatenation @@ -2021,14 +2181,30 @@ void EmitConcatenation(RegexNode node, RegexNode? subsequent, bool emitLengthChe EmitSpanLengthCheck(requiredLength); for (; i < exclusiveEnd; i++) { - EmitNode(node.Child(i), i + 1 < childCount ? node.Child(i + 1) : subsequent, emitLengthChecksIfRequired: false); + EmitNode(node.Child(i), GetSubsequent(i, node, subsequent), emitLengthChecksIfRequired: false); } i--; continue; } - EmitNode(node.Child(i), i + 1 < childCount ? node.Child(i + 1) : subsequent); + EmitNode(node.Child(i), GetSubsequent(i, node, subsequent)); + } + + // Gets the node to treat as the subsequent one to node.Child(index) + static RegexNode? GetSubsequent(int index, RegexNode node, RegexNode? subsequent) + { + int childCount = node.ChildCount(); + for (int i = index + 1; i < childCount; i++) + { + RegexNode next = node.Child(i); + if (next.Type is not RegexNode.UpdateBumpalong) // skip node types that don't have a semantic impact + { + return next; + } + } + + return subsequent; } } @@ -2391,32 +2567,48 @@ void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitL EmitStackPop(); Stloc(startingPos); - // if (startingPos >= endingPos) goto originalDoneLabel; - Label originalDoneLabel = doneLabel; + // if (startingPos >= endingPos) goto doneLabel; Ldloc(startingPos); Ldloc(endingPos); - BgeFar(originalDoneLabel); - doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes + BgeFar(doneLabel); - if (subsequent?.FindStartingCharacter() is char subsequentCharacter) + if (subsequent?.FindStartingCharacterOrString() is ValueTuple literal) { - // endingPos = inputSpan.Slice(startingPos, endingPos - startingPos).LastIndexOf(subsequentCharacter); + // endingPos = inputSpan.Slice(startingPos, Math.Min(inputSpan.Length, endingPos + literal.Length - 1) - startingPos).LastIndexOf(literal); // if (endingPos < 0) // { - // goto originalDoneLabel; + // goto doneLabel; // } Ldloca(inputSpan); Ldloc(startingPos); - Ldloc(endingPos); - Ldloc(startingPos); - Sub(); - Call(s_spanSliceIntIntMethod); - Ldc(subsequentCharacter); - Call(s_spanLastIndexOfChar); + if (literal.Item2 is not null) + { + Ldloca(inputSpan); + Call(s_spanGetLengthMethod); + Ldloc(endingPos); + Ldc(literal.Item2.Length - 1); + Add(); + Call(s_mathMinIntInt); + Ldloc(startingPos); + Sub(); + Call(s_spanSliceIntIntMethod); + Ldstr(literal.Item2); + Call(s_stringAsSpanMethod); + Call(s_spanLastIndexOfSpan); + } + else + { + Ldloc(endingPos); + Ldloc(startingPos); + Sub(); + Call(s_spanSliceIntIntMethod); + Ldc(literal.Item1); + Call(s_spanLastIndexOfChar); + } Stloc(endingPos); Ldloc(endingPos); Ldc(0); - BltFar(originalDoneLabel); + BltFar(doneLabel); // endingPos += startingPos; Ldloc(endingPos); @@ -2448,9 +2640,11 @@ void EmitSingleCharLoop(RegexNode node, RegexNode? subsequent = null, bool emitL { EmitStackPush(() => Ldloc(capturepos!)); } + + doneLabel = backtrackingLabel; // leave set to the backtracking label for all subsequent nodes } - void EmitSingleCharLazy(RegexNode node, bool emitLengthChecksIfRequired = true) + void EmitSingleCharLazy(RegexNode node, RegexNode? subsequent = null, bool emitLengthChecksIfRequired = true) { Debug.Assert(node.Type is RegexNode.Onelazy or RegexNode.Notonelazy or RegexNode.Setlazy, $"Unexpected type: {node.Type}"); @@ -2537,16 +2731,95 @@ void EmitSingleCharLazy(RegexNode node, bool emitLengthChecksIfRequired = true) // Now match the next item in the lazy loop. We need to reset the pos to the position // just after the last character in this loop was matched, and we need to store the resulting position // for the next time we backtrack. - // pos = startingPos; + // Match single char; Ldloc(startingPos); Stloc(pos); SliceInputSpan(); - - // Match single character EmitSingleChar(node); TransferSliceStaticPosToPos(); + // Now that we've appropriately advanced by one character and are set for what comes after the loop, + // see if we can skip ahead more iterations by doing a search for a following literal. + if (iterationCount is null && + node.Type is RegexNode.Notonelazy && + !IsCaseInsensitive(node) && + subsequent?.FindStartingCharacterOrString() is ValueTuple literal && + (literal.Item2?[0] ?? literal.Item1) != node.Ch) + { + // e.g. "<[^>]*?>" + // This lazy loop will consume all characters other than node.Ch until the subsequent literal. + // We can implement it to search for either that char or the literal, whichever comes first. + // If it ends up being that node.Ch, the loop fails (we're only here if we're backtracking). + + // startingPos = slice.IndexOfAny(node.Ch, literal); + Ldloc(slice); + Ldc(node.Ch); + Ldc(literal.Item2?[0] ?? literal.Item1); + Call(s_spanIndexOfAnyCharChar); + Stloc(startingPos); + + // if ((uint)startingPos >= (uint)slice.Length) goto doneLabel; + Ldloc(startingPos); + Ldloca(slice); + Call(s_spanGetLengthMethod); + BgeUnFar(doneLabel); + + // if (slice[startingPos] == node.Ch) goto doneLabel; + Ldloca(slice); + Ldloc(startingPos); + Call(s_spanGetItemMethod); + LdindU2(); + Ldc(node.Ch); + BeqFar(doneLabel); + + // pos += startingPos; + // slice = inputSpace.Slice(pos, end - pos); + Ldloc(pos); + Ldloc(startingPos); + Add(); + Stloc(pos); + SliceInputSpan(); + } + else if (iterationCount is null && + node.Type is RegexNode.Setlazy && + node.Str == RegexCharClass.AnyClass && + subsequent?.FindStartingCharacterOrString() is ValueTuple literal2) + { + // e.g. ".*?string" with RegexOptions.Singleline + // This lazy loop will consume all characters until the subsequent literal. If the subsequent literal + // isn't found, the loop fails. We can implement it to just search for that literal. + + // startingPos = slice.IndexOf(literal); + Ldloc(slice); + if (literal2.Item2 is not null) + { + Ldstr(literal2.Item2); + Call(s_stringAsSpanMethod); + Call(s_spanIndexOfSpan); + } + else + { + Ldc(literal2.Item1); + Call(s_spanIndexOfChar); + } + Stloc(startingPos); + + // if (startingPos < 0) goto doneLabel; + Ldloc(startingPos); + Ldc(0); + BltFar(doneLabel); + + // pos += startingPos; + // slice = inputSpace.Slice(pos, end - pos); + Ldloc(pos); + Ldloc(startingPos); + Add(); + Stloc(pos); + SliceInputSpan(); + } + + // Store the position we've left off at in case we need to iterate again. // startingPos = pos; Ldloc(pos); Stloc(startingPos); diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexFindOptimizations.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexFindOptimizations.cs index de2fb1619e0cb..7f8191e51752c 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexFindOptimizations.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexFindOptimizations.cs @@ -121,12 +121,19 @@ public RegexFindOptimizations(RegexTree tree, CultureInfo culture) // We're now left-to-right only and looking for sets. + // As a backup, see if we can find a literal after a leading atomic loop. That might be better than whatever sets we find, so + // we want to know whether we have one in our pocket before deciding whether to use a leading set. + (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? literalAfterLoop = RegexPrefixAnalyzer.FindLiteralFollowingLeadingLoop(tree); + // Build up a list of all of the sets that are a fixed distance from the start of the expression. List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? fixedDistanceSets = RegexPrefixAnalyzer.FindFixedDistanceSets(tree, culture, thorough: !interpreter); - if (fixedDistanceSets is not null) - { - Debug.Assert(fixedDistanceSets.Count != 0); + Debug.Assert(fixedDistanceSets is null || fixedDistanceSets.Count != 0); + // If we got such sets, we'll likely use them. However, if the best of them is something that doesn't support a vectorized + // search and we did successfully find a literal after an atomic loop we could search instead, we prefer the vectorizable search. + if (fixedDistanceSets is not null && + (fixedDistanceSets[0].Chars is not null || literalAfterLoop is null)) + { // Determine whether to do searching based on one or more sets or on a single literal. Compiled engines // don't need to special-case literals as they already do codegen to create the optimal lookup based on // the set's characteristics. @@ -162,6 +169,15 @@ public RegexFindOptimizations(RegexTree tree, CultureInfo culture) } return; } + + // If we found a literal we can search for after a leading set loop, use it. + if (literalAfterLoop is not null) + { + FindMode = FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive; + LiteralAfterLoop = literalAfterLoop; + _asciiLookups = new uint[1][]; + return; + } } /// Gets the selected mode for performing the next operation @@ -180,6 +196,9 @@ public RegexFindOptimizations(RegexTree tree, CultureInfo culture) /// The case-insensitivity of the 0th entry will always match the mode selected, but subsequent entries may not. public List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? FixedDistanceSets { get; } + /// When in literal after set loop node, gets the literal to search for and the RegexNode representing the leading loop. + public (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? LiteralAfterLoop { get; } + /// Try to advance to the next starting position that might be a location for a match. /// The text to search. /// The position in . This is updated with the found position. @@ -601,6 +620,54 @@ public bool TryFindNextStartingPosition(ReadOnlySpan textSpan, ref int pos return false; } + // There's a literal after a leading set loop. Find the literal, then walk backwards through the loop to find the starting position. + case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: + { + Debug.Assert(LiteralAfterLoop is not null); + (RegexNode loopNode, (char Char, string? String, char[]? Chars) literal) = LiteralAfterLoop.GetValueOrDefault(); + + Debug.Assert(loopNode.Type is RegexNode.Setloop or RegexNode.Setlazy or RegexNode.Setloopatomic); + Debug.Assert(loopNode.N == int.MaxValue); + + int startingPos = pos; + while (true) + { + ReadOnlySpan slice = textSpan.Slice(startingPos, end - startingPos); + + // Find the literal. If we can't find it, we're done searching. + int i = literal.String is not null ? slice.IndexOf(literal.String.AsSpan()) : + literal.Chars is not null ? slice.IndexOfAny(literal.Chars.AsSpan()) : + slice.IndexOf(literal.Char); + if (i < 0) + { + break; + } + + // We found the literal. Walk backwards from it finding as many matches as we can against the loop. + int prev = i; + while ((uint)--prev < (uint)slice.Length && RegexCharClass.CharInClass(slice[prev], loopNode.Str!, ref _asciiLookups![0])) ; + + // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, + // so we can start from after the last place the literal matched. + if ((i - prev - 1) < loopNode.M) + { + startingPos += i + 1; + continue; + } + + // We have a winner. The starting position is just after the last position that failed to match the loop. + // TODO: It'd be nice to be able to communicate literalPos as a place the matching engine can start matching + // after the loop, so that it doesn't need to re-match the loop. This might only be feasible for RegexCompiler + // and the source generator after we refactor them to generate a single Scan method rather than separate + // FindFirstChar / Go methods. + pos = startingPos + prev + 1; + return true; + } + + pos = end; + return false; + } + // Nothing special to look for. Just return true indicating this is a valid position to try to match. default: @@ -660,6 +727,9 @@ internal enum FindNextStartingPositionMode /// One or more sets at a fixed distance from the start of the pattern. At least the first set is case-insensitive. FixedSets_LeftToRight_CaseInsensitive, + /// A literal after a non-overlapping set loop at the start of the pattern. The literal is case-sensitive. + LiteralAfterLoop_LeftToRight_CaseSensitive, + /// Nothing to search for. Nop. NoSearch, } diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs index e915634b69575..3f3f2808a01ef 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexInterpreter.cs @@ -1101,10 +1101,17 @@ protected override void Go() case RegexCode.UpdateBumpalong: // UpdateBumpalong should only exist in the code stream at such a point where the root // of the backtracking stack contains the runtextpos from the start of this Go call. Replace - // that tracking value with the current runtextpos value. - runtrack![runtrack.Length - 1] = runtextpos; - advance = 0; - continue; + // that tracking value with the current runtextpos value if it's greater. + { + Debug.Assert(!_rightToLeft, "UpdateBumpalongs aren't added for RTL"); + ref int trackingpos = ref runtrack![runtrack.Length - 1]; + if (trackingpos < runtextpos) + { + trackingpos = runtextpos; + } + advance = 0; + continue; + } default: Debug.Fail($"Unimplemented state: {_operator:X8}"); diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs index ea696c6680a2a..121b9d1e4225b 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.cs @@ -227,6 +227,12 @@ private void MakeLoopAtomic() // to the minimum number of iterations, as they should end up matching as little as possible. Type += Oneloopatomic - Onelazy; N = M; + if (N == 0) + { + Type = Empty; + Str = null; + Ch = '\0'; + } break; default: @@ -362,8 +368,17 @@ internal RegexNode FinalOptimize() Debug.Assert(rootNode.Next is null); Debug.Assert(rootNode.ChildCount() == 1); - if ((Options & RegexOptions.RightToLeft) == 0) // only apply optimization when LTR to avoid needing additional code for the rarer RTL case + // Only apply optimization when LTR to avoid needing additional code for the much rarer RTL case. + // Also only apply these optimizations when not using NonBacktracking, as these optimizations are + // all about avoiding things that are impactful for the backtracking engines but nops for non-backtracking. + if ((Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) == 0) { + // Optimization: eliminate backtracking for loops. + // For any single-character loop (Oneloop, Notoneloop, Setloop), see if we can automatically convert + // that into its atomic counterpart (Oneloopatomic, Notoneloopatomic, Setloopatomic) based on what + // comes after it in the expression tree. + rootNode.FindAndMakeLoopsAtomic(); + // Optimization: backtracking removal at expression end. // If we find backtracking construct at the end of the regex, we can instead make it non-backtracking, // since nothing would ever backtrack into it anyway. Doing this then makes the construct available @@ -380,8 +395,11 @@ internal RegexNode FinalOptimize() // we can only consider unbounded loops, as to be able to start at the end of the loop we need the loop to have consumed all possible matches; // otherwise, you could end up with a pattern like "a{1,3}b" matching against "aaaabc", which should match, but if we pre-emptively stop consuming // after the first three a's and re-start from that position, we'll end up failing the match even though it should have succeeded. We can also - // apply this optimization to non-atomic loops. Even though backtracking could be necessary, such backtracking would be handled within the processing - // of a single starting position. + // apply this optimization to non-atomic loops: even though backtracking could be necessary, such backtracking would be handled within the processing + // of a single starting position. Lazy loops similarly benefit, as a failed match will result in exploring the exact same search space as with + // a greedy loop, just in the opposite order (and a successful match will overwrite the bumpalong position); we need to avoid atomic lazy loops, + // however, as they will only end up as a repeater for the minimum length and thus will effectively end up with a non-infinite upper bound, which + // we've already outlined is problematic. { RegexNode node = rootNode.Child(0); // skip implicit root capture node while (true) @@ -394,6 +412,7 @@ internal RegexNode FinalOptimize() continue; case Oneloop or Oneloopatomic or Notoneloop or Notoneloopatomic or Setloop or Setloopatomic when node.N == int.MaxValue: + case Onelazy or Notonelazy or Setlazy when node.N == int.MaxValue && !node.IsAtomicByParent(): RegexNode? parent = node.Next; if (parent != null && parent.Type == Concatenate) { @@ -422,16 +441,12 @@ internal RegexNode FinalOptimize() /// private void EliminateEndingBacktracking() { - if (!StackHelper.TryEnsureSufficientExecutionStack()) + if (!StackHelper.TryEnsureSufficientExecutionStack() || + (Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) != 0) { // If we can't recur further, just stop optimizing. - return; - } - - // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option - // is set we don't want to create atomic groups where they weren't explicitly authored. - if ((Options & RegexOptions.NonBacktracking) != 0) - { + // We haven't done the work to validate this is correct for RTL. + // And NonBacktracking doesn't support atomic groups and doesn't have backtracking to be eliminated. return; } @@ -444,12 +459,8 @@ private void EliminateEndingBacktracking() // {One/Notone/Set}loops can be upgraded to {One/Notone/Set}loopatomic nodes, e.g. [abc]* => (?>[abc]*). // And {One/Notone/Set}lazys can similarly be upgraded to be atomic, which really makes them into repeaters // or even empty nodes. - case Oneloop: - case Notoneloop: - case Setloop: - case Onelazy: - case Notonelazy: - case Setlazy: + case Oneloop or Notoneloop or Setloop: + case Onelazy or Notonelazy or Setlazy: node.MakeLoopAtomic(); break; @@ -460,7 +471,7 @@ private void EliminateEndingBacktracking() continue; // For Capture and Concatenate, we just recur into their last child (only child in the case - // of Capture). However, if the child is Alternate, Loop, and Lazyloop, we can also make the + // of Capture). However, if the child is an alternation or loop, we can also make the // node itself atomic by wrapping it in an Atomic node. Since we later check to see whether a // node is atomic based on its parent or grandparent, we don't bother wrapping such a node in // an Atomic one if its grandparent is already Atomic. @@ -468,7 +479,7 @@ private void EliminateEndingBacktracking() case Capture: case Concatenate: RegexNode existingChild = node.Child(node.ChildCount() - 1); - if ((existingChild.Type == Alternate || existingChild.Type == Loop || existingChild.Type == Lazyloop) && + if ((existingChild.Type is Alternate or Testref or Testgroup or Loop or Lazyloop) && (node.Next is null || node.Next.Type != Atomic)) // validate grandparent isn't atomic { var atomic = new RegexNode(Atomic, existingChild.Options); @@ -479,23 +490,47 @@ private void EliminateEndingBacktracking() continue; // For alternate, we can recur into each branch separately. We use this iteration for the first branch. + // Conditionals are just like alternations in this regard. // e.g. abc*|def* => ab(?>c*)|de(?>f*) case Alternate: + case Testref: + case Testgroup: { int branches = node.ChildCount(); for (int i = 1; i < branches; i++) { node.Child(i).EliminateEndingBacktracking(); } + + if (node.Type != Testgroup) // ReduceTestgroup will have already applied ending backtracking removal + { + node = node.Child(0); + continue; + } } - node = node.Child(0); - continue; + break; - // For Loop, we search to see if there's a viable last expression, and iff there - // is we recur into processing it. + // For {Lazy}Loop, we search to see if there's a viable last expression, and iff there + // is we recur into processing it. Also, as with the single-char lazy loops, LazyLoop + // can have its max iteration count dropped to its min iteration count, as there's no + // reason for it to match more than the minimal at the end; that in turn makes it a + // repeater, which results in better code generation. // e.g. (?:abc*)* => (?:ab(?>c*))* + // e.g. (abc*?)+? => (ab){1} + case Lazyloop: + node.N = node.M; + goto case Loop; case Loop: { + if (node.N == 1) + { + // If the loop has a max iteration count of 1 (e.g. it's an optional node), + // there's no possibility for conflict between multiple iterations, so + // we can process it. + node = node.Child(0); + continue; + } + RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { @@ -571,6 +606,7 @@ internal RegexNode Reduce() => Group => ReduceGroup(), Loop or Lazyloop => ReduceLoops(), Prevent => ReducePrevent(), + Require => ReduceRequire(), Set or Setloop or Setloopatomic or Setlazy => ReduceSet(), Testgroup => ReduceTestgroup(), Testref => ReduceTestref(), @@ -581,17 +617,14 @@ internal RegexNode Reduce() => /// /// Simple optimization for a concatenation or alternation: /// - if the node has only one child, use it instead - /// - if the node has zero children, turn it into an empty with the specified empty type + /// - if the node has zero children, turn it into an empty with Nothing for an alternation or Empty for a concatenation /// - private RegexNode ReplaceNodeIfUnnecessary(int emptyTypeIfNoChildren) + private RegexNode ReplaceNodeIfUnnecessary() { - Debug.Assert( - (Type == Alternate && emptyTypeIfNoChildren == Nothing) || - (Type == Concatenate && emptyTypeIfNoChildren == Empty)); - + Debug.Assert(Type is Alternate or Concatenate); return ChildCount() switch { - 0 => new RegexNode(emptyTypeIfNoChildren, Options), + 0 => new RegexNode(Type == Alternate ? Nothing : Empty, Options), 1 => Child(0), _ => this, }; @@ -646,6 +679,12 @@ private RegexNode ReduceAtomic() switch (child.Type) { + // If the child is empty/nothing, there's nothing to be made atomic so the Atomic + // node can simply be removed. + case Empty: + case Nothing: + return child; + // If the child is already atomic, we can just remove the atomic node. case Oneloopatomic: case Notoneloopatomic: @@ -945,9 +984,19 @@ private RegexNode ReduceAlternation() default: ReduceSingleLetterAndNestedAlternations(); - RegexNode node = ReplaceNodeIfUnnecessary(Nothing); - node = ExtractCommonPrefixText(node); - node = ExtractCommonPrefixOneNotoneSet(node); + RegexNode node = ReplaceNodeIfUnnecessary(); + if (node.Type == Alternate) + { + node = ExtractCommonPrefixText(node); + if (node.Type == Alternate) + { + node = ExtractCommonPrefixOneNotoneSet(node); + if (node.Type == Alternate) + { + node = RemoveRedundantEmptiesAndNothings(node); + } + } + } return node; } @@ -1077,11 +1126,7 @@ void ReduceSingleLetterAndNestedAlternations() // e.g. \w12|\d34|\d56|\w78|\w90 => \w12|\d(?:34|56)|\w(?:78|90) static RegexNode ExtractCommonPrefixOneNotoneSet(RegexNode alternation) { - if (alternation.Type != Alternate) - { - return alternation; - } - + Debug.Assert(alternation.Type == Alternate); Debug.Assert(alternation.Children is List { Count: >= 2 }); var children = (List)alternation.Children; @@ -1167,9 +1212,45 @@ static RegexNode ExtractCommonPrefixOneNotoneSet(RegexNode alternation) children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } - // If we've reduced this alternation to just a single branch, return it. - // Otherwise, return the alternation. - return alternation.ChildCount() == 1 ? alternation.Child(0) : alternation; + return alternation.ReplaceNodeIfUnnecessary(); + } + + // Removes unnecessary Empty and Nothing nodes from the alternation. A Nothing will never + // match, so it can be removed entirely, and an Empty can be removed if there's a previous + // Empty in the alternation: it's an extreme case of just having a repeated branch in an + // alternation, and while we don't check for all duplicates, checking for empty is easy. + static RegexNode RemoveRedundantEmptiesAndNothings(RegexNode node) + { + Debug.Assert(node.Type == Alternate); + Debug.Assert(node.ChildCount() >= 2); + var children = (List)node.Children!; + + int i = 0, j = 0; + bool seenEmpty = false; + while (i < children.Count) + { + RegexNode child = children[i]; + switch (child.Type) + { + case Empty when !seenEmpty: + seenEmpty = true; + goto default; + + case Empty: + case Nothing: + i++; + break; + + default: + children[j] = children[i]; + i++; + j++; + break; + } + } + + children.RemoveRange(j, children.Count - j); + return node.ReplaceNodeIfUnnecessary(); } // Analyzes all the branches of the alternation for text that's identical at the beginning @@ -1183,11 +1264,7 @@ static RegexNode ExtractCommonPrefixOneNotoneSet(RegexNode alternation) // e.g. abc|ade => a(?bc|de) static RegexNode ExtractCommonPrefixText(RegexNode alternation) { - if (alternation.Type != Alternate) - { - return alternation; - } - + Debug.Assert(alternation.Type == Alternate); Debug.Assert(alternation.Children is List { Count: >= 2 }); var children = (List)alternation.Children; @@ -1283,20 +1360,11 @@ static RegexNode ExtractCommonPrefixText(RegexNode alternation) new RegexNode(One, startingNodeOptions, startingSpan[0]) : new RegexNode(Multi, startingNodeOptions, startingSpan.ToString()); var newAlternate = new RegexNode(Alternate, startingNodeOptions); - bool seenEmpty = false; for (int i = startingIndex; i < endingIndex; i++) { RegexNode branch = children[i]; ProcessOneOrMulti(branch.Type == Concatenate ? branch.Child(0) : branch, startingSpan); branch = branch.Reduce(); - if (branch.Type == Empty) - { - if (seenEmpty) - { - continue; - } - seenEmpty = true; - } newAlternate.AddChild(branch); // Remove the starting text from the one or multi node. This may end up changing @@ -1360,14 +1428,15 @@ static void ProcessOneOrMulti(RegexNode node, ReadOnlySpan startingSpan) /// public RegexNode? FindBranchOneOrMultiStart() { - RegexNode branch = this; - - if (branch.Type == Concatenate) - { - branch = branch.Child(0); - } + RegexNode branch = Type == Concatenate ? Child(0) : this; + return branch.Type is One or Multi ? branch : null; + } - return branch.Type == One || branch.Type == Multi ? branch : null; + /// Same as but also for Sets. + public RegexNode? FindBranchOneMultiOrSetStart() + { + RegexNode branch = Type == Concatenate ? Child(0) : this; + return branch.Type is One or Multi or Set ? branch : null; } /// Gets the character that begins a One or Multi. @@ -1379,45 +1448,39 @@ public char FirstCharOfOneOrMulti() } /// Finds the guaranteed beginning character of the node, or null if none exists. - public char? FindStartingCharacter() + public (char Char, string? String)? FindStartingCharacterOrString() { RegexNode? node = this; while (true) { - if (node is null || (node.Options & RegexOptions.RightToLeft) != 0) - { - return null; - } - - char c; - switch (node.Type) + if (node is not null && (node.Options & RegexOptions.RightToLeft) == 0) { - case One: - case Oneloop or Oneloopatomic or Onelazy when node.M > 0: - c = node.Ch; - break; - - case Multi: - c = node.Str![0]; - break; - - case Atomic: - case Concatenate: - case Capture: - case Group: - case Loop or Lazyloop when node.M > 0: - case Require: - node = node.Child(0); - continue; + switch (node.Type) + { + case One: + case Oneloop or Oneloopatomic or Onelazy when node.M > 0: + if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Ch)) + { + return (node.Ch, null); + } + break; - default: - return null; - } + case Multi: + if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Str.AsSpan())) + { + return ('\0', node.Str); + } + break; - if ((node.Options & RegexOptions.IgnoreCase) == 0 || - !RegexCharClass.ParticipatesInCaseConversion(c)) - { - return c; + case Atomic: + case Concatenate: + case Capture: + case Group: + case Loop or Lazyloop when node.M > 0: + case Require: + node = node.Child(0); + continue; + } } return null; @@ -1449,15 +1512,9 @@ private RegexNode ReduceConcatenation() // and also help to reduce catastrophic backtracking. ReduceConcatenationWithAdjacentLoops(); - // Now convert as many loops as possible to be atomic to avoid unnecessary backtracking. - if ((Options & RegexOptions.RightToLeft) == 0) - { - ReduceConcatenationWithAutoAtomic(); - } - // If the concatenation is now empty, return an empty node, or if it's got a single child, return that child. // Otherwise, return this. - return ReplaceNodeIfUnnecessary(Empty); + return ReplaceNodeIfUnnecessary(); } /// @@ -1660,21 +1717,43 @@ static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) /// to {one/notone/set}loopatomic nodes. Such changes avoid potential useless backtracking. /// e.g. A*B (where sets A and B don't overlap) => (?>A*)B. /// - private void ReduceConcatenationWithAutoAtomic() + private void FindAndMakeLoopsAtomic() { - // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option - // is set we don't want to create atomic groups where they weren't explicitly authored. - if ((Options & RegexOptions.NonBacktracking) != 0) + Debug.Assert((Options & RegexOptions.NonBacktracking) == 0, "Atomic groups aren't supported and don't help performance with NonBacktracking"); + + if (!StackHelper.TryEnsureSufficientExecutionStack()) { + // If we're too deep on the stack, give up optimizing further. return; } - Debug.Assert(Type == Concatenate); - Debug.Assert((Options & RegexOptions.RightToLeft) == 0); - Debug.Assert(Children is List); + if ((Options & RegexOptions.RightToLeft) != 0) + { + // RTL is so rare, we don't need to spend additional time/code optimizing for it. + return; + } + // For all node types that have children, recur into each of those children. + int childCount = ChildCount(); + if (childCount != 0) + { + for (int i = 0; i < childCount; i++) + { + Child(i).FindAndMakeLoopsAtomic(); + } + } + + // If this isn't a concatenation, nothing more to do. + if (Type is not Concatenate) + { + return; + } + + // This is a concatenation. Iterate through each pair of nodes in the concatenation seeing whether we can + // make the first node (or its right-most child) atomic based on the second node (or its left-most child). + Debug.Assert(Children is List); var children = (List)Children; - for (int i = 0; i < children.Count - 1; i++) + for (int i = 0; i < childCount - 1; i++) { ProcessNode(children[i], children[i + 1]); @@ -1717,21 +1796,25 @@ static void ProcessNode(RegexNode node, RegexNode subsequent) // If the node can be changed to atomic based on what comes after it, do so. switch (node.Type) { - case Oneloop when CanBeMadeAtomic(node, subsequent): - case Notoneloop when CanBeMadeAtomic(node, subsequent): - case Setloop when CanBeMadeAtomic(node, subsequent): + case Oneloop when CanBeMadeAtomic(node, subsequent, allowSubsequentIteration: true): + case Notoneloop when CanBeMadeAtomic(node, subsequent, allowSubsequentIteration: true): + case Setloop when CanBeMadeAtomic(node, subsequent, allowSubsequentIteration: true): node.MakeLoopAtomic(); break; case Alternate: + case Testref: + case Testgroup: // In the case of alternation, we can't change the alternation node itself // based on what comes after it (at least not with more complicated analysis // that factors in all branches together), but we can look at each individual // branch, and analyze ending loops in each branch individually to see if they // can be made atomic. Then if we do end up backtracking into the alternation, - // we at least won't need to backtrack into that loop. + // we at least won't need to backtrack into that loop. The same is true for + // conditionals, though we don't want to process the condition expression + // itself, as it's already considered atomic and handled as part of ReduceTestgroup. { int alternateBranches = node.ChildCount(); - for (int b = 0; b < alternateBranches; b++) + for (int b = node.Type == Testgroup ? 1 : 0; b < alternateBranches; b++) { ProcessNode(node.Child(b), subsequent); } @@ -1751,7 +1834,7 @@ static void ProcessNode(RegexNode node, RegexNode subsequent) { RegexNode node = this; - Debug.Assert(node.Type == Loop); + Debug.Assert(node.Type is Loop or Lazyloop); // Start by looking at the loop's sole child. node = node.Child(0); @@ -1772,7 +1855,7 @@ static void ProcessNode(RegexNode node, RegexNode subsequent) { int concatCount = node.ChildCount(); RegexNode lastConcatChild = node.Child(concatCount - 1); - if (CanBeMadeAtomic(lastConcatChild, node.Child(0))) + if (CanBeMadeAtomic(lastConcatChild, node.Child(0), allowSubsequentIteration: false)) { return lastConcatChild; } @@ -1782,13 +1865,36 @@ static void ProcessNode(RegexNode node, RegexNode subsequent) return null; } + /// Optimizations for positive lookaheads/behinds. + private RegexNode ReduceRequire() + { + Debug.Assert(Type == Require); + Debug.Assert(ChildCount() == 1); + + // A positive lookaround is a zero-width atomic assertion. + // As it's atomic, nothing will backtrack into it, and we can + // eliminate any ending backtracking from it. + EliminateEndingBacktracking(); + + // A positive lookaround wrapped around an empty is a nop, and can just + // be made into an empty. A developer typically doesn't write this, but + // rather it evolves due to optimizations resulting in empty. + if (Child(0).Type == Empty) + { + Type = Empty; + Children = null; + } + + return this; + } + /// Optimizations for negative lookaheads/behinds. private RegexNode ReducePrevent() { Debug.Assert(Type == Prevent); Debug.Assert(ChildCount() == 1); - // A negative lookahead/lookbehind wrapped around an empty child, i.e. (?!), is + // A negative lookaround wrapped around an empty child, i.e. (?!), is // sometimes used as a way to insert a guaranteed no-match into the expression. // We can reduce it to simply Nothing. if (Child(0).Type == Empty) @@ -1844,6 +1950,11 @@ private RegexNode ReduceTestgroup() ReplaceChild(0, condition.Child(0)); } + // We can also eliminate any ending backtracking in the condition, as the condition + // is considered to be a positive lookahead, which is an atomic zero-width assertion. + condition = Child(0); + condition.EliminateEndingBacktracking(); + return this; } @@ -1851,7 +1962,7 @@ private RegexNode ReduceTestgroup() /// Determines whether node can be switched to an atomic loop. Subsequent is the node /// immediately after 'node'. /// - private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent) + private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent, bool allowSubsequentIteration) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { @@ -1859,102 +1970,191 @@ private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent) return false; } - // Skip the successor down to the closest node that's guaranteed to follow it. - while (subsequent.ChildCount() > 0) + // In most case, we'll simply check the node against whatever subsequent is. However, in case + // subsequent ends up being a loop with a min bound of 0, we'll also need to evaluate the node + // against whatever comes after subsequent. In that case, we'll walk the tree to find the + // next subsequent, and we'll loop around against to perform the comparison again. + while (true) { - Debug.Assert(subsequent.Type != Group); - switch (subsequent.Type) + // Skip the successor down to the closest node that's guaranteed to follow it. + int childCount; + while ((childCount = subsequent.ChildCount()) > 0) { - case Concatenate: - case Capture: - case Atomic: - case Require when (subsequent.Options & RegexOptions.RightToLeft) == 0: // only lookaheads, not lookbehinds (represented as RTL Require nodes) - case Loop or Lazyloop when subsequent.M > 0: - subsequent = subsequent.Child(0); - continue; + Debug.Assert(subsequent.Type != Group); + switch (subsequent.Type) + { + case Concatenate: + case Capture: + case Atomic: + case Require when (subsequent.Options & RegexOptions.RightToLeft) == 0: // only lookaheads, not lookbehinds (represented as RTL Require nodes) + case Loop or Lazyloop when subsequent.M > 0: + subsequent = subsequent.Child(0); + continue; + } + + break; } - break; - } + // If the two nodes don't agree on options in any way, don't try to optimize them. + // TODO: Remove this once https://github.com/dotnet/runtime/issues/61048 is implemented. + if (node.Options != subsequent.Options) + { + return false; + } - // If the two nodes don't agree on options in any way, don't try to optimize them. - if (node.Options != subsequent.Options) - { - return false; - } + // If the successor is an alternation, all of its children need to be evaluated, since any of them + // could come after this node. If any of them fail the optimization, then the whole node fails. + // This applies to expression conditionals as well, as long as they have both a yes and a no branch (if there's + // only a yes branch, we'd need to also check whatever comes after the conditional). It doesn't apply to + // backreference conditionals, as the condition itself is unknown statically and could overlap with the + // loop being considered for atomicity. + switch (subsequent.Type) + { + case Alternate: + case Testgroup when childCount == 3: // condition, yes, and no branch + for (int i = 0; i < childCount; i++) + { + if (!CanBeMadeAtomic(node, subsequent.Child(i), allowSubsequentIteration)) + { + return false; + } + } + return true; + } - // If the successor is an alternation, all of its children need to be evaluated, since any of them - // could come after this node. If any of them fail the optimization, then the whole node fails. - if (subsequent.Type == Alternate) - { - int childCount = subsequent.ChildCount(); - for (int i = 0; i < childCount; i++) + // If this node is a {one/notone/set}loop, see if it overlaps with its successor in the concatenation. + // If it doesn't, then we can upgrade it to being a {one/notone/set}loopatomic. + // Doing so avoids unnecessary backtracking. + switch (node.Type) { - if (!CanBeMadeAtomic(node, subsequent.Child(i))) - { + case Oneloop: + switch (subsequent.Type) + { + case One when node.Ch != subsequent.Ch: + case Notone when node.Ch == subsequent.Ch: + case Set when !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): + case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: + case Notonelazy or Notoneloop or Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: + case Setlazy or Setloop or Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): + case Multi when node.Ch != subsequent.Str![0]: + case End: + case EndZ or Eol when node.Ch != '\n': + case Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): + case NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): + case ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): + case NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): + return true; + + case Onelazy or Oneloop or Oneloopatomic when subsequent.M == 0 && node.Ch != subsequent.Ch: + case Notonelazy or Notoneloop or Notoneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: + case Setlazy or Setloop or Setloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): + // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. + break; + + default: + return false; + } + break; + + case Notoneloop: + switch (subsequent.Type) + { + case One when node.Ch == subsequent.Ch: + case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: + case Multi when node.Ch == subsequent.Str![0]: + case End: + return true; + + case Onelazy or Oneloop or Oneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: + // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. + break; + + default: + return false; + } + break; + + case Setloop: + switch (subsequent.Type) + { + case One when !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): + case Set when !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): + case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): + case Setlazy or Setloop or Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): + case Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): + case End: + case EndZ or Eol when !RegexCharClass.CharInClass('\n', node.Str!): + case Boundary when node.Str == RegexCharClass.WordClass || node.Str == RegexCharClass.DigitClass: + case NonBoundary when node.Str == RegexCharClass.NotWordClass || node.Str == RegexCharClass.NotDigitClass: + case ECMABoundary when node.Str == RegexCharClass.ECMAWordClass || node.Str == RegexCharClass.ECMADigitClass: + case NonECMABoundary when node.Str == RegexCharClass.NotECMAWordClass || node.Str == RegexCharClass.NotDigitClass: + return true; + + case Onelazy or Oneloop or Oneloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): + case Setlazy or Setloop or Setloopatomic when subsequent.M == 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): + // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. + break; + + default: + return false; + } + break; + + default: return false; - } } - return true; - } + // We only get here if the node could be made atomic based on subsequent but subsequent has a lower bound of zero + // and thus we need to move subsequent to be the next node in sequence and loop around to try again. + Debug.Assert(subsequent.Type is Oneloop or Oneloopatomic or Onelazy or Notoneloop or Notoneloopatomic or Notonelazy or Setloop or Setloopatomic or Setlazy); + Debug.Assert(subsequent.M == 0); + if (!allowSubsequentIteration) + { + return false; + } - // If this node is a {one/notone/set}loop, see if it overlaps with its successor in the concatenation. - // If it doesn't, then we can upgrade it to being a {one/notone/set}loopatomic. - // Doing so avoids unnecessary backtracking. - switch (node.Type) - { - case Oneloop: - switch (subsequent.Type) + // To be conservative, we only walk up through a very limited set of constructs (even though we may have walked + // down through more, like loops), looking for the next concatenation that we're not at the end of, at + // which point subsequent becomes whatever node is next in that concatenation. + while (true) + { + RegexNode? parent = subsequent.Next; + switch (parent?.Type) { - case One when node.Ch != subsequent.Ch: - case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: - case Notone when node.Ch == subsequent.Ch: - case Notonelazy or Notoneloop or Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: - case Multi when node.Ch != subsequent.Str![0]: - case Set when !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): - case Setlazy or Setloop or Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): - case End: - case EndZ or Eol when node.Ch != '\n': - case Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): - case NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): - case ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): - case NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): - return true; - } - break; + case Atomic: + case Alternate: + case Capture: + subsequent = parent; + continue; - case Notoneloop: - switch (subsequent.Type) - { - case One when node.Ch == subsequent.Ch: - case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: - case Multi when node.Ch == subsequent.Str![0]: - case End: - return true; - } - break; + case Concatenate: + var peers = (List)parent.Children!; + int currentIndex = peers.IndexOf(subsequent); + Debug.Assert(currentIndex >= 0, "Node should have been in its parent's child list"); + if (currentIndex + 1 == peers.Count) + { + subsequent = parent; + continue; + } + else + { + subsequent = peers[currentIndex + 1]; + break; + } - case Setloop: - switch (subsequent.Type) - { - case One when !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): - case Onelazy or Oneloop or Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): - case Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): - case Set when !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): - case Setlazy or Setloop or Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): - case End: - case EndZ or Eol when !RegexCharClass.CharInClass('\n', node.Str!): - case Boundary when node.Str == RegexCharClass.WordClass || node.Str == RegexCharClass.DigitClass: - case NonBoundary when node.Str == RegexCharClass.NotWordClass || node.Str == RegexCharClass.NotDigitClass: - case ECMABoundary when node.Str == RegexCharClass.ECMAWordClass || node.Str == RegexCharClass.ECMADigitClass: - case NonECMABoundary when node.Str == RegexCharClass.NotECMAWordClass || node.Str == RegexCharClass.NotDigitClass: + case null: + // If we hit the root, we're at the end of the expression, at which point nothing could backtrack + // in and we can declare success. return true; + + default: + // Anything else, we don't know what to do, so we have to assume it could conflict with the loop. + return false; } + break; + } } - - return false; } /// Computes a min bound on the required length of any string that could possibly match. @@ -2012,6 +2212,14 @@ public int ComputeMinLength() return min; } + case Testref: + // Minimum of its yes and no branches. The backreference doesn't add to the length. + return Math.Min(Child(0).ComputeMinLength(), Child(1).ComputeMinLength()); + + case Testgroup: + // Minimum of its yes and no branches. The condition is a zero-width assertion. + return Math.Min(Child(1).ComputeMinLength(), Child(2).ComputeMinLength()); + case Concatenate: // The sum of all of the concatenation's children. { @@ -2054,8 +2262,6 @@ public int ComputeMinLength() // a different structure, as they can't be added as part of a concatenation, since they overlap // with what comes after. case Ref: - case Testgroup: - case Testref: // Constructs requiring data at runtime from the matching pattern can't influence min length. return 0; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs index 070acc36abcc4..02b4f1408e679 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexParser.cs @@ -252,7 +252,7 @@ private void Reset(RegexOptions options) private RegexNode ScanRegex() { - char ch = '@'; // nonspecial ch, means at beginning + char ch; bool isQuantifier = false; StartGroup(new RegexNode(RegexNode.Capture, _options, 0, -1)); @@ -563,7 +563,7 @@ node.M is not (0 or RegexReplacement.LeftPortion or RegexReplacement.RightPortio */ private RegexCharClass? ScanCharClass(bool caseInsensitive, bool scanOnly) { - char ch = '\0'; + char ch; char chPrev = '\0'; bool inRange = false; bool firstChar = true; @@ -2346,5 +2346,27 @@ private RegexParseException MakeException(RegexParseError error, string message) /// Number of characters to the right of the current parsing position. private int CharsRight() => _pattern.Length - _currentPos; + + /// Gets group name from its number. + internal static string GroupNameFromNumber(Hashtable? caps, string[]? capslist, int capsize, int i) + { + if (capslist is null) + { + if ((uint)i < (uint)capsize) + { + return ((uint)i).ToString(); + } + } + else + { + if ((caps is null || caps.TryGetValue(i, out i)) && + (uint)i < (uint)capslist.Length) + { + return capslist[i]; + } + } + + return string.Empty; + } } } diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexPrefixAnalyzer.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexPrefixAnalyzer.cs index 22a2abba1946a..ceabbef99af6c 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexPrefixAnalyzer.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexPrefixAnalyzer.cs @@ -79,55 +79,6 @@ static bool Process(RegexNode node, ref ValueStringBuilder vsb) return !rtl; } - // Alternation: find a string that's a shared prefix of all branches - case RegexNode.Alternate: - { - int childCount = node.ChildCount(); - - // Store the initial branch into the target builder - int initialLength = vsb.Length; - bool keepExploring = Process(node.Child(0), ref vsb); - int addedLength = vsb.Length - initialLength; - - // Then explore the rest of the branches, finding the length - // a prefix they all share in common with the initial branch. - if (addedLength != 0) - { - var alternateSb = new ValueStringBuilder(64); - - // Process each branch. If we reach a point where we've proven there's - // no overlap, we can bail early. - for (int i = 1; i < childCount && addedLength != 0; i++) - { - alternateSb.Length = 0; - - // Process the branch. We want to keep exploring after this alternation, - // but we can't if either this branch doesn't allow for it or if the prefix - // supplied by this branch doesn't entirely match all the previous ones. - keepExploring &= Process(node.Child(i), ref alternateSb); - keepExploring &= alternateSb.Length == addedLength; - - addedLength = Math.Min(addedLength, alternateSb.Length); - for (int j = 0; j < addedLength; j++) - { - if (vsb[initialLength + j] != alternateSb[j]) - { - addedLength = j; - keepExploring = false; - break; - } - } - } - - alternateSb.Dispose(); - - // Then cull back on what was added based on the other branches. - vsb.Length = initialLength + addedLength; - } - - return !rtl && keepExploring; - } - // One character case RegexNode.One when (node.Options & RegexOptions.IgnoreCase) == 0: vsb.Append(node.Ch); @@ -532,11 +483,13 @@ static bool TryFindFixedSets(RegexNode node, List<(char[]? Chars, string Set, in } } - // Computes a character class for the first character in tree. This uses a more robust algorithm - // than is used by TryFindFixedLiterals and thus can find starting sets it couldn't. For example, - // fixed literals won't find the starting set for a*b, as the a isn't guaranteed and the b is at a - // variable position, but this will find [ab] as it's instead looking for anything that under any - // circumstance could possibly start a match. + /// + /// Computes a character class for the first character in tree. This uses a more robust algorithm + /// than is used by TryFindFixedLiterals and thus can find starting sets it couldn't. For example, + /// fixed literals won't find the starting set for a*b, as the a isn't guaranteed and the b is at a + /// variable position, but this will find [ab] as it's instead looking for anything that under any + /// circumstance could possibly start a match. + /// public static (string CharClass, bool CaseInsensitive)? FindFirstCharClass(RegexTree tree, CultureInfo culture) { var s = new RegexPrefixAnalyzer(stackalloc int[StackBufferSize]); @@ -556,6 +509,90 @@ public static (string CharClass, bool CaseInsensitive)? FindFirstCharClass(Regex return (fc.GetFirstChars(), fc.CaseInsensitive); } + /// + /// Analyzes the pattern for a leading set loop followed by a non-overlapping literal. If such a pattern is found, an implementation + /// can search for the literal and then walk backward through all matches for the loop until the beginning is found. + /// + public static (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? FindLiteralFollowingLeadingLoop(RegexTree tree) + { + RegexNode node = tree.Root; + if ((node.Options & RegexOptions.RightToLeft) != 0) + { + // As a simplification, ignore RightToLeft. + return null; + } + + // Find the first concatenation. + while ((node.Type is RegexNode.Atomic or RegexNode.Capture) || (node.Type is RegexNode.Loop or RegexNode.Lazyloop && node.M > 0)) + { + node = node.Child(0); + } + if (node.Type != RegexNode.Concatenate) + { + return null; + } + + // Bail if the first node isn't a set loop. We treat any kind of set loop (Setloop, Setloopatomic, and Setlazy) + // the same because of two important constraints: the loop must not have an upper bound, and the literal we look + // for immediately following it must not overlap. With those constraints, all three of these kinds of loops will + // end up having the same semantics; in fact, if atomic optimizations are used, we will have converted Setloop + // into a Setloopatomic (but those optimizations are disabled for NonBacktracking in general). This + // could also be made to support Oneloopatomic and Notoneloopatomic, but the scenarios for that are rare. + Debug.Assert(node.ChildCount() >= 2); + RegexNode firstChild = node.Child(0); + if (firstChild.Type is not (RegexNode.Setloop or RegexNode.Setloopatomic or RegexNode.Setlazy) || firstChild.N != int.MaxValue) + { + return null; + } + + // Get the subsequent node. An UpdateBumpalong may have been added as an optimization, but it doesn't have an + // impact on semantics and we can skip it. + RegexNode nextChild = node.Child(1); + if (nextChild.Type == RegexNode.UpdateBumpalong) + { + if (node.ChildCount() == 2) + { + return null; + } + nextChild = node.Child(2); + } + + // If the subsequent node is a literal, we need to ensure it doesn't overlap with the prior set. + // For simplicity, we also want to ensure they're both case-sensitive. If there's no overlap + // and they're both case-sensitive, we have a winner. + if (((firstChild.Options | nextChild.Options) & RegexOptions.IgnoreCase) == 0) + { + switch (nextChild.Type) + { + case RegexNode.One when !RegexCharClass.CharInClass(nextChild.Ch, firstChild.Str!): + return (firstChild, (nextChild.Ch, null, null)); + + case RegexNode.Multi when !RegexCharClass.CharInClass(nextChild.Str![0], firstChild.Str!): + return (firstChild, ('\0', nextChild.Str, null)); + + case RegexNode.Set when !RegexCharClass.IsNegated(nextChild.Str!): + Span chars = stackalloc char[5]; // maximum number of chars optimized by IndexOfAny + chars = chars.Slice(0, RegexCharClass.GetSetChars(nextChild.Str!, chars)); + if (!chars.IsEmpty) + { + foreach (char c in chars) + { + if (RegexCharClass.CharInClass(c, firstChild.Str!)) + { + return null; + } + } + + return (firstChild, ('\0', null, chars.ToArray())); + } + break; + } + } + + // Otherwise, we couldn't find the pattern of an atomic set loop followed by a literal. + return null; + } + /// Takes a RegexTree and computes the leading anchor that it encounters. public static int FindLeadingAnchor(RegexTree tree) { diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs index aaf1d57a4eae0..1448ed8c6e580 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs @@ -114,7 +114,7 @@ public IEnumerable EnumerateTargetStates(int sourceState, S input, uint con Stack todo = new(); todo.Push(transition._second); todo.Push(transition._first); - while (todo.TryPop(out Transition? top)) + while (todo.TryPop(out _)) { switch (transition._kind) { diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs index 6c06ebf1b0490..3deec76d1528b 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.KnownPattern.Tests.cs @@ -1211,150 +1211,184 @@ public async Task Blog_Levithan_BalancingGroups_WordLengthIncreases(RegexEngine // These patterns come from real-world customer usages // + public static IEnumerable RealWorld_ExtractResourceUri_MemberData() + { + foreach (RegexEngine engine in RegexHelpers.AvailableEngines) + { + yield return new object[] { engine, "https://foo.com:443/bar/17/groups/0ad1/providers/Network/public/4e-ip?version=16", "Network/public/4e-ip" }; + yield return new object[] { engine, "ftp://443/notproviders/17/groups/0ad1/providers/Network/public/4e-ip?version=16", "Network/public/4e-ip" }; + yield return new object[] { engine, "ftp://443/providersnot/17/groups/0ad1/providers/Network/public/4e-ip?version=16", "Network/public/4e-ip" }; + } + } + [Theory] - [InlineData("https://foo.com:443/bar/17/groups/0ad1/providers/Network/public/4e-ip?version=16", "Network/public/4e-ip")] - [InlineData("ftp://443/notproviders/17/groups/0ad1/providers/Network/public/4e-ip?version=16", "Network/public/4e-ip")] - [InlineData("ftp://443/providersnot/17/groups/0ad1/providers/Network/public/4e-ip?version=16", "Network/public/4e-ip")] - public async Task RealWorld_ExtractResourceUri(string url, string expected) + [MemberData(nameof(RealWorld_ExtractResourceUri_MemberData))] + public async Task RealWorld_ExtractResourceUri(RegexEngine engine, string url, string expected) + { + Regex r = await RegexHelpers.GetRegexAsync(engine, @"/providers/(.+?)\?"); + Match m = r.Match(url); + Assert.True(m.Success); + if (!RegexHelpers.IsNonBacktracking(engine)) + { + Assert.Equal(2, m.Groups.Count); + Assert.Equal(expected, m.Groups[1].Value); + } + } + + public static IEnumerable RealWorld_IsValidCSharpName_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { - Regex r = await RegexHelpers.GetRegexAsync(engine, @"/providers/(.+?)\?"); - Match m = r.Match(url); - Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(2, m.Groups.Count); - Assert.Equal(expected, m.Groups[1].Value); - } + yield return new object[] { engine, "IsValidCSharpName", true }; + yield return new object[] { engine, "_IsValidCSharpName", true }; + yield return new object[] { engine, "__", true }; + yield return new object[] { engine, "a\u2169", true }; // \u2169 is in {Nl} + yield return new object[] { engine, "\u2169b", true }; // \u2169 is in {Nl} + yield return new object[] { engine, "a\u0600", true }; // \u0600 is in {Cf} + yield return new object[] { engine, "\u0600b", false }; // \u0600 is in {Cf} + yield return new object[] { engine, "a\u0300", true }; // \u0300 is in {Mn} + yield return new object[] { engine, "\u0300b", false }; // \u0300 is in {Mn} + yield return new object[] { engine, "https://foo.com:443/bar/17/groups/0ad1/providers/Network/public/4e-ip?version=16", false }; + yield return new object[] { engine, "david.jones@proseware.com", false }; + yield return new object[] { engine, "~david", false }; + yield return new object[] { engine, "david~", false }; } } [Theory] - [InlineData("IsValidCSharpName", true)] - [InlineData("_IsValidCSharpName", true)] - [InlineData("__", true)] - [InlineData("a\u2169", true)] // \u2169 is in {Nl} - [InlineData("\u2169b", true)] // \u2169 is in {Nl} - [InlineData("a\u0600", true)] // \u0600 is in {Cf} - [InlineData("\u0600b", false)] // \u0600 is in {Cf} - [InlineData("a\u0300", true)] // \u0300 is in {Mn} - [InlineData("\u0300b", false)] // \u0300 is in {Mn} - [InlineData("https://foo.com:443/bar/17/groups/0ad1/providers/Network/public/4e-ip?version=16", false)] - [InlineData("david.jones@proseware.com", false)] - [InlineData("~david", false)] - [InlineData("david~", false)] - public async Task RealWorld_IsValidCSharpName(string value, bool isExpectedMatch) + [MemberData(nameof(RealWorld_IsValidCSharpName_MemberData))] + public async Task RealWorld_IsValidCSharpName(RegexEngine engine, string value, bool isExpectedMatch) { const string StartCharacterRegex = @"_|[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}]"; const string PartCharactersRegex = @"[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]"; - const string IdentifierRegex = @"^(" + StartCharacterRegex + ")(" + PartCharactersRegex + ")*$"; + Regex r = await RegexHelpers.GetRegexAsync(engine, IdentifierRegex); + Assert.Equal(isExpectedMatch, r.IsMatch(value)); + } + + public static IEnumerable RealWorld_IsCommentLine_MemberData() + { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { - Regex r = await RegexHelpers.GetRegexAsync(engine, IdentifierRegex); - Assert.Equal(isExpectedMatch, r.IsMatch(value)); + yield return new object[] { engine, "; this is a comment", true }; + yield return new object[] { engine, "\t; so is this", true }; + yield return new object[] { engine, " ; and this", true }; + yield return new object[] { engine, ";", true }; + yield return new object[] { engine, ";comment\nNotThisBecauseOfNewLine", false }; + yield return new object[] { engine, "-;not a comment", false }; } } [Theory] - [InlineData("; this is a comment", true)] - [InlineData("\t; so is this", true)] - [InlineData(" ; and this", true)] - [InlineData(";", true)] - [InlineData(";comment\nNotThisBecauseOfNewLine", false)] - [InlineData("-;not a comment", false)] - public async Task RealWorld_IsCommentLine(string value, bool isExpectedMatch) + [MemberData(nameof(RealWorld_IsCommentLine_MemberData))] + public async Task RealWorld_IsCommentLine(RegexEngine engine, string value, bool isExpectedMatch) { const string CommentLineRegex = @"^\s*;\s*(.*?)\s*$"; + Regex r = await RegexHelpers.GetRegexAsync(engine, CommentLineRegex); + Assert.Equal(isExpectedMatch, r.IsMatch(value)); + } + + public static IEnumerable RealWorld_IsSectionLine_MemberData() + { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { - Regex r = await RegexHelpers.GetRegexAsync(engine, CommentLineRegex); - Assert.Equal(isExpectedMatch, r.IsMatch(value)); + yield return new object[] { engine, "[ThisIsASection]", true }; + yield return new object[] { engine, " [ThisIsASection] ", true }; + yield return new object[] { engine, "\t[ThisIs\\ASection]\t", true }; + yield return new object[] { engine, "\t[This.Is:(A+Section)]\t", true }; + yield return new object[] { engine, "[This Is Not]", false }; + yield return new object[] { engine, "This is not[]", false }; + yield return new object[] { engine, "[Nor This]/", false }; } } [Theory] - [InlineData("[ThisIsASection]", true)] - [InlineData(" [ThisIsASection] ", true)] - [InlineData("\t[ThisIs\\ASection]\t", true)] - [InlineData("\t[This.Is:(A+Section)]\t", true)] - [InlineData("[This Is Not]", false)] - [InlineData("This is not[]", false)] - [InlineData("[Nor This]/", false)] - public async Task RealWorld_IsSectionLine(string value, bool isExpectedMatch) + [MemberData(nameof(RealWorld_IsSectionLine_MemberData))] + public async Task RealWorld_IsSectionLine(RegexEngine engine, string value, bool isExpectedMatch) { const string SectionLineRegex = @"^\s*\[([\w\.\-\+:\/\(\)\\]+)\]\s*$"; + Regex r = await RegexHelpers.GetRegexAsync(engine, SectionLineRegex); + Assert.Equal(isExpectedMatch, r.IsMatch(value)); + } + + public static IEnumerable RealWorld_ValueParse_MemberData() + { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { - Regex r = await RegexHelpers.GetRegexAsync(engine, SectionLineRegex); - Assert.Equal(isExpectedMatch, r.IsMatch(value)); + yield return new object[] { engine, "Jiri: 10", "10" }; + yield return new object[] { engine, "jiri: -10.01", "-10.01" }; + yield return new object[] { engine, "jiri: .-22", "-22" }; + yield return new object[] { engine, "jiri: .-22.3", "-22.3" }; + yield return new object[] { engine, "foo15.0", "15.0" }; + yield return new object[] { engine, "foo15", "15" }; + yield return new object[] { engine, "foo16bar", "16" }; + yield return new object[] { engine, "fds:-4", "-4" }; + yield return new object[] { engine, "dsa:-20.04", "-20.04" }; + yield return new object[] { engine, "dsa:15.a", "15" }; } } [Theory] - [InlineData("Jiri: 10", "10")] - [InlineData("jiri: -10.01", "-10.01")] - [InlineData("jiri: .-22", "-22")] - [InlineData("jiri: .-22.3", "-22.3")] - [InlineData("foo15.0", "15.0")] - [InlineData("foo15", "15")] - [InlineData("foo16bar", "16")] - [InlineData("fds:-4", "-4")] - [InlineData("dsa:-20.04", "-20.04")] - [InlineData("dsa:15.a", "15")] - public async Task RealWorld_ValueParse(string value, string expected) + [MemberData(nameof(RealWorld_ValueParse_MemberData))] + public async Task RealWorld_ValueParse(RegexEngine engine, string value, string expected) + { + Regex r = await RegexHelpers.GetRegexAsync(engine, @"(?-?\d+(\.\d+)?)"); + Match m = r.Match(value); + Assert.True(m.Success); + if (!RegexHelpers.IsNonBacktracking(engine)) // named capture groups unsupported + { + Assert.Equal(expected, m.Groups["value"].Value); + } + } + + public static IEnumerable RealWorld_FirebirdVersionString_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { - Regex r = await RegexHelpers.GetRegexAsync(engine, @"(?-?\d+(\.\d+)?)"); - Match m = r.Match(value); - Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) // named capture groups unsupported - { - Assert.Equal(expected, m.Groups["value"].Value); - } + yield return new object[] { engine, "WI-T4.0.0.1963 Firebird 4.0 Beta 2", "4.0.0.1963" }; + yield return new object[] { engine, "WI-V3.0.5.33220 Firebird 3.0", "3.0.5.33220" }; } } [Theory] - [InlineData("WI-T4.0.0.1963 Firebird 4.0 Beta 2", "4.0.0.1963")] - [InlineData("WI-V3.0.5.33220 Firebird 3.0", "3.0.5.33220")] - public async Task RealWorld_FirebirdVersionString(string value, string expected) + [MemberData(nameof(RealWorld_FirebirdVersionString_MemberData))] + public async Task RealWorld_FirebirdVersionString(RegexEngine engine, string value, string expected) + { + Regex r = await RegexHelpers.GetRegexAsync(engine, @"\w{2}-\w(\d+\.\d+\.\d+\.\d+)"); + Match m = r.Match(value); + Assert.True(m.Success); + if (!RegexHelpers.IsNonBacktracking(engine)) + { + Assert.Equal(expected, m.Groups[1].Value); + } + } + + public static IEnumerable RealWorld_ExternalEntryPoint_MemberData() { foreach (RegexEngine engine in RegexHelpers.AvailableEngines) { - Regex r = await RegexHelpers.GetRegexAsync(engine, @"\w{2}-\w(\d+\.\d+\.\d+\.\d+)"); - Match m = r.Match(value); - Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) - { - Assert.Equal(expected, m.Groups[1].Value); - } + yield return new object[] { engine, "Foo!Bar.M", "Foo", "Bar", "M" }; + yield return new object[] { engine, "Foo!Bar.A.B.C", "Foo", "Bar.A.B", "C" }; + yield return new object[] { engine, "Foo1.Foo2.Foo!Bar.A.B.C", "Foo1.Foo2.Foo", "Bar.A.B", "C" }; + yield return new object[] { engine, @"Foo1\Foo2.Foo!Bar.A.B.C", @"Foo1\Foo2.Foo", "Bar.A.B", "C" }; } } [Theory] - [InlineData("Foo!Bar.M", "Foo", "Bar", "M")] - [InlineData("Foo!Bar.A.B.C", "Foo", "Bar.A.B", "C")] - [InlineData("Foo1.Foo2.Foo!Bar.A.B.C", "Foo1.Foo2.Foo", "Bar.A.B", "C")] - [InlineData(@"Foo1\Foo2.Foo!Bar.A.B.C", @"Foo1\Foo2.Foo", "Bar.A.B", "C")] - public async Task RealWorld_ExternalEntryPoint(string value, string a, string b, string c) + [MemberData(nameof(RealWorld_ExternalEntryPoint_MemberData))] + public async Task RealWorld_ExternalEntryPoint(RegexEngine engine, string value, string a, string b, string c) { - foreach (RegexEngine engine in RegexHelpers.AvailableEngines) + Regex r = await RegexHelpers.GetRegexAsync(engine, @"^(.+)!(.+)\.([^.]+)$"); + Match m = r.Match(value); + Assert.True(m.Success); + if (!RegexHelpers.IsNonBacktracking(engine)) // subcaptures aren't supported { - Regex r = await RegexHelpers.GetRegexAsync(engine, @"^(.+)!(.+)\.([^.]+)$"); - Match m = r.Match(value); - Assert.True(m.Success); - if (!RegexHelpers.IsNonBacktracking(engine)) // subcaptures aren't supported - { - Assert.Equal(a, m.Groups[1].Value); - Assert.Equal(b, m.Groups[2].Value); - Assert.Equal(c, m.Groups[3].Value); - } + Assert.Equal(a, m.Groups[1].Value); + Assert.Equal(b, m.Groups[2].Value); + Assert.Equal(c, m.Groups[3].Value); } } diff --git a/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs index 97f98cd991132..8fd3ea6e32231 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs @@ -58,9 +58,15 @@ public static IEnumerable Match_MemberData() yield return (@"a{1,3}b", "abc", RegexOptions.None, 0, 3, true, "ab"); yield return (@"a{1,3}b", "aaabc", RegexOptions.None, 0, 5, true, "aaab"); yield return (@"a{1,3}b", "aaaabc", RegexOptions.None, 0, 6, true, "aaab"); + yield return (@"a{1,3}?b", "bc", RegexOptions.None, 0, 2, false, string.Empty); + yield return (@"a{1,3}?b", "abc", RegexOptions.None, 0, 3, true, "ab"); + yield return (@"a{1,3}?b", "aaabc", RegexOptions.None, 0, 5, true, "aaab"); + yield return (@"a{1,3}?b", "aaaabc", RegexOptions.None, 0, 6, true, "aaab"); yield return (@"a{2,}b", "abc", RegexOptions.None, 0, 3, false, string.Empty); yield return (@"a{2,}b", "aabc", RegexOptions.None, 0, 4, true, "aab"); + yield return (@"a{2,}?b", "abc", RegexOptions.None, 0, 3, false, string.Empty); + yield return (@"a{2,}?b", "aabc", RegexOptions.None, 0, 4, true, "aab"); // {,n} is treated as a literal rather than {0,n} as it should be yield return (@"a{,3}b", "a{,3}bc", RegexOptions.None, 0, 6, true, "a{,3}b"); @@ -68,6 +74,7 @@ public static IEnumerable Match_MemberData() // Using [a-z], \s, \w: Actual - "([a-zA-Z]+)\\s(\\w+)" yield return (@"([a-zA-Z]+)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau"); + yield return (@"([a-zA-Z]+?)\s(\w+)", "David Bau", RegexOptions.None, 0, 9, true, "David Bau"); // \\S, \\d, \\D, \\W: Actual - "(\\S+):\\W(\\d+)\\s(\\D+)" yield return (@"(\S+):\W(\d+)\s(\D+)", "Price: 5 dollars", RegexOptions.None, 0, 16, true, "Price: 5 dollars"); @@ -107,6 +114,7 @@ public static IEnumerable Match_MemberData() if (!RegexHelpers.IsNonBacktracking(engine)) { + // Atomic greedy yield return (Case("(?>[0-9]+)abc"), "abc12345abc", options, 3, 8, true, "12345abc"); yield return (Case("(?>(?>[0-9]+))abc"), "abc12345abc", options, 3, 8, true, "12345abc"); yield return (Case("(?>[0-9]*)abc"), "abc12345abc", options, 3, 8, true, "12345abc"); @@ -116,8 +124,21 @@ public static IEnumerable Match_MemberData() yield return (Case("(?>a+)123"), "aa1234", options, 0, 5, true, "aa123"); yield return (Case("(?>a*)123"), "aa1234", options, 0, 5, true, "aa123"); yield return (Case("(?>(?>a*))123"), "aa1234", options, 0, 5, true, "aa123"); - yield return (Case("(?>a+?)a"), "aaaaa", options, 0, 2, true, "aa"); - yield return (Case("(?>a*?)a"), "aaaaa", options, 0, 1, true, "a"); + yield return (Case("(?>a{2,})b"), "aaab", options, 0, 4, true, "aaab"); + + // Atomic lazy + yield return (Case("(?>[0-9]+?)abc"), "abc12345abc", options, 3, 8, true, "5abc"); + yield return (Case("(?>(?>[0-9]+?))abc"), "abc12345abc", options, 3, 8, true, "5abc"); + yield return (Case("(?>[0-9]*?)abc"), "abc12345abc", options, 3, 8, true, "abc"); + yield return (Case("(?>[^z]+?)z"), "zzzzxyxyxyz123", options, 4, 9, true, "yz"); + yield return (Case("(?>(?>[^z]+?))z"), "zzzzxyxyxyz123", options, 4, 9, true, "yz"); + yield return (Case("(?>[^z]*?)z123"), "zzzzxyxyxyz123", options, 4, 10, true, "z123"); + yield return (Case("(?>a+?)123"), "aa1234", options, 0, 5, true, "a123"); + yield return (Case("(?>a*?)123"), "aa1234", options, 0, 5, true, "123"); + yield return (Case("(?>(?>a*?))123"), "aa1234", options, 0, 5, true, "123"); + yield return (Case("(?>a{2,}?)b"), "aaab", options, 0, 4, true, "aab"); + + // Alternations yield return (Case("(?>hi|hello|hey)hi"), "hellohi", options, 0, 0, false, string.Empty); yield return (Case("(?>hi|hello|hey)hi"), "hihi", options, 0, 4, true, "hihi"); } @@ -143,8 +164,52 @@ public static IEnumerable Match_MemberData() yield return (@"(\w+)@\w+.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); yield return (@"((\w+))@\w+.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); yield return (@"(\w+)c@\w+.com", "abc@def.comabcdef", RegexOptions.None, 0, 17, true, "abc@def.com"); + yield return (@"\w+://\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); + yield return (@"\w+[:|$*&]//\w+\.\w+", "test https://dot.net test", RegexOptions.None, 0, 25, true, "https://dot.net"); + yield return (@".+a", "baa", RegexOptions.None, 0, 3, true, "baa"); + yield return (@"[ab]+a", "cacbaac", RegexOptions.None, 0, 7, true, "baa"); + yield return (@"^(\d{2,3}){2}$", "1234", RegexOptions.None, 0, 4, true, "1234"); + yield return (@"(\d{2,3}){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); + yield return (@"((\d{2,3})){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); + yield return (@"(abc\d{2,3}){2}", "abc123abc4567", RegexOptions.None, 0, 12, true, "abc123abc456"); + + // Lazy versions of those loops + yield return (@"a+?", "aaa", RegexOptions.None, 0, 3, true, "a"); + yield return (@"a+?\d+?", "a1", RegexOptions.None, 0, 2, true, "a1"); + yield return (@".+?\d+?", "a1", RegexOptions.None, 0, 2, true, "a1"); + yield return (".+?\nabc", "a\nabc", RegexOptions.None, 0, 5, true, "a\nabc"); + yield return (@"\d+?", "abcd123efg", RegexOptions.None, 0, 10, true, "1"); + yield return (@"\d+?\d+?", "abcd123efg", RegexOptions.None, 0, 10, true, "12"); + yield return (@"\w+?123\w+?", "abcd123efg", RegexOptions.None, 0, 10, true, "abcd123e"); + yield return (@"\d+?\w+?", "abcd123efg", RegexOptions.None, 0, 10, true, "12"); + yield return (@"\w+?@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"\w{3,}?@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"\w{4,}?@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, false, string.Empty); + yield return (@"\w{2,5}?@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"\w{3}?@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"\w{0,3}?@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"\w{0,2}?c@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"\w*?@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"(\w+?)@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"((\w+?))@\w+?\.com", "abc@def.com", RegexOptions.None, 0, 11, true, "abc@def.com"); + yield return (@"(\w+?)c@\w+?\.com", "abc@def.comabcdef", RegexOptions.None, 0, 17, true, "abc@def.com"); + yield return (@".+?a", "baa", RegexOptions.None, 0, 3, true, "ba"); + yield return (@"[ab]+?a", "cacbaac", RegexOptions.None, 0, 7, true, "ba"); + yield return (@"^(\d{2,3}?){2}$", "1234", RegexOptions.None, 0, 4, true, "1234"); + yield return (@"(\d{2,3}?){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); + yield return (@"((\d{2,3}?)){2}", "1234", RegexOptions.None, 0, 4, true, "1234"); + yield return (@"(abc\d{2,3}?){2}", "abc123abc4567", RegexOptions.None, 0, 12, true, "abc123abc45"); + + // Testing selected FindOptimizations finds the right prefix + yield return (@"(^|a+)bc", " aabc", RegexOptions.None, 0, 5, true, "aabc"); + yield return (@"(^|($|a+))bc", " aabc", RegexOptions.None, 0, 5, true, "aabc"); + yield return (@"yz(^|a+)bc", " yzaabc", RegexOptions.None, 0, 7, true, "yzaabc"); + yield return (@"(^a|a$) bc", "a bc", RegexOptions.None, 0, 4, true, "a bc"); + if (!RegexHelpers.IsNonBacktracking(engine)) { + // Back references not support with NonBacktracking + yield return (@"(\w+)c@\w+.com\1", "abc@def.comabcdef", RegexOptions.None, 0, 17, true, "abc@def.comab"); yield return (@"(\w+)@def.com\1", "abc@def.comab", RegexOptions.None, 0, 13, false, string.Empty); yield return (@"(\w+)@def.com\1", "abc@def.combc", RegexOptions.None, 0, 13, true, "bc@def.combc"); @@ -153,36 +218,44 @@ public static IEnumerable Match_MemberData() yield return (@"\w+(?\w+)(?\w+)(?\w+?)(?\w+?)(? Match_MemberData() } // Alternation construct + foreach (string input in new[] { "abc", "def" }) + { + string upper = input.ToUpperInvariant(); + + // Two branches + yield return (@"abc|def", input, RegexOptions.None, 0, input.Length, true, input); + yield return (@"abc|def", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); + yield return (@"abc|def", upper, RegexOptions.None, 0, input.Length, false, ""); + + // Three branches + yield return (@"abc|agh|def", input, RegexOptions.None, 0, input.Length, true, input); + yield return (@"abc|agh|def", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); + yield return (@"abc|agh|def", upper, RegexOptions.None, 0, input.Length, false, ""); + + // Four branches + yield return (@"abc|agh|def|aij", input, RegexOptions.None, 0, input.Length, true, input); + yield return (@"abc|agh|def|aij", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); + yield return (@"abc|agh|def|aij", upper, RegexOptions.None, 0, input.Length, false, ""); + + // Four branches (containing various other constructs) + if (!RegexHelpers.IsNonBacktracking(engine)) + { + yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", input, RegexOptions.None, 0, input.Length, true, input); + yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); + yield return (@"abc|(agh)|(?=def)def|(?:(?(aij)aij|(?!)))", upper, RegexOptions.None, 0, input.Length, false, ""); + } + + // Sets in various positions in each branch + yield return (@"a\wc|\wgh|de\w", input, RegexOptions.None, 0, input.Length, true, input); + yield return (@"a\wc|\wgh|de\w", upper, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, 0, input.Length, true, upper); + yield return (@"a\wc|\wgh|de\w", upper, RegexOptions.None, 0, input.Length, false, ""); + } yield return ("[^a-z0-9]etag|[^a-z0-9]digest", "this string has .digest as a substring", RegexOptions.None, 16, 7, true, ".digest"); if (!RegexHelpers.IsNonBacktracking(engine)) { @@ -373,7 +478,6 @@ public static IEnumerable Match_MemberData() yield return ("(?>(?:a|ab|abc|abcd))d", "abcd", RegexOptions.None, 0, 4, false, string.Empty); yield return ("(?>(?:a|ab|abc|abcd))d", "abcd", RegexOptions.RightToLeft, 0, 4, true, "abcd"); } - yield return ("[^a-z0-9]etag|[^a-z0-9]digest", "this string has .digest as a substring", RegexOptions.None, 16, 7, true, ".digest"); // No Negation yield return ("[abcd-[abcd]]+", "abcxyzABCXYZ`!@#$%^&*()_-+= \t\n", RegexOptions.None, 0, 30, false, string.Empty); @@ -475,15 +579,29 @@ public static IEnumerable Match_MemberData() yield return (@".*\nFoo", $"\nFooThis should match", RegexOptions.None, 0, 21, true, "\nFoo"); yield return (@".*\nfoo", "\nfooThis should match", RegexOptions.None, 4, 17, false, ""); + yield return (@".*?\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); + yield return (@"a.*?\nfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); + yield return (@".*?\nFoo", $"\nFooThis should match", RegexOptions.None, 0, 21, true, "\nFoo"); + yield return (@".*?\nfoo", "\nfooThis should match", RegexOptions.None, 4, 17, false, ""); + yield return (@".*\dfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); yield return (@".*\dFoo", "This1Foo should match", RegexOptions.None, 0, 21, true, "This1Foo"); yield return (@".*\dFoo", "This1foo should 2Foo match", RegexOptions.None, 0, 26, true, "This1foo should 2Foo"); yield return (@".*\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None, 0, 29, false, ""); yield return (@".*\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None, 24, 5, false, ""); + yield return (@".*?\dfoo", "This shouldn't match", RegexOptions.None, 0, 20, false, ""); + yield return (@".*?\dFoo", "This1Foo should match", RegexOptions.None, 0, 21, true, "This1Foo"); + yield return (@".*?\dFoo", "This1foo should 2Foo match", RegexOptions.None, 0, 26, true, "This1foo should 2Foo"); + yield return (@".*?\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None, 0, 29, false, ""); + yield return (@".*?\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None, 24, 5, false, ""); + yield return (@".*\dfoo", "1fooThis1foo should 1foo match", RegexOptions.None, 4, 9, true, "This1foo"); yield return (@".*\dfoo", "This shouldn't match 1foo", RegexOptions.None, 0, 20, false, ""); + yield return (@".*?\dfoo", "1fooThis1foo should 1foo match", RegexOptions.None, 4, 9, true, "This1foo"); + yield return (@".*?\dfoo", "This shouldn't match 1foo", RegexOptions.None, 0, 20, false, ""); + // Turkish case sensitivity yield return (@"[\u0120-\u0130]", "\u0130", RegexOptions.None, 0, 1, true, "\u0130"); @@ -494,6 +612,17 @@ public static IEnumerable Match_MemberData() yield return (@".*\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo should 2fOo"); yield return (@".*\dfoo", "1fooThis1FOO should 1foo match", RegexOptions.IgnoreCase, 4, 9, true, "This1FOO"); + yield return (@".*?\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase, 0, 21, true, "\nfoo"); + yield return (@".*?\dFoo", "This1foo should match", RegexOptions.IgnoreCase, 0, 21, true, "This1foo"); + if (!RegexHelpers.IsNonBacktracking(engine)) // TODO: https://github.com/dotnet/runtime/issues/63395 + { + yield return (@".*?\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); + yield return (@".*?\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); + yield return (@".*?\dFo{2}", "This1foo should 2FoO match", RegexOptions.IgnoreCase, 0, 26, true, "This1foo"); + yield return (@".*?\dFo{2}", "This1Foo should 2fOo match", RegexOptions.IgnoreCase, 0, 26, true, "This1Foo"); + } + yield return (@".*?\dfoo", "1fooThis1FOO should 1foo match", RegexOptions.IgnoreCase, 4, 9, true, "This1FOO"); + if (!RegexHelpers.IsNonBacktracking(engine)) { // RightToLeft @@ -503,6 +632,12 @@ public static IEnumerable Match_MemberData() yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty); yield return (@"foo\d+", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty); + yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 0, 32, true, "foo4567890"); + yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 22, true, "foo4567890"); + yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 4, true, "foo4"); + yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 10, 3, false, string.Empty); + yield return (@"foo\d+?", "0123456789foo4567890foo ", RegexOptions.RightToLeft, 11, 21, false, string.Empty); + yield return (@"\s+\d+", "sdf 12sad", RegexOptions.RightToLeft, 0, 9, true, " 12"); yield return (@"\s+\d+", " asdf12 ", RegexOptions.RightToLeft, 0, 6, false, string.Empty); yield return ("aaa", "aaabbb", RegexOptions.None, 3, 3, false, string.Empty); @@ -514,15 +649,29 @@ public static IEnumerable Match_MemberData() yield return (@"a.*\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*\nFoo", $"This should match\nFoo", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "This should match\nFoo"); + yield return (@".*?\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); + yield return (@".*?\nfoo", "This should matchfoo\n", RegexOptions.None | RegexOptions.RightToLeft, 4, 13, false, ""); + yield return (@"a.*?\nfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); + yield return (@".*?\nFoo", $"This should match\nFoo", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "\nFoo"); + yield return (@".*\dfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); yield return (@".*\dFoo", "This1Foo should match", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "This1Foo"); yield return (@".*\dFoo", "This1foo should 2Foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 26, true, "This1foo should 2Foo"); yield return (@".*\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 29, false, ""); yield return (@".*\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 19, 0, false, ""); + yield return (@".*?\dfoo", "This shouldn't match", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); + yield return (@".*?\dFoo", "This1Foo should match", RegexOptions.None | RegexOptions.RightToLeft, 0, 21, true, "1Foo"); + yield return (@".*?\dFoo", "This1foo should 2Foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 26, true, "2Foo"); + yield return (@".*?\dFoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 0, 29, false, ""); + yield return (@".*?\dfoo", "This1foo shouldn't 2foo match", RegexOptions.None | RegexOptions.RightToLeft, 19, 0, false, ""); + yield return (@".*\dfoo", "1fooThis2foo should 1foo match", RegexOptions.None | RegexOptions.RightToLeft, 8, 4, true, "2foo"); yield return (@".*\dfoo", "This shouldn't match 1foo", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); + yield return (@".*?\dfoo", "1fooThis2foo should 1foo match", RegexOptions.None | RegexOptions.RightToLeft, 8, 4, true, "2foo"); + yield return (@".*?\dfoo", "This shouldn't match 1foo", RegexOptions.None | RegexOptions.RightToLeft, 0, 20, false, ""); + // .* : RTL, case insensitive yield return (@".*\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "\nfoo"); yield return (@".*\dFoo", "This1foo should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "This1foo"); @@ -531,6 +680,14 @@ public static IEnumerable Match_MemberData() yield return (@".*\dfoo", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 8, 4, true, "2FOO"); yield return (@"[\w\s].*", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "1fooThis2FOO should 1foo match"); yield return (@"i.*", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "is2FOO should 1foo match"); + + yield return (@".*?\nFoo", "\nfooThis should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "\nfoo"); + yield return (@".*?\dFoo", "This1foo should match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 21, true, "1foo"); + yield return (@".*?\dFoo", "This1foo should 2FoO match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "2FoO"); + yield return (@".*?\dFoo", "This1Foo should 2fOo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 26, true, "2fOo"); + yield return (@".*?\dfoo", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 8, 4, true, "2FOO"); + yield return (@"[\w\s].*?", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "h"); + yield return (@"i.*?", "1fooThis2FOO should 1foo match", RegexOptions.IgnoreCase | RegexOptions.RightToLeft, 0, 30, true, "is2FOO should 1foo match"); } // [ActiveIssue("https://github.com/dotnet/runtime/issues/36149")] @@ -900,6 +1057,18 @@ public static IEnumerable Match_Advanced_TestData() new CaptureData(string.Empty, 1, 0) } }; + yield return new object[] + { + engine, + "(d+?)(e*?)(f+)", "dddeeefff", RegexOptions.None, 0, 9, + new CaptureData[] + { + new CaptureData("dddeeefff", 0, 9), + new CaptureData("ddd", 0, 3), + new CaptureData("eee", 3, 3), + new CaptureData("fff", 6, 3), + } + }; // Noncapturing group : Actual - "(a+)(?:b*)(ccc)" yield return new object[] diff --git a/src/libraries/System.Text.RegularExpressions/tests/RegexReductionTests.cs b/src/libraries/System.Text.RegularExpressions/tests/RegexReductionTests.cs index c3cd830fbb7b2..38cf72a3f5238 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/RegexReductionTests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/RegexReductionTests.cs @@ -343,6 +343,9 @@ private static int GetMinRequiredLength(Regex r) [InlineData("(?:a{1,2}){4}", "a{4,8}")] // Nested atomic [InlineData("(?>(?>(?>(?>abc*))))", "(?>ab(?>c*))")] + [InlineData("(?>(?>(?>(?>))))", "")] + [InlineData("(?>(?>(?>(?>(?!)))))", "(?!)")] + [InlineData("(?=(?>))", "")] // Alternation reduction [InlineData("a|b", "[ab]")] [InlineData("a|b|c|d|e|g|h|z", "[a-eghz]")] @@ -366,6 +369,11 @@ private static int GetMinRequiredLength(Regex r) [InlineData("hello there|hello again|hello|hello|hello|hello", "hello(?> there| again|)")] [InlineData("hello there|hello again|hello|hello|hello|hello|hello world", "hello(?> there| again|| world)")] [InlineData("hello there|hello again|hello|hello|hello|hello|hello world|hello", "hello(?> there| again|| world)")] + [InlineData("ab|cd|||ef", "ab|cd||ef")] + [InlineData("|ab|cd|e||f", "|ab|cd|ef")] + [InlineData("ab|cd|||||||||||ef", "ab|cd||ef")] + [InlineData("ab|cd|||||||||||e||f|||", "ab|cd||ef")] + [InlineData("ab|cd|(?!)|ef", "ab|cd|ef")] [InlineData("abcd(?:(?i:e)|(?i:f))", "abcd(?i:[ef])")] [InlineData("(?i:abcde)|(?i:abcdf)", "(?i:abcd[ef])")] [InlineData("xyz(?:(?i:abcde)|(?i:abcdf))", "xyz(?i:abcd[ef])")] @@ -376,14 +384,40 @@ private static int GetMinRequiredLength(Regex r) [InlineData("(?(a)a)", "(?(a)a|)")] [InlineData("(?(abc)def)", "(?(abc)def|)")] [InlineData("(?(\\w)\\d)", "(?(\\w)\\d|)")] + // Loops inside alternation constructs + [InlineData("(abc*|def)ghi", "(ab(?>c*)|def)ghi")] + [InlineData("(abc|def*)ghi", "(abc|de(?>f*))ghi")] + [InlineData("(abc*|def*)ghi", "(ab(?>c*)|de(?>f*))ghi")] + [InlineData("(abc*|def*)", "(ab(?>c*)|de(?>f*))")] + [InlineData("(?(\\w)abc*|def*)ghi", "(?(\\w)ab(?>c*)|de(?>f*))ghi")] + [InlineData("(?(\\w)abc*|def*)", "(?(\\w)ab(?>c*)|de(?>f*))")] + [InlineData("(?(xyz*)abc|def)", "(?(xy(?>z*))abc|def)")] + [InlineData("(?(xyz*)abc|def)\\w", "(?(xy(?>z*))abc|def)\\w")] + // Loops followed by alternation constructs + [InlineData("a*(bcd|efg)", "(?>a*)(bcd|efg)")] + [InlineData("a*(?(xyz)bcd|efg)", "(?>a*)(?(xyz)bcd|efg)")] // Auto-atomicity [InlineData("a*b", "(?>a*)b")] - [InlineData("a*b+", "(?>a*)b+")] - [InlineData("a*b{3,4}", "(?>a*)b{3,4}")] + [InlineData("a*b+", "(?>a*)(?>b+)")] + [InlineData("a*b*", "(?>a*)(?>b*)")] + [InlineData("a*b+c*", "(?>a*)(?>b+)(?>c*)")] + [InlineData("a*b*c*", "(?>a*)(?>b*)(?>c*)")] + [InlineData("a*b*c*|d*[ef]*", "(?>a*)(?>b*)(?>c*)|(?>d*)(?>[ef]*)")] + [InlineData("(a*)(b*)(c*)", "((?>a*))((?>b*))((?>c*))")] + [InlineData("a*b{3,4}", "(?>a*)(?>b{3,4})")] + [InlineData("[ab]*[^a]*", "[ab]*(?>[^a]*)")] + [InlineData("[aa]*[^a]*", "(?>a*)(?>[^a]*)")] + [InlineData("a??", "")] + [InlineData("(abc*?)", "(ab)")] + [InlineData("a{1,3}?", "a{1,4}?")] + [InlineData("a{2,3}?", "a{2}")] + [InlineData("bc(a){1,3}?", "bc(a){1,2}?")] + [InlineData("c{3,}?|f{2,}?", "c{3}|f{2}")] + [InlineData("[a-z]*[\x0000-\xFFFF]+", "[a-z]*(?>[\x0000-\xFFFF]+)")] [InlineData("a+b", "(?>a+)b")] [InlineData("a?b", "(?>a?)b")] [InlineData("[^\n]*\n", "(?>[^\n]*)\n")] - [InlineData("[^\n]*\n+", "(?>[^\n]*)\n+")] + [InlineData("[^\n]*\n+", "(?>[^\n]*)(?>\n+)")] [InlineData("(a+)b", "((?>a+))b")] [InlineData("a*(?:bcd|efg)", "(?>a*)(?:bcd|efg)")] [InlineData("\\w*\\b", "(?>\\w*)\\b")] @@ -392,8 +426,8 @@ private static int GetMinRequiredLength(Regex r) [InlineData("(?:a[ce]*|b*)g", "(?:a(?>[ce]*)|(?>b*))g")] [InlineData("(?:a[ce]*|b*)c", "(?:a[ce]*|(?>b*))c")] [InlineData("apple|(?:orange|pear)|grape", "apple|orange|pear|grape")] - [InlineData("(?>(?>(?>(?:abc)*)))", "(?:abc)*")] - [InlineData("(?:w*)+", "(?>w*)+")] + [InlineData("(?:abc)*", "(?>(?>(?>(?:abc)*)))")] + [InlineData("(?:w*)+", "(?>(?>w*)+)")] [InlineData("(?:w*)+\\.", "(?>w*)+\\.")] [InlineData("(a[bcd]e*)*fg", "(a[bcd](?>e*))*fg")] [InlineData("(\\w[bcd]\\s*)*fg", "(\\w[bcd](?>\\s*))*fg")] @@ -461,7 +495,7 @@ public void PatternsReduceIdentically(string pattern1, string pattern2) [InlineData("(?i:abcd)|abcd", "abcd|abcd")] [InlineData("abcd|(?i:abcd)", "abcd|abcd")] // Not applying auto-atomicity - [InlineData("a*b*", "(?>a*)b*")] + [InlineData(@"(a*|b*)\w*", @"((?>a*)|(?>b*))\w*")] [InlineData("[ab]*[^a]", "(?>[ab]*)[^a]")] [InlineData("[ab]*[^a]*", "(?>[ab]*)[^a]*")] [InlineData("[ab]*[^a]*?", "(?>[ab]*)[^a]*?")] @@ -477,6 +511,18 @@ public void PatternsReduceIdentically(string pattern1, string pattern2) [InlineData("(w+)+", "((?>w+))+")] [InlineData("(w{1,2})+", "((?>w{1,2}))+")] [InlineData("(?:ab|cd|ae)f", "(?>ab|cd|ae)f")] + // Loops inside alternation constructs + [InlineData("(abc*|def)chi", "(ab(?>c*)|def)chi")] + [InlineData("(abc|def*)fhi", "(abc|de(?>f*))fhi")] + [InlineData("(abc*|def*)\\whi", "(ab(?>c*)|de(?>f*))\\whi")] + [InlineData("(?(\\w)abc*|def*)\\whi", "(?(\\w)ab(?>c*)|de(?>f*))\\whi")] + // Loops followed by alternation constructs + [InlineData("a*(bcd|afg)", "(?>a*)(bcd|afg)")] + [InlineData("(a*)(?(1)bcd|efg)", "((?>a*))(?(1)bcd|efg)")] + [InlineData("a*(?(abc)bcd|efg)", "(?>a*)(?(abc)bcd|efg)")] + [InlineData("a*(?(xyz)acd|efg)", "(?>a*)(?(xyz)acd|efg)")] + [InlineData("a*(?(xyz)bcd|afg)", "(?>a*)(?(xyz)bcd|afg)")] + [InlineData("a*(?(xyz)bcd)", "(?>a*)(?(xyz)bcd)")] public void PatternsReduceDifferently(string pattern1, string pattern2) { string result1 = GetRegexCodes(new Regex(pattern1)); @@ -523,6 +569,20 @@ public void PatternsReduceDifferently(string pattern1, string pattern2) [InlineData(@"(YZ+|(WX+|(UV+|(ST+|(QR+|(OP+|(MN+|(KL+|(IJ+|(GH+|(EF+|(CD+|(AB+|(89+|(67+|(45+|(23+|(01+|(yz+|(wx+|(uv+|(st+|(qr+|(op+|(mn+|(kl+|(ij+|(gh+|(ef+|(de+|(a|bc+)))))))))))))))))))))))))))))))", 1)] [InlineData(@"a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(ab|cd+)|ef+)|gh+)|ij+)|kl+)|mn+)|op+)|qr+)|st+)|uv+)|wx+)|yz+)|01+)|23+)|45+)|67+)|89+)|AB+)|CD+)|EF+)|GH+)|IJ+)|KL+)|MN+)|OP+)|QR+)|ST+)|UV+)|WX+)|YZ+)", 3)] [InlineData(@"(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((a)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))", 1)] + [InlineData(@"(?(\d)\d{3}|\d)", 1)] + [InlineData(@"(?(\d{7})\d{3}|\d{2})", 2)] + [InlineData(@"(?(\d{7})\d{2}|\d{3})", 2)] + [InlineData(@"(?(\d)\d{3}|\d{2})", 2)] + [InlineData(@"(?(\d)|\d{2})", 0)] + [InlineData(@"(?(\d)\d{3})", 0)] + [InlineData(@"(abc)(?(1)\d{3}|\d{2})", 5)] + [InlineData(@"(abc)(?(1)\d{2}|\d{3})", 5)] + [InlineData(@"(abc)(?(1)|\d{2})", 3)] + [InlineData(@"(abc)(?(1)\d{3})", 3)] + [InlineData(@"(abc|)", 0)] + [InlineData(@"(|abc)", 0)] + [InlineData(@"(?(x)abc|)", 0)] + [InlineData(@"(?(x)|abc)", 0)] public void MinRequiredLengthIsCorrect(string pattern, int expectedLength) { var r = new Regex(pattern); diff --git a/src/libraries/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Generators.Tests/RegexGeneratorParserTests.cs b/src/libraries/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Generators.Tests/RegexGeneratorParserTests.cs index da7e19c820128..d3d8a1f5af219 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Generators.Tests/RegexGeneratorParserTests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Generators.Tests/RegexGeneratorParserTests.cs @@ -442,6 +442,30 @@ partial class C ", compile: true)); } + [Fact] + public async Task Valid_ClassWithGenericConstraints() + { + Assert.Empty(await RunGenerator(@" + using D; + using System.Text.RegularExpressions; + namespace A + { + public partial class B + { + private partial class C where T : IBlah + { + [RegexGenerator(""ab"")] + private static partial Regex Valid(); + } + } + } + namespace D + { + internal interface IBlah { } + } + ", compile: true)); + } + public static IEnumerable Valid_Modifiers_MemberData() { foreach (string type in new[] { "class", "struct", "record", "record struct", "record class", "interface" }) diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs index 4ef7a3b721e4d..74ef7ec9e890b 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/ConcurrencyLimiter.cs @@ -95,10 +95,27 @@ protected override ValueTask WaitAsyncCore(int permitCount, Canc return new ValueTask(lease); } - // Don't queue if queue limit reached - if (_queueCount + permitCount > _options.QueueLimit) + // Avoid integer overflow by using subtraction instead of addition + Debug.Assert(_options.QueueLimit >= _queueCount); + if (_options.QueueLimit - _queueCount < permitCount) { - return new ValueTask(QueueLimitLease); + if (_options.QueueProcessingOrder == QueueProcessingOrder.NewestFirst && permitCount <= _options.QueueLimit) + { + // remove oldest items from queue until there is space for the newest request + do + { + RequestRegistration oldestRequest = _queue.DequeueHead(); + _queueCount -= oldestRequest.Count; + Debug.Assert(_queueCount >= 0); + oldestRequest.Tcs.TrySetResult(FailedLease); + } + while (_options.QueueLimit - _queueCount < permitCount); + } + else + { + // Don't queue if queue limit reached and QueueProcessingOrder is OldestFirst + return new ValueTask(QueueLimitLease); + } } TaskCompletionSource tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); diff --git a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs index bb1ec82f3fff0..6593d895a6810 100644 --- a/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs +++ b/src/libraries/System.Threading.RateLimiting/src/System/Threading/RateLimiting/TokenBucketRateLimiter.cs @@ -101,10 +101,27 @@ protected override ValueTask WaitAsyncCore(int tokenCount, Cance return new ValueTask(lease); } - // Don't queue if queue limit reached - if (_queueCount + tokenCount > _options.QueueLimit) + // Avoid integer overflow by using subtraction instead of addition + Debug.Assert(_options.QueueLimit >= _queueCount); + if (_options.QueueLimit - _queueCount < tokenCount) { - return new ValueTask(CreateFailedTokenLease(tokenCount)); + if (_options.QueueProcessingOrder == QueueProcessingOrder.NewestFirst && tokenCount <= _options.QueueLimit) + { + // remove oldest items from queue until there is space for the newest acquisition request + do + { + RequestRegistration oldestRequest = _queue.DequeueHead(); + _queueCount -= oldestRequest.Count; + Debug.Assert(_queueCount >= 0); + oldestRequest.Tcs.TrySetResult(FailedLease); + } + while (_options.QueueLimit - _queueCount < tokenCount); + } + else + { + // Don't queue if queue limit reached and QueueProcessingOrder is OldestFirst + return new ValueTask(CreateFailedTokenLease(tokenCount)); + } } TaskCompletionSource tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); diff --git a/src/libraries/System.Threading.RateLimiting/tests/BaseRateLimiterTests.cs b/src/libraries/System.Threading.RateLimiting/tests/BaseRateLimiterTests.cs index 9d98a5101a33b..a96dc0ba86e63 100644 --- a/src/libraries/System.Threading.RateLimiting/tests/BaseRateLimiterTests.cs +++ b/src/libraries/System.Threading.RateLimiting/tests/BaseRateLimiterTests.cs @@ -24,11 +24,23 @@ public abstract class BaseRateLimiterTests public abstract Task CanAcquireResourceAsync_QueuesAndGrabsNewest(); [Fact] - public abstract Task FailsWhenQueuingMoreThanLimit(); + public abstract Task FailsWhenQueuingMoreThanLimit_OldestFirst(); + + [Fact] + public abstract Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst(); + + [Fact] + public abstract Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFirst(); + + [Fact] + public abstract Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimitAndNoAvailability_NewestFirst(); [Fact] public abstract Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAvailable(); + [Fact] + public abstract Task LargeAcquiresAndQueuesDoNotIntegerOverflow(); + [Fact] public abstract void ThrowsWhenAcquiringMoreThanLimit(); diff --git a/src/libraries/System.Threading.RateLimiting/tests/ConcurrencyLimiterTests.cs b/src/libraries/System.Threading.RateLimiting/tests/ConcurrencyLimiterTests.cs index 22658e07a5c9c..da041ac938aa2 100644 --- a/src/libraries/System.Threading.RateLimiting/tests/ConcurrencyLimiterTests.cs +++ b/src/libraries/System.Threading.RateLimiting/tests/ConcurrencyLimiterTests.cs @@ -94,9 +94,9 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() } [Fact] - public override async Task FailsWhenQueuingMoreThanLimit() + public override async Task FailsWhenQueuingMoreThanLimit_OldestFirst() { - var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions(1, QueueProcessingOrder.NewestFirst, 1)); + var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions(1, QueueProcessingOrder.OldestFirst, 1)); using var lease = limiter.Acquire(1); var wait = limiter.WaitAsync(1); @@ -105,11 +105,96 @@ public override async Task FailsWhenQueuingMoreThanLimit() } [Fact] - public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAvailable() + public override async Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst() { var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions(1, QueueProcessingOrder.NewestFirst, 1)); var lease = limiter.Acquire(1); var wait = limiter.WaitAsync(1); + Assert.False(wait.IsCompleted); + + var wait2 = limiter.WaitAsync(1); + var lease1 = await wait; + Assert.False(lease1.IsAcquired); + Assert.False(wait2.IsCompleted); + + lease.Dispose(); + + lease = await wait2; + Assert.True(lease.IsAcquired); + } + + [Fact] + public override async Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFirst() + { + var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions(2, QueueProcessingOrder.NewestFirst, 2)); + var lease = limiter.Acquire(2); + Assert.True(lease.IsAcquired); + var wait = limiter.WaitAsync(1); + Assert.False(wait.IsCompleted); + + var wait2 = limiter.WaitAsync(1); + Assert.False(wait2.IsCompleted); + + var wait3 = limiter.WaitAsync(2); + var lease1 = await wait; + var lease2 = await wait2; + Assert.False(lease1.IsAcquired); + Assert.False(lease2.IsAcquired); + Assert.False(wait3.IsCompleted); + + lease.Dispose(); + + lease = await wait3; + Assert.True(lease.IsAcquired); + } + + [Fact] + public override async Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimitAndNoAvailability_NewestFirst() + { + var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions(2, QueueProcessingOrder.NewestFirst, 1)); + var lease = limiter.Acquire(2); + Assert.True(lease.IsAcquired); + + // Fill queue + var wait = limiter.WaitAsync(1); + Assert.False(wait.IsCompleted); + + var lease1 = await limiter.WaitAsync(2); + Assert.False(lease1.IsAcquired); + + lease.Dispose(); + var lease2 = await wait; + Assert.True(lease2.IsAcquired); + } + + [Fact] + public override async Task LargeAcquiresAndQueuesDoNotIntegerOverflow() + { + var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions(int.MaxValue, QueueProcessingOrder.NewestFirst, int.MaxValue)); + var lease = limiter.Acquire(int.MaxValue); + Assert.True(lease.IsAcquired); + + // Fill queue + var wait = limiter.WaitAsync(3); + Assert.False(wait.IsCompleted); + + var wait2 = limiter.WaitAsync(int.MaxValue); + Assert.False(wait2.IsCompleted); + + var lease1 = await wait; + Assert.False(lease1.IsAcquired); + + lease.Dispose(); + var lease2 = await wait2; + Assert.True(lease2.IsAcquired); + } + + [Fact] + public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAvailable() + { + var limiter = new ConcurrencyLimiter(new ConcurrencyLimiterOptions(1, QueueProcessingOrder.OldestFirst, 1)); + var lease = limiter.Acquire(1); + var wait = limiter.WaitAsync(1); var failedLease = await limiter.WaitAsync(1); Assert.False(failedLease.IsAcquired); diff --git a/src/libraries/System.Threading.RateLimiting/tests/TokenBucketRateLimiterTests.cs b/src/libraries/System.Threading.RateLimiting/tests/TokenBucketRateLimiterTests.cs index edf05bfe15cce..594bb79be22eb 100644 --- a/src/libraries/System.Threading.RateLimiting/tests/TokenBucketRateLimiterTests.cs +++ b/src/libraries/System.Threading.RateLimiting/tests/TokenBucketRateLimiterTests.cs @@ -111,9 +111,9 @@ public override async Task CanAcquireResourceAsync_QueuesAndGrabsNewest() } [Fact] - public override async Task FailsWhenQueuingMoreThanLimit() + public override async Task FailsWhenQueuingMoreThanLimit_OldestFirst() { - var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions(1, QueueProcessingOrder.NewestFirst, 1, + var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions(1, QueueProcessingOrder.OldestFirst, 1, TimeSpan.Zero, 1, autoReplenishment: false)); using var lease = limiter.Acquire(1); var wait = limiter.WaitAsync(1); @@ -125,9 +125,77 @@ public override async Task FailsWhenQueuingMoreThanLimit() } [Fact] - public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAvailable() + public override async Task DropsOldestWhenQueuingMoreThanLimit_NewestFirst() { var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions(1, QueueProcessingOrder.NewestFirst, 1, + TimeSpan.Zero, 1, autoReplenishment: false)); + var lease = limiter.Acquire(1); + var wait = limiter.WaitAsync(1); + Assert.False(wait.IsCompleted); + + var wait2 = limiter.WaitAsync(1); + var lease1 = await wait; + Assert.False(lease1.IsAcquired); + Assert.False(wait2.IsCompleted); + + limiter.TryReplenish(); + + lease = await wait2; + Assert.True(lease.IsAcquired); + } + + [Fact] + public override async Task DropsMultipleOldestWhenQueuingMoreThanLimit_NewestFirst() + { + var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions(2, QueueProcessingOrder.NewestFirst, 2, + TimeSpan.Zero, 1, autoReplenishment: false)); + var lease = limiter.Acquire(2); + Assert.True(lease.IsAcquired); + var wait = limiter.WaitAsync(1); + Assert.False(wait.IsCompleted); + + var wait2 = limiter.WaitAsync(1); + Assert.False(wait2.IsCompleted); + + var wait3 = limiter.WaitAsync(2); + var lease1 = await wait; + var lease2 = await wait2; + Assert.False(lease1.IsAcquired); + Assert.False(lease2.IsAcquired); + Assert.False(wait3.IsCompleted); + + limiter.TryReplenish(); + limiter.TryReplenish(); + + lease = await wait3; + Assert.True(lease.IsAcquired); + } + + [Fact] + public override async Task DropsRequestedLeaseIfPermitCountGreaterThanQueueLimitAndNoAvailability_NewestFirst() + { + var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions(2, QueueProcessingOrder.NewestFirst, 1, + TimeSpan.Zero, 1, autoReplenishment: false)); + var lease = limiter.Acquire(2); + Assert.True(lease.IsAcquired); + + // Fill queue + var wait = limiter.WaitAsync(1); + Assert.False(wait.IsCompleted); + + var lease1 = await limiter.WaitAsync(2); + Assert.False(lease1.IsAcquired); + + limiter.TryReplenish(); + + lease = await wait; + Assert.True(lease.IsAcquired); + } + + [Fact] + public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAvailable() + { + var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions(1, QueueProcessingOrder.OldestFirst, 1, TimeSpan.Zero, 1, autoReplenishment: false)); var lease = limiter.Acquire(1); var wait = limiter.WaitAsync(1); @@ -147,6 +215,29 @@ public override async Task QueueAvailableAfterQueueLimitHitAndResources_BecomeAv Assert.True(lease.IsAcquired); } + [Fact] + public override async Task LargeAcquiresAndQueuesDoNotIntegerOverflow() + { + var limiter = new TokenBucketRateLimiter(new TokenBucketRateLimiterOptions(int.MaxValue, QueueProcessingOrder.NewestFirst, int.MaxValue, + TimeSpan.Zero, int.MaxValue, autoReplenishment: false)); + var lease = limiter.Acquire(int.MaxValue); + Assert.True(lease.IsAcquired); + + // Fill queue + var wait = limiter.WaitAsync(3); + Assert.False(wait.IsCompleted); + + var wait2 = limiter.WaitAsync(int.MaxValue); + Assert.False(wait2.IsCompleted); + + var lease1 = await wait; + Assert.False(lease1.IsAcquired); + + limiter.TryReplenish(); + var lease2 = await wait2; + Assert.True(lease2.IsAcquired); + } + [Fact] public override void ThrowsWhenAcquiringMoreThanLimit() { diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs index 2cf653c6c20aa..9bc5e46e67897 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SourceCore.cs @@ -543,7 +543,7 @@ private bool OfferToTargets(ITargetBlock? linkToTarget = null) // Peek at the next message if there is one, so we can offer it. DataflowMessageHeader header = default(DataflowMessageHeader); - TOutput? message = default(TOutput); + TOutput? message; bool offerJustToLinkToTarget = false; // If offering isn't enabled and if we're not doing this as diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SpscTargetCore.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SpscTargetCore.cs index 65daf01fcc5a9..804dc77ac0bfe 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SpscTargetCore.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/SpscTargetCore.cs @@ -323,8 +323,7 @@ private void CompleteBlockOncePossible() Debug.Assert(_completionReserved, "Should only invoke once completion has been reserved."); // Dump any messages that might remain in the queue, which could happen if we completed due to exceptions. - TInput? dumpedMessage; - while (_messages.TryDequeue(out dumpedMessage)) ; + while (_messages.TryDequeue(out _)) ; // Complete the completion task bool result; diff --git a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetCore.cs b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetCore.cs index ded6e9a053b07..8e6b338279ccb 100644 --- a/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetCore.cs +++ b/src/libraries/System.Threading.Tasks.Dataflow/src/Internal/TargetCore.cs @@ -538,7 +538,7 @@ private bool TryGetNextMessageForNewAsyncOperation(out KeyValuePair target, DataflowLinkOptions linkOptions) Debug.Assert(target != null, "The target that is supposed to be linked must not be null."); Debug.Assert(linkOptions != null, "The link options must not be null."); - LinkedTargetInfo? targetInfo; - // If the target already exists in the registry, replace it with a new NopLinkPropagator to maintain uniqueness - if (_targetInformation.TryGetValue(target, out targetInfo)) target = new NopLinkPropagator(_owningSource, target); + if (_targetInformation.TryGetValue(target, out _)) target = new NopLinkPropagator(_owningSource, target); // Add the target to both stores, the list and the dictionary, which are used for different purposes var node = new LinkedTargetInfo(target, linkOptions); diff --git a/src/libraries/System.Threading/src/System/Threading/Barrier.cs b/src/libraries/System.Threading/src/System/Threading/Barrier.cs index 3f5b1e993a540..5e1f6ff96f104 100644 --- a/src/libraries/System.Threading/src/System/Threading/Barrier.cs +++ b/src/libraries/System.Threading/src/System/Threading/Barrier.cs @@ -337,7 +337,7 @@ public long AddParticipants(int participantCount) } SpinWait spinner = default; - long newPhase = 0; + long newPhase; while (true) { int currentTotal = _currentTotalCount; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs index 531f4e8ca3a7f..d2af113ed8f63 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs @@ -81,7 +81,6 @@ internal static EnterpriseServicesInteropOption InteropMode(TransactionScope? cu internal static Transaction? FastGetTransaction(TransactionScope? currentScope, ContextData contextData, out Transaction? contextTransaction) { Transaction? current = null; - contextTransaction = null; contextTransaction = contextData.CurrentTransaction; @@ -159,7 +158,7 @@ public static Transaction? Current etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.get_Current"); } - GetCurrentTransactionAndScope(TxLookup.Default, out Transaction? current, out TransactionScope? currentScope, out Transaction? contextValue); + GetCurrentTransactionAndScope(TxLookup.Default, out Transaction? current, out TransactionScope? currentScope, out _); if (currentScope != null) { @@ -1277,7 +1276,7 @@ internal static ContextData TLSCurrentData internal static ContextData LookupContextData(TxLookup defaultLookup) { - ContextData? currentData = null; + ContextData? currentData; if (CallContextCurrentData.TryGetCurrentData(out currentData)) { if (currentData.CurrentScope == null && currentData.CurrentTransaction == null && defaultLookup != TxLookup.DefaultCallContext) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs index 4107e213ee455..4ccd3c5f17bc5 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -157,7 +157,7 @@ public static Enlistment Reenlist( // Put the recovery information into a stream. MemoryStream stream = new MemoryStream(recoveryInformation); - int recoveryInformationVersion = 0; + int recoveryInformationVersion; string? nodeName = null; byte[]? resourceManagerRecoveryInformation = null; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs index 206e8d6517cfa..67c53ef9a3aec 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs @@ -4304,7 +4304,7 @@ internal override void EnterState(InternalTransaction tx) CommonEnterState(tx); // We are never going to have an DistributedTransaction for this one. - DistributedTransaction? distributedTx = null; + DistributedTransaction? distributedTx; try { // Ask the delegation interface to promote the transaction. diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs index c256c0530bc61..a36d3836827bc 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs @@ -52,7 +52,7 @@ private ManualResetEvent WriterFinishedEvent public int EnterReadLock() { - int readerIndex = 0; + int readerIndex; do { if (_writerPresent) @@ -223,7 +223,7 @@ private long CurrentTime internal int Add(InternalTransaction txNew) { // Tell the runtime that we are modifying global state. - int readerIndex = 0; + int readerIndex; readerIndex = _rwLock.EnterReadLock(); try @@ -359,7 +359,6 @@ private void AddIter(InternalTransaction txNew) // creating the second BucketSet with remove the backward reference that was created in the // first trip thru the loop. currentBucketSet = lastBucketSet; - lastBucketSet = null; // The outer loop will iterate and pick up where we left off. } @@ -410,14 +409,14 @@ private void ThreadTimer(object? state) // that point will timeout so once we've found it then it is just a matter of traversing the // structure. // - BucketSet? lastBucketSet = null; + BucketSet? lastBucketSet; BucketSet currentBucketSet = _headBucketSet; // The list always has a head. // Acquire a writer lock before checking to see if we should disable the timer. // Adding of transactions acquires a reader lock and might insert a new BucketSet. // If that races with our check for a BucketSet existing, we may not timeout that // transaction that is being added. - WeakReference? nextWeakSet = null; + WeakReference? nextWeakSet; BucketSet? nextBucketSet = null; nextWeakSet = (WeakReference?)currentBucketSet.nextSetWeak; @@ -505,7 +504,7 @@ private void ThreadTimer(object? state) if (abortingSetsWeak == nextWeakSet) { // Yea - now proceed to abort the transactions. - BucketSet? abortingBucketSets = null; + BucketSet? abortingBucketSets; do { diff --git a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/UriUtil.cs b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/UriUtil.cs index 64e88be64f5d0..9ef10f6f68944 100644 --- a/src/libraries/System.Web.HttpUtility/src/System/Web/Util/UriUtil.cs +++ b/src/libraries/System.Web.HttpUtility/src/System/Web/Util/UriUtil.cs @@ -7,15 +7,13 @@ namespace System.Web.Util { internal static class UriUtil { - private static readonly char[] s_queryFragmentSeparators = { '?', '#' }; - // Just extracts the query string and fragment from the input path by splitting on the separator characters. // Doesn't perform any validation as to whether the input represents a valid URL. // Concatenating the pieces back together will form the original input string. private static void ExtractQueryAndFragment(string input, out string path, out string? queryAndFragment) { - int queryFragmentSeparatorPos = input.IndexOfAny(s_queryFragmentSeparators); - if (queryFragmentSeparatorPos != -1) + int queryFragmentSeparatorPos = input.AsSpan().IndexOfAny('?', '#'); // query fragment separators + if (queryFragmentSeparatorPos >= 0) { path = input.Substring(0, queryFragmentSeparatorPos); queryAndFragment = input.Substring(queryFragmentSeparatorPos); diff --git a/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs b/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs index 4ded3f0d2bf96..c970d47a32c06 100644 --- a/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs +++ b/src/libraries/System.Windows.Extensions/src/System/Media/SoundPlayer.cs @@ -616,7 +616,7 @@ private unsafe void ValidateSoundFile(string fileName) private static void ValidateSoundData(byte[] data) { - int position = 0; + int position; short wFormatTag = -1; bool fmtChunkFound = false; diff --git a/src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Utils.cs b/src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Utils.cs index eb445034c2546..d995154505290 100644 --- a/src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Utils.cs +++ b/src/libraries/System.Windows.Extensions/src/System/Security/Cryptography/X509Certificates/X509Utils.cs @@ -20,7 +20,7 @@ internal static SafeCertContextHandle DuplicateCertificateContext(X509Certificat internal static SafeCertStoreHandle ExportToMemoryStore(X509Certificate2Collection collection) { - SafeCertStoreHandle safeCertStoreHandle = SafeCertStoreHandle.InvalidHandle; + SafeCertStoreHandle safeCertStoreHandle; // we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation. // By default, Archived certificates will not be included. diff --git a/src/libraries/externals.csproj b/src/libraries/externals.csproj index 969ed9603a2cd..54ef0d14897c6 100644 --- a/src/libraries/externals.csproj +++ b/src/libraries/externals.csproj @@ -26,7 +26,8 @@ + AfterTargets="AfterResolveReferences" + Condition="'$(TestNativeAot)' != 'true'"> true @@ -75,7 +76,7 @@ + Condition="'$(RuntimeFlavor)' != 'Mono' and '$(TestNativeAot)' != 'true'"> diff --git a/src/libraries/sendtohelix-mobile.targets b/src/libraries/sendtohelix-mobile.targets new file mode 100644 index 0000000000000..33b538779f0b8 --- /dev/null +++ b/src/libraries/sendtohelix-mobile.targets @@ -0,0 +1,143 @@ + + + $(BuildHelixWorkItemsDependsOn);PrepareForBuildHelixWorkItems_Mobile + false + false + + true + true + + + + + maccatalyst + $(_workItemTimeout) + $(_workItemTimeout) + + + + + + armeabi-v7a + arm64-v8a + x86_64 + x86 + net.dot.MonoRunner + $(_workItemTimeout) + + + + + true + true + true + + + + + + + + + + + ios-simulator-64 + tvos-simulator + ios-device + tvos-device + maccatalyst + + + + $([MSBuild]::NormalizeDirectory('$(RepoRoot)', 'src', 'mono', 'msbuild', 'apple', 'build')) + $(TargetOS)- + + https://netcorenativeassets.blob.core.windows.net/resource-packages/external/macos/cmake/cmake-3.16.4-Darwin-x86_64.tar.gz + + <_XHarnessAppleCustomCommand Condition="'$(NeedsiOSSDK)' == 'true'"> + source build-apple-app.sh + + + + + + + + + + + + + + + + + $(AppleTestTarget) + $(_workItemTimeout) + $(_XHarnessAppleCustomCommand) + + + + + $(AppleTestTarget) + $(_workItemTimeout) + $(_XHarnessAppleCustomCommand) + + + + + + false + + 42 + $(AppleTestTarget) + + + + + + false + + 42 + $(AppleTestTarget) + + + + + <_apks Include="$(TestArchiveTestsRoot)**/*.apk" /> + + net.dot.%(Filename) + + <_runonlyApks Include="$(TestArchiveRoot)runonly/**/*.apk" /> + + net.dot.%(Filename) + + 42 + + + + + + + + + <_TestPath Condition="'%(XHarnessAppBundleToTest.CustomCommands)' != ''">$([System.IO.Path]::GetDirectoryName('%(XHarnessAppBundleToTest.Identity)')) + + + + + + diff --git a/src/libraries/sendtohelix-wasm.targets b/src/libraries/sendtohelix-wasm.targets new file mode 100644 index 0000000000000..0941e72a2e0aa --- /dev/null +++ b/src/libraries/sendtohelix-wasm.targets @@ -0,0 +1,221 @@ + + + <_workItemTimeout Condition="'$(Scenario)' == 'BuildWasmApps' and '$(_workItemTimeout)' == ''">01:30:00 + <_workItemTimeout Condition="'$(NeedsToBuildWasmAppsOnHelix)' == 'true'">01:00:00 + <_workItemTimeout Condition="'$(Scenario)' == 'WasmDebuggerTests'">00:10:00 + <_workItemTimeout Condition="'$(Scenario)' == 'WasmTestOnBrowser' and '$(BrowserHost)' == 'windows'">00:45:00 + + true + true + + $(BuildHelixWorkItemsDependsOn);StageEmSdkForHelix;PrepareForBuildHelixWorkItems_Wasm + false + false + + $(RepositoryEngineeringDir)\testing\scenarios\BuildWasmAppsJobsList.txt + $(RepositoryEngineeringDir)\testing\scenarios\WasmDebuggerTestsJobsList.txt + + + $(RepoRoot)src\mono\wasm\emsdk\ + $([MSBuild]::NormalizeDirectory('$(RepoRoot)', 'src', 'mono', 'wasm', 'emsdk')) + + true + true + true + true + true + + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(IsRunningLibraryTests) + + + true + + + + + + true + true + true + true + + + + + true + true + + + + + + + $([MSBuild]::NormalizeDirectory('$(RepoRoot)', 'src', 'mono', 'wasm', 'build')) + $([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'bin', 'NetCoreServer', '$(AspNetCoreAppCurrent)-$(Configuration)')) + $([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'bin', 'RemoteLoopServer', '$(AspNetCoreAppCurrent)-$(Configuration)')) + Workloads- + EMSDK- + $(Scenario)- + + + + + 929513 + https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/$(ChromiumRevision)/chrome-linux.zip + https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/$(ChromiumRevision)/chromedriver_linux64.zip + + + 929513 + https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/$(ChromiumRevision)/chrome-win.zip + https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/$(ChromiumRevision)/chromedriver_win32.zip + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <_WasmWorkItem Include="$(WorkItemArchiveWildCard)" Exclude="$(HelixCorrelationPayload)" Condition="'$(Scenario)' == 'BuildWasmApps'" /> + + <_WasmWorkItem Include="$(TestArchiveTestsRoot)**/Wasm.Debugger.Tests.zip" Condition="'$(IsWasmDebuggerTests)' == 'true'" /> + <_WasmWorkItem Include="$(TestArchiveRoot)browseronly/**/*.zip" Condition="'$(Scenario)' == 'WasmTestOnBrowser'" /> + + + + <_BuildWasmAppsPayloadArchive>@(_WasmWorkItem) + <_WasmDebuggerTestsPayloadArchive>@(_WasmWorkItem) + + + + + + + $(_BuildWasmAppsPayloadArchive) + set "HELIX_XUNIT_ARGS=-class %(Identity)" + export "HELIX_XUNIT_ARGS=-class %(Identity)" + $(HelixCommand) + $(_workItemTimeout) + + + + + + $(_WasmDebuggerTestsPayloadArchive) + + + set TEST_ARGS=--filter "FullyQualifiedName~%(Identity)&Category^!=windows-failing" + export TEST_ARGS="--filter FullyQualifiedName~%(Identity)&Category!=linux-failing" + + $(HelixCommand) + $(_workItemTimeout) + + + + + + <_WasmSampleZipFile Condition="'$(Scenario)' == 'normal' or '$(Scenario)' == ''" Include="$(TestArchiveRoot)runonly/**/*.Console.V8.*.Sample.zip" /> + <_WasmSampleZipFile Condition="'$(Scenario)' == 'WasmTestOnNodeJs'" Include="$(TestArchiveRoot)runonly/**/*.Console.Node.*.Sample.zip" /> + <_WasmSampleZipFile Condition="'$(Scenario)' == 'WasmTestOnBrowser'" Include="$(TestArchiveRoot)runonly/**/*.Browser.*.Sample.zip" /> + + + %(Identity) + $(HelixCommand) + $(_workItemTimeout) + + + + + + + + + + + + <_EmSdkFiles Include="$(EMSDK_PATH)\**\*" Exclude="$(EMSDK_PATH)\.git\**\*" /> + + + + + diff --git a/src/libraries/sendtohelixhelp.proj b/src/libraries/sendtohelixhelp.proj index d1f6b0542de0e..3875c28fdf383 100644 --- a/src/libraries/sendtohelixhelp.proj +++ b/src/libraries/sendtohelixhelp.proj @@ -13,6 +13,16 @@ $(BUILD_BUILDNUMBER) default + $(Configuration) + $(TargetArchitecture) + BuildHelixCommand + true + + + + + + @@ -30,23 +40,17 @@ <_workItemTimeout Condition="'$(_workItemTimeout)' == '' and ('$(TargetOS)' == 'iOS' or '$(TargetOS)' == 'tvOS')">00:45:00 <_workItemTimeout Condition="'$(Scenario)' == '' and '$(_workItemTimeout)' == '' and ('$(TargetArchitecture)' == 'arm64' or '$(TargetArchitecture)' == 'arm')">00:45:00 <_workItemTimeout Condition="'$(Scenario)' != '' and '$(_workItemTimeout)' == '' and ('$(TargetArchitecture)' == 'arm64' or '$(TargetArchitecture)' == 'arm')">01:00:00 - <_workItemTimeout Condition="'$(Scenario)' == 'BuildWasmApps' and '$(_workItemTimeout)' == ''">01:30:00 - <_workItemTimeout Condition="'$(TargetOS)' == 'Browser' and '$(NeedsToBuildWasmAppsOnHelix)' == 'true'">01:00:00 - <_workItemTimeout Condition="'$(TargetOS)' == 'Browser' and '$(Scenario)' == 'WasmDebuggerTests'">00:10:00 <_workItemTimeout Condition="'$(Scenario)' == '' and '$(_workItemTimeout)' == '' and '$(Outerloop)' == 'true'">00:20:00 <_workItemTimeout Condition="'$(Scenario)' == '' and '$(_workItemTimeout)' == ''">00:15:00 <_workItemTimeout Condition="'$(Scenario)' != '' and '$(_workItemTimeout)' == ''">00:30:00 - <_workItemTimeout Condition="'$(Scenario)' == 'WasmTestOnBrowser' and '$(BrowserHost)' == 'windows'">00:45:00 + + $(TestArchiveRuntimeFile) - $(TestArchiveTestsRoot)**/Wasm.Debugger.Tests.zip $(TestArchiveTestsRoot)**/*.zip - $(Configuration) - $(TargetArchitecture) - - $(RepoRoot)src\mono\wasm\emsdk\ - $([MSBuild]::NormalizeDirectory('$(RepoRoot)', 'src', 'mono', 'wasm', 'emsdk')) + $(WaitForWorkItemCompletion) - true - true - true - true - true - - dotnet-workload - sdk-no-workload + dotnet-workload + sdk-no-workload @@ -92,100 +78,21 @@ - - + + - + - - - - - - - - - - - - - - - - - - - - - - - - - true - - - true + + false + true + true - - - - - - - - - - - - - - - - - - - - false - true - true - - - - - true - true - true - true - - - - - true - true - - - - - true - true - true - - - - - - + @@ -243,174 +154,38 @@ - - - maccatalyst - $(_workItemTimeout) - $(_workItemTimeout) - - - - - - armeabi-v7a - arm64-v8a - x86_64 - x86 - net.dot.MonoRunner - $(_workItemTimeout) - - - - - + + @(HelixPreCommand) $(HelixCommandPrefix) @(HelixCommandPrefixItem -> 'set "%(Identity)"', ' & ') $(HelixCommandPrefix) @(HelixCommandPrefixItem, ' ') - true + true $(HelixCommandPrefix) $(HelixCommandPrefix) & - $(HelixCommand) dotnet dev-certs https && + $(HelixCommand) dotnet dev-certs https && - $(HelixCommand) powershell -command "New-SelfSignedCertificate -FriendlyName 'ASP.NET Core HTTPS development certificate' -DnsName @('localhost') -Subject 'CN = localhost' -KeyAlgorithm RSA -KeyLength 2048 -HashAlgorithm sha256 -CertStoreLocation 'Cert:\CurrentUser\My' -TextExtension @('2.5.29.37={text}1.3.6.1.5.5.7.3.1','1.3.6.1.4.1.311.84.1.1={hex}02','2.5.29.19={text}') -KeyUsage DigitalSignature,KeyEncipherment" && + $(HelixCommand) powershell -command "New-SelfSignedCertificate -FriendlyName 'ASP.NET Core HTTPS development certificate' -DnsName @('localhost') -Subject 'CN = localhost' -KeyAlgorithm RSA -KeyLength 2048 -HashAlgorithm sha256 -CertStoreLocation 'Cert:\CurrentUser\My' -TextExtension @('2.5.29.37={text}1.3.6.1.5.5.7.3.1','1.3.6.1.4.1.311.84.1.1={hex}02','2.5.29.19={text}') -KeyUsage DigitalSignature,KeyEncipherment" && - $(HelixCommand)call RunTests.cmd - $(HelixCommand) --runtime-path %HELIX_CORRELATION_PAYLOAD% - - $(HelixCommand)./RunTests.sh - $(HelixCommand) --runtime-path "$HELIX_CORRELATION_PAYLOAD" - - - - - - - - - - - - - ios-simulator-64 - tvos-simulator - ios-device - tvos-device - maccatalyst - - - - $([MSBuild]::NormalizeDirectory('$(RepoRoot)', 'src', 'mono', 'msbuild', 'apple', 'build')) - $(TargetOS)- - - https://netcorenativeassets.blob.core.windows.net/resource-packages/external/macos/cmake/cmake-3.16.4-Darwin-x86_64.tar.gz - - <_XHarnessAppleCustomCommand Condition="'$(NeedsiOSSDK)' == 'true'"> - source build-apple-app.sh - - - - - - - $(AppleTestTarget) - $(_workItemTimeout) - $(_XHarnessAppleCustomCommand) - - - - - $(AppleTestTarget) - $(_workItemTimeout) - $(_XHarnessAppleCustomCommand) - - - - - - false - - 42 - $(AppleTestTarget) - - - - - - false - - 42 - $(AppleTestTarget) - - - - - <_apks Include="$(TestArchiveTestsRoot)**/*.apk" /> - - net.dot.%(Filename) - - <_runonlyApks Include="$(TestArchiveRoot)runonly/**/*.apk" /> - - net.dot.%(Filename) - - 42 - - + $(HelixCommand)call RunTests.cmd + $(HelixCommand) --runtime-path %HELIX_CORRELATION_PAYLOAD% - - $([MSBuild]::NormalizeDirectory('$(RepoRoot)', 'src', 'mono', 'wasm', 'build')) - $([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'bin', 'NetCoreServer', '$(AspNetCoreAppCurrent)-$(Configuration)')) - $([MSBuild]::NormalizeDirectory('$(ArtifactsDir)', 'bin', 'RemoteLoopServer', '$(AspNetCoreAppCurrent)-$(Configuration)')) - Workloads- - EMSDK- - $(Scenario)- - - - - - 929513 - https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/$(ChromiumRevision)/chrome-linux.zip - https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/$(ChromiumRevision)/chromedriver_linux64.zip - - - 929513 - https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/$(ChromiumRevision)/chrome-win.zip - https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/$(ChromiumRevision)/chromedriver_win32.zip + $(HelixCommand)./RunTests.sh + $(HelixCommand) --runtime-path "$HELIX_CORRELATION_PAYLOAD" + <_MonoAotCrossCompilerPath>$([MSBuild]::NormalizePath($(MonoAotCrossDir), 'mono-aot-cross')) <_MonoAotCrossCompilerPath Condition="$([MSBuild]::IsOSPlatform('WINDOWS'))">$(_MonoAotCrossCompilerPath).exe @@ -418,8 +193,24 @@ + - + + + + + + + + + + + @@ -445,138 +236,33 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - - - <_WorkItem Include="$(WorkItemArchiveWildCard)" Exclude="$(HelixCorrelationPayload)" /> + <_DefaultWorkItems Include="$(WorkItemArchiveWildCard)" Exclude="$(HelixCorrelationPayload)" /> - <_WorkItem Include="$(TestArchiveRoot)browseronly/**/*.zip" Condition="'$(TargetOS)' == 'Browser' and '$(Scenario)' == 'WasmTestOnBrowser'" /> - - + %(Identity) $(HelixCommand) $(_workItemTimeout) - - - - <_BuildWasmAppsPayloadArchive>@(_WorkItem) - <_WasmDebuggerTestsPayloadArchive>@(_WorkItem) - - - - - $(_BuildWasmAppsPayloadArchive) - set "HELIX_XUNIT_ARGS=-class %(Identity)" - export "HELIX_XUNIT_ARGS=-class %(Identity)" - $(HelixCommand) - $(_workItemTimeout) - - - - - - $(_WasmDebuggerTestsPayloadArchive) - - - set TEST_ARGS=--filter "FullyQualifiedName~%(Identity)&Category^!=windows-failing" - export TEST_ARGS="--filter FullyQualifiedName~%(Identity)&Category!=linux-failing" - - $(HelixCommand) - $(_workItemTimeout) - - - - - - <_WasmSampleZipFile Condition="'$(Scenario)' == 'normal' or '$(Scenario)' == ''" Include="$(TestArchiveRoot)runonly/**/*.Console.V8.*.Sample.zip" /> - <_WasmSampleZipFile Condition="'$(Scenario)' == 'WasmTestOnNodeJs'" Include="$(TestArchiveRoot)runonly/**/*.Console.Node.*.Sample.zip" /> - <_WasmSampleZipFile Condition="'$(Scenario)' == 'WasmTestOnBrowser'" Include="$(TestArchiveRoot)runonly/**/*.Browser.*.Sample.zip" /> - - - %(Identity) - $(HelixCommand) - $(_workItemTimeout) - - - - - - - - - <_TestPath Condition="'%(XHarnessAppBundleToTest.CustomCommands)' != ''">$([System.IO.Path]::GetDirectoryName('%(XHarnessAppBundleToTest.Identity)')) - - - + + - - - - - - - + - - <_EmSdkFiles Include="$(EMSDK_PATH)\**\*" Exclude="$(EMSDK_PATH)\.git\**\*" /> - + - + diff --git a/src/libraries/tests.proj b/src/libraries/tests.proj index c0d361ba8dbfa..d9391e0ec2c9d 100644 --- a/src/libraries/tests.proj +++ b/src/libraries/tests.proj @@ -84,6 +84,8 @@ Roslyn4.0.Tests.csproj" /> + + @@ -115,9 +117,6 @@ Roslyn4.0.Tests.csproj" /> - - - @@ -134,7 +133,6 @@ Roslyn4.0.Tests.csproj" /> - @@ -166,7 +164,6 @@ Roslyn4.0.Tests.csproj" /> - @@ -179,9 +176,6 @@ Roslyn4.0.Tests.csproj" /> - - - @@ -228,8 +222,6 @@ Roslyn4.0.Tests.csproj" /> - - @@ -283,9 +275,6 @@ Roslyn4.0.Tests.csproj" /> - - - @@ -307,9 +296,6 @@ Roslyn4.0.Tests.csproj" /> - - - @@ -331,19 +317,6 @@ Roslyn4.0.Tests.csproj" /> - - - - - - - - - - - - - @@ -361,17 +334,30 @@ Roslyn4.0.Tests.csproj" /> + + + + + - + + + + + + + + + diff --git a/src/mono/Directory.Build.props b/src/mono/Directory.Build.props index 64cbb38bceab8..0ab0f8ac2a557 100644 --- a/src/mono/Directory.Build.props +++ b/src/mono/Directory.Build.props @@ -17,7 +17,7 @@ 10.0 2.0 5.1 - 10.13 + 10.14 11.0 diff --git a/src/mono/System.Private.CoreLib/System.Private.CoreLib.csproj b/src/mono/System.Private.CoreLib/System.Private.CoreLib.csproj index cb143f5d381be..da99b06e81b8e 100644 --- a/src/mono/System.Private.CoreLib/System.Private.CoreLib.csproj +++ b/src/mono/System.Private.CoreLib/System.Private.CoreLib.csproj @@ -290,6 +290,7 @@ + diff --git a/src/mono/System.Private.CoreLib/src/ILLink/ILLink.Descriptors.xml b/src/mono/System.Private.CoreLib/src/ILLink/ILLink.Descriptors.xml index 4a8ffce034109..2f578bdf50ab6 100644 --- a/src/mono/System.Private.CoreLib/src/ILLink/ILLink.Descriptors.xml +++ b/src/mono/System.Private.CoreLib/src/ILLink/ILLink.Descriptors.xml @@ -647,5 +647,8 @@ + + + diff --git a/src/mono/System.Private.CoreLib/src/Mono/HotReload.cs b/src/mono/System.Private.CoreLib/src/Mono/HotReload.cs new file mode 100644 index 0000000000000..c1cd977ceb6b2 --- /dev/null +++ b/src/mono/System.Private.CoreLib/src/Mono/HotReload.cs @@ -0,0 +1,114 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Mono.HotReload; + +// TODO: this is just a sketch, instance field additions aren't supported by Mono yet until https://github.com/dotnet/runtime/issues/63643 is fixed +#if false +internal class InstanceFieldTable +{ + // Q: Does CoreCLR EnC allow adding fields to a valuetype? + // A: No, see EEClass::AddField - if the type has layout or is a valuetype, you can't add fields to it. + + // See EnCAddedField::Allocate for a description of the CoreCLR version of this. + // + // This is substantially the same design, except instead of using dependent handles + // (ephemerons) directly from native (storing a linked list of ephemerons off the sync block + // of the instance), we use a ConditionalWeakTable from managed that's keyed on the + // instances (so the value dies when the instance dies) and whose value is another + // dictionary, keyed on the fielddef token with values that are storage for the actual field values. + // + // for reference types, the storage just stores it as an object. For valuetypes and + // primitives, the storage stores the value as a boxed value. + // + // The whole thing is basically a ConditionalWeakTable> but + // with locking on the inner dictionary. + // + + // This should behave somewhat like EditAndContinueModule::ResolveOrAddField (and EnCAddedField::Allocate) + // we want to create some storage space that has the same lifetime as the instance object. + + // // TODO: should the linker keep this if Hot Reload stuff is enabled? Hot Reload is predicated on the linker not rewriting user modules, but maybe trimming SPC is ok? + internal static FieldStore GetInstanceFieldFieldStore(object inst, RuntimeTypeHandle type, uint fielddef_token) + => _singleton.GetOrCreateInstanceFields(inst).LookupOrAdd(type, fielddef_token); + + private static InstanceFieldTable _singleton = new(); + + private ConditionalWeakTable _table; + + private InstanceFieldTable() + { + _table = new(); + } + + private InstanceFields GetOrCreateInstanceFields(object key) + => _table.GetOrCreateValue(key); + + private class InstanceFields + { + private Dictionary _fields; + private object _lock; + + public InstanceFields() + { + _fields = new(); + _lock = new(); + } + + public FieldStore LookupOrAdd(RuntimeTypeHandle type, uint key) + { + if (_fields.TryGetValue(key, out FieldStore? v)) + return v; + lock (_lock) + { + if (_fields.TryGetValue (key, out FieldStore? v2)) + return v2; + + FieldStore s = FieldStore.Create(type); + _fields.Add(key, s); + return s; + } + } + } + +} +#endif + +// This is similar to System.Diagnostics.EditAndContinueHelper in CoreCLR, except instead of +// having the allocation logic in native (see EditAndContinueModule::ResolveOrAllocateField, +// and EnCSyncBlockInfo::ResolveOrAllocateField), the logic is in managed. +// +// Additionally Mono uses this for storing added static fields. +[StructLayout(LayoutKind.Sequential)] +internal class FieldStore +{ + // keep in sync with hot_reload-internals.h + private object? _loc; + + private FieldStore (object? loc) + { + _loc = loc; + } + + public object? Location => _loc; + + public static FieldStore Create (RuntimeTypeHandle type) + { + Type t = Type.GetTypeFromHandle(type) ?? throw new ArgumentException(nameof(type), "Type handle was null"); + object? loc; + if (t.IsPrimitive || t.IsValueType) + loc = RuntimeHelpers.GetUninitializedObject(t); + else if (t.IsClass || t.IsInterface) + loc = null; + else + throw new ArgumentException("EnC: Expected a primitive, valuetype, class or interface field"); + /* FIXME: do we want FieldStore to be pinned? */ + return new FieldStore(loc); + } +} diff --git a/src/mono/System.Private.CoreLib/src/System/Math.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Math.Mono.cs index b2bf6baadd57c..eb0024f983e64 100644 --- a/src/mono/System.Private.CoreLib/src/System/Math.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Math.Mono.cs @@ -7,12 +7,6 @@ namespace System { public partial class Math { - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern double Abs(double value); - - [MethodImpl(MethodImplOptions.InternalCall)] - public static extern float Abs(float value); - [MethodImpl(MethodImplOptions.InternalCall)] public static extern double Acos(double d); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs index 973eb43d91ca7..afac9bf5e88da 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Metadata/MetadataUpdater.cs @@ -55,7 +55,8 @@ public static void ApplyUpdate(Assembly assembly, ReadOnlySpan metadataDel private static string InitializeApplyUpdateCapabilities() { - return ApplyUpdateEnabled(justComponentCheck: 1) != 0 ? "Baseline" : string.Empty ; + const string caps = "Baseline AddMethodToExistingType AddStaticFieldToExistingType NewTypeDefinition"; + return ApplyUpdateEnabled(justComponentCheck: 1) != 0 ? caps : string.Empty ; } [MethodImpl (MethodImplOptions.InternalCall)] diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs index 6f17c5f14c0bd..5fbe196a1ab08 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeAssembly.cs @@ -38,6 +38,14 @@ namespace System.Reflection [StructLayout(LayoutKind.Sequential)] internal sealed class RuntimeAssembly : Assembly { + private enum AssemblyInfoKind + { + Location = 1, + CodeBase = 2, + FullName = 3, + ImageRuntimeVersion = 4 + } + private sealed class ResolveEventHolder { public event ModuleResolveEventHandler? ModuleResolve; @@ -65,30 +73,26 @@ public unsafe UnmanagedMemoryStreamForModule(byte* pointer, long length, Module private ResolveEventHolder? resolve_event_holder; - public extern override MethodInfo? EntryPoint - { - [MethodImplAttribute(MethodImplOptions.InternalCall)] - get; - } - - public override bool ReflectionOnly => false; + [MethodImplAttribute(MethodImplOptions.InternalCall)] + private static extern void GetEntryPoint(QCallAssembly assembly, ObjectHandleOnStack res); - [RequiresAssemblyFiles(ThrowingMessageInRAF)] - public override string? CodeBase + public override MethodInfo? EntryPoint { get { - return get_code_base(this); + var this_assembly = this; + MethodInfo? res = null; + GetEntryPoint(new QCallAssembly(ref this_assembly), ObjectHandleOnStack.Create(ref res)); + return res; } } - public override string? FullName - { - get - { - return get_fullname(this); - } - } + public override bool ReflectionOnly => false; + + [RequiresAssemblyFiles(ThrowingMessageInRAF)] + public override string? CodeBase => GetInfo(AssemblyInfoKind.CodeBase); + + public override string? FullName => GetInfo(AssemblyInfoKind.FullName); // // We can't store the event directly in this class, since the @@ -106,22 +110,25 @@ public override event ModuleResolveEventHandler? ModuleResolve } } - public override Module ManifestModule => GetManifestModuleInternal(); + public override Module ManifestModule + { + get + { + var this_assembly = this; + Module? res = null; + GetManifestModuleInternal(new QCallAssembly(ref this_assembly), ObjectHandleOnStack.Create(ref res)); + return res!; + } + } [Obsolete(Obsoletions.GlobalAssemblyCacheMessage, DiagnosticId = Obsoletions.GlobalAssemblyCacheDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public override bool GlobalAssemblyCache => false; public override long HostContext => 0; - public override string ImageRuntimeVersion => InternalImageRuntimeVersion(this); + public override string ImageRuntimeVersion => GetInfo(AssemblyInfoKind.ImageRuntimeVersion)!; - public override string Location - { - get - { - return get_location(); - } - } + public override string Location => GetInfo(AssemblyInfoKind.Location)!; // TODO: consider a dedicated icall instead public override bool IsCollectible => AssemblyLoadContext.GetLoadContext((Assembly)this)!.IsCollectible; @@ -150,23 +157,41 @@ public override string Location } [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern override string[] GetManifestResourceNames(); + private static extern void GetManifestResourceNames(QCallAssembly assembly_h, ObjectHandleOnStack res); + + public override string[] GetManifestResourceNames() + { + var this_assembly = this; + string[]? res = null; + GetManifestResourceNames(new QCallAssembly(ref this_assembly), ObjectHandleOnStack.Create(ref res)); + return res!; + } - [RequiresUnreferencedCode("Types might be removed")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - public extern override Type[] GetExportedTypes(); + private static extern void GetExportedTypes(QCallAssembly assembly_h, ObjectHandleOnStack res); + + [RequiresUnreferencedCode("Types might be removed")] + public override Type[] GetExportedTypes() + { + var this_assembly = this; + Type[]? res = null; + GetExportedTypes(new QCallAssembly(ref this_assembly), ObjectHandleOnStack.Create(ref res)); + return res!; + } [MethodImplAttribute(MethodImplOptions.InternalCall)] - internal extern Type[] GetTopLevelForwardedTypes(); + private static extern void GetTopLevelForwardedTypes(QCallAssembly assembly_h, ObjectHandleOnStack res); [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetForwardedTypes() { - Type[] topLevelTypes = GetTopLevelForwardedTypes(); - List forwardedTypes = new List(topLevelTypes); + var this_assembly = this; + Type[]? topLevelTypes = null; + GetTopLevelForwardedTypes(new QCallAssembly(ref this_assembly), ObjectHandleOnStack.Create(ref topLevelTypes)); + List forwardedTypes = new List(topLevelTypes!); List exceptions = new List(); - foreach (Type t in topLevelTypes) + foreach (Type t in topLevelTypes!) AddPublicNestedTypes(t, forwardedTypes, exceptions); if (exceptions.Count > 0) @@ -208,7 +233,8 @@ private static void AddPublicNestedTypes(Type type, List types, List types, List types, Listcorlib, name_space, name); \ - tmp_class = klass; \ - mono_memory_barrier (); \ - inited = TRUE; \ - } \ - return klass; \ -} - #ifndef MONO_HANDLE_TRACK_OWNER #define MONO_HANDLE_NEW_DBG(type, object) \ @@ -162,13 +145,13 @@ mono_class_try_get_##shortname##_class (void) \ static inline MonoType* mono_get_object_type_dbg (void) { - return m_class_get_byval_arg (mdbg_mono_defaults->object_class); + return m_class_get_byval_arg (mono_get_object_class ()); } static inline MonoType* mono_get_void_type_dbg (void) { - return m_class_get_byval_arg (mdbg_mono_defaults->void_class); + return m_class_get_byval_arg (mono_get_void_class ()); } typedef struct { @@ -420,8 +403,6 @@ static gint32 suspend_count; /* Whenever to buffer reply messages and send them together */ static gboolean buffer_replies; -MonoDefaults *mdbg_mono_defaults; - #ifndef TARGET_WASM #define GET_TLS_DATA_FROM_THREAD(thread) \ DebuggerTlsData *tls = NULL; \ @@ -532,7 +513,7 @@ static int handle_multiple_ss_requests (void); static void mono_dbg_debugger_agent_user_break (void); -static GENERATE_TRY_GET_CLASS_WITH_CACHE_DBG (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute") +static GENERATE_TRY_GET_CLASS_WITH_CACHE (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute") #ifndef DISABLE_SOCKET_TRANSPORT static void @@ -744,13 +725,11 @@ mono_debugger_is_disconnected (void) } static void -debugger_agent_init (MonoDefaults *mono_defaults) +debugger_agent_init (void) { if (!agent_config.enabled) return; - mdbg_mono_defaults = mono_defaults; - DebuggerEngineCallbacks cbs; memset (&cbs, 0, sizeof (cbs)); cbs.tls_get_restore_state = tls_get_restore_state; @@ -2498,7 +2477,7 @@ process_suspend (DebuggerTlsData *tls, MonoContext *ctx) g_assert (ji); /* Can't suspend in these methods */ method = jinfo_get_method (ji); - if (method->klass == mdbg_mono_defaults->string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy"))) + if (method->klass == mono_get_string_class () && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy"))) return; save_thread_context (ctx); @@ -2945,7 +2924,7 @@ static gint32 isFixedSizeArray (MonoClassField *f) CattrNamedArg *arginfo; int num_named_args; - mono_reflection_create_custom_attr_data_args_noalloc (mdbg_mono_defaults->corlib, attr->ctor, attr->data, attr->data_size, + mono_reflection_create_custom_attr_data_args_noalloc (mono_get_corlib (), attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &num_named_args, &arginfo, error); if (!is_ok (error)) { ret = 0; @@ -3244,9 +3223,9 @@ dbg_path_get_basename (const char *filename) return g_strdup (&r[1]); } -static GENERATE_TRY_GET_CLASS_WITH_CACHE_DBG (hidden_klass, "System.Diagnostics", "DebuggerHiddenAttribute") -static GENERATE_TRY_GET_CLASS_WITH_CACHE_DBG (step_through_klass, "System.Diagnostics", "DebuggerStepThroughAttribute") -static GENERATE_TRY_GET_CLASS_WITH_CACHE_DBG (non_user_klass, "System.Diagnostics", "DebuggerNonUserCodeAttribute") +static GENERATE_TRY_GET_CLASS_WITH_CACHE (hidden_klass, "System.Diagnostics", "DebuggerHiddenAttribute") +static GENERATE_TRY_GET_CLASS_WITH_CACHE (step_through_klass, "System.Diagnostics", "DebuggerStepThroughAttribute") +static GENERATE_TRY_GET_CLASS_WITH_CACHE (non_user_klass, "System.Diagnostics", "DebuggerNonUserCodeAttribute") static void init_jit_info_dbg_attrs (MonoJitInfo *ji) @@ -3769,7 +3748,7 @@ runtime_initialized (MonoProfiler *prof) { process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ()); if (CHECK_PROTOCOL_VERSION (2, 59)) - process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, (mdbg_mono_defaults->corlib->assembly)); + process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, (mono_get_corlib ()->assembly)); if (agent_config.defer) { ERROR_DECL (error); start_debugger_thread (error); @@ -4767,7 +4746,7 @@ static void debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx, MonoContext *catch_ctx, StackFrameInfo *catch_frame) { - if (catch_ctx == NULL && catch_frame == NULL && get_mini_debug_options ()->suspend_on_unhandled && mono_object_class (exc) != mdbg_mono_defaults->threadabortexception_class) { + if (catch_ctx == NULL && catch_frame == NULL && get_mini_debug_options ()->suspend_on_unhandled && mono_object_class (exc) != mono_get_defaults ()->threadabortexception_class) { mono_runtime_printf_err ("Unhandled exception, suspending..."); while (1) ; @@ -5489,7 +5468,8 @@ decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, */ buf2 = buf; decode_byte (buf, &buf, limit); - decode_byte (buf, &buf, limit); //ignore is boxed + if (CHECK_PROTOCOL_VERSION(2, 61)) + decode_byte (buf, &buf, limit); //ignore is boxed klass = decode_typeid (buf, &buf, limit, &d, &err); if (err != ERR_NONE) return err; @@ -6528,7 +6508,7 @@ module_apply_changes (MonoImage *image, MonoArray *dmeta, MonoArray *dil, MonoAr static void buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val) { - if (val && val->vtable->klass == mdbg_mono_defaults->runtimetype_class) { + if (val && val->vtable->klass == mono_get_defaults ()->runtimetype_class) { /* Special case these so the client doesn't have to handle Type objects */ buffer_add_byte (buf, VALUE_TYPE_ID_TYPE); @@ -6733,7 +6713,7 @@ vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf) wait_for_suspend (); #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT - env_class = mono_class_try_load_from_name (mdbg_mono_defaults->corlib, "System", "Environment"); + env_class = mono_class_try_load_from_name (mono_get_corlib (), "System", "Environment"); if (env_class) { ERROR_DECL (error); exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error); @@ -7114,7 +7094,7 @@ event_commands (int command, guint8 *p, guint8 *end, Buffer *buf) if (exc_class) { req->modifiers [i].data.exc_class = exc_class; - if (!mono_class_is_assignable_from_internal (mdbg_mono_defaults->exception_class, exc_class)) { + if (!mono_class_is_assignable_from_internal (mono_get_exception_class (), exc_class)) { g_free (req); return ERR_INVALID_ARGUMENT; } @@ -8728,19 +8708,19 @@ method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, g g_error ("Could not load token due to %s", mono_error_get_message (error)); } - if (handle_class == mdbg_mono_defaults->typehandle_class) { + if (handle_class == mono_get_defaults ()->typehandle_class) { buffer_add_byte (buf, TOKEN_TYPE_TYPE); if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) buffer_add_typeid (buf, domain, (MonoClass *) val); else buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val)); - } else if (handle_class == mdbg_mono_defaults->fieldhandle_class) { + } else if (handle_class == mono_get_defaults ()->fieldhandle_class) { buffer_add_byte (buf, TOKEN_TYPE_FIELD); buffer_add_fieldid (buf, domain, (MonoClassField *)val); - } else if (handle_class == mdbg_mono_defaults->methodhandle_class) { + } else if (handle_class == mono_get_defaults ()->methodhandle_class) { buffer_add_byte (buf, TOKEN_TYPE_METHOD); buffer_add_methodid (buf, domain, (MonoMethod *)val); - } else if (handle_class == mdbg_mono_defaults->string_class) { + } else if (handle_class == mono_get_string_class ()) { char *s; s = mono_string_to_utf8_checked_internal ((MonoString *)val, error); diff --git a/src/mono/mono/component/debugger-engine.c b/src/mono/mono/component/debugger-engine.c index e1040a861c84c..5083e3b68c819 100644 --- a/src/mono/mono/component/debugger-engine.c +++ b/src/mono/mono/component/debugger-engine.c @@ -812,7 +812,7 @@ mono_de_process_single_step (void *tls, gboolean from_signal) * Stopping in memset makes half-initialized vtypes visible. * Stopping in memcpy makes half-copied vtypes visible. */ - if (method->klass == mdbg_mono_defaults->string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy"))) + if (method->klass == mono_get_string_class () && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy"))) goto exit; /* @@ -1719,7 +1719,7 @@ get_notify_debugger_of_wait_completion_method (void) if (notify_debugger_of_wait_completion_method_cache != NULL) return notify_debugger_of_wait_completion_method_cache; ERROR_DECL (error); - MonoClass* task_class = mono_class_load_from_name (mdbg_mono_defaults->corlib, "System.Threading.Tasks", "Task"); + MonoClass* task_class = mono_class_load_from_name (mono_get_corlib (), "System.Threading.Tasks", "Task"); GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, 1, FALSE, error); mono_error_assert_ok (error); g_assert (array->len == 1); diff --git a/src/mono/mono/component/debugger-stub.c b/src/mono/mono/component/debugger-stub.c index 224f531f79648..4235a97eb5017 100644 --- a/src/mono/mono/component/debugger-stub.c +++ b/src/mono/mono/component/debugger-stub.c @@ -16,7 +16,7 @@ static void stub_debugger_parse_options (char *options); static void -stub_debugger_init (MonoDefaults *mono_defaults); +stub_debugger_init (void); static void stub_debugger_breakpoint_hit (void *sigctx); @@ -113,7 +113,7 @@ stub_debugger_parse_options (char *options) } static void -stub_debugger_init (MonoDefaults *mono_defaults) +stub_debugger_init (void) { } diff --git a/src/mono/mono/component/debugger.h b/src/mono/mono/component/debugger.h index a573750b1fa9f..633bfc492cc03 100644 --- a/src/mono/mono/component/debugger.h +++ b/src/mono/mono/component/debugger.h @@ -172,7 +172,7 @@ typedef struct _DebuggerTlsData DebuggerTlsData; typedef struct MonoComponentDebugger { MonoComponent component; - void (*init) (MonoDefaults *mono_defaults); + void (*init) (void); void (*user_break) (void); void (*parse_options) (char *options); void (*breakpoint_hit) (void *sigctx); @@ -199,8 +199,6 @@ typedef struct MonoComponentDebugger { } MonoComponentDebugger; -extern MonoDefaults *mdbg_mono_defaults; - #define DE_ERR_NONE 0 // WARNING WARNING WARNING // Error codes MUST match those of sdb for now diff --git a/src/mono/mono/component/hot_reload-internals.h b/src/mono/mono/component/hot_reload-internals.h new file mode 100644 index 0000000000000..36d3606e17e4a --- /dev/null +++ b/src/mono/mono/component/hot_reload-internals.h @@ -0,0 +1,53 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// + +#ifndef _MONO_COMPONENT_HOT_RELOAD_INTERNALS_H +#define _MONO_COMPONENT_HOT_RELOAD_INTERNALS_H + +#include +#include "mono/metadata/object-forward.h" +#include "mono/metadata/metadata-internals.h" +#include "mono/metadata/class-internals.h" + +/* Execution-time info for an updated class. */ +typedef struct _MonoClassRuntimeMetadataUpdateInfo { + MonoCoopMutex static_fields_lock; /* protects the static_fields hashtable. Values can be used outside the lock (since they're allocated pinned). */ + MonoGHashTable *static_fields; /* key is field token, value is a pinned managed object: either a boxed valuetype (the static field address is the value address) or a Mono.HotReload.FieldStore object (in which case the static field address is the address of the _loc field in the object.) */ + gboolean inited; +} MonoClassRuntimeMetadataUpdateInfo; + +/* Class-specific metadata update info. See + * mono_class_get_metadata_update_info() Note that this info is associated with + * class _definitions_ that can be edited, so primitives, generic instances, + * arrays, pointers, etc do not have this info. + */ +struct _MonoClassMetadataUpdateInfo { + /* FIXME: use a struct that allocates out of the MonoClass mempool! or maybe add the GArray + * to the BaselineInfo for the image and cleanup from there. */ + GSList *added_members; /* a set of Method or Field table tokens of any methods or fields added to this class, allocated from the MonoClass mempool */ + + GPtrArray *added_fields; /* a set of MonoClassMetadataUpdateField* values for every added field. */ + + MonoClassRuntimeMetadataUpdateInfo runtime; +}; + + +/* Keep in sync with Mono.HotReload.FieldStore in managed */ +typedef struct _MonoHotReloadFieldStoreObject { + MonoObject object; + MonoObject *_loc; +} MonoHotReloadFieldStoreObject; + +typedef struct _MonoClassMetadataUpdateField { + MonoClassField field; + uint32_t generation; /* when this field was added */ + uint32_t token; /* the Field table token where this field was defined. (this won't make + * sense for generic instances, once EnC is supported there) */ + /* if non-zero the EnC update came before the parent class was initialized. The field is + * stored in the instance at this offset. MonoClassField:offset is -1. Not used for static + * fields. */ + int before_init_instance_offset; +} MonoClassMetadataUpdateField; + +#endif/*_MONO_COMPONENT_HOT_RELOAD_INTERNALS_H*/ diff --git a/src/mono/mono/component/hot_reload-stub.c b/src/mono/mono/component/hot_reload-stub.c index 6064a6a78f875..2377b948a7b0a 100644 --- a/src/mono/mono/component/hot_reload-stub.c +++ b/src/mono/mono/component/hot_reload-stub.c @@ -65,12 +65,27 @@ hot_reload_stub_has_modified_rows (const MonoTableInfo *table); static int hot_reload_stub_table_num_rows_slow (MonoImage *image, int table_index); -static GArray* -hot_reload_stub_get_added_methods (MonoClass *klass); - static uint32_t hot_reload_stub_method_parent (MonoImage *image, uint32_t method_index); +static void* +hot_reload_stub_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer); + +static uint32_t +hot_reload_stub_field_parent (MonoImage *image, uint32_t field_index); + +static uint32_t +hot_reload_stub_get_field_idx (MonoClassField *field); + +static MonoClassField * +hot_reload_stub_get_field (MonoClass *klass, uint32_t fielddef_token); + +static gpointer +hot_reload_stub_get_static_field_addr (MonoClassField *field); + +static MonoMethod * +hot_reload_stub_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error); + static MonoComponentHotReload fn_table = { { MONO_COMPONENT_ITF_VERSION, &hot_reload_stub_available }, &hot_reload_stub_set_fastpath_data, @@ -89,8 +104,13 @@ static MonoComponentHotReload fn_table = { &hot_reload_stub_get_updated_method_ppdb, &hot_reload_stub_has_modified_rows, &hot_reload_stub_table_num_rows_slow, - &hot_reload_stub_get_added_methods, &hot_reload_stub_method_parent, + &hot_reload_stub_metadata_linear_search, + &hot_reload_stub_field_parent, + &hot_reload_stub_get_field_idx, + &hot_reload_stub_get_field, + &hot_reload_stub_get_static_field_addr, + &hot_reload_stub_find_method_by_name, }; static bool @@ -200,18 +220,49 @@ hot_reload_stub_table_num_rows_slow (MonoImage *image, int table_index) g_assert_not_reached (); /* should always take the fast path */ } -static GArray* -hot_reload_stub_get_added_methods (MonoClass *klass) +static uint32_t +hot_reload_stub_method_parent (MonoImage *image, uint32_t method_index) +{ + return 0; +} + + +static void* +hot_reload_stub_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer) { return NULL; } static uint32_t -hot_reload_stub_method_parent (MonoImage *image, uint32_t method_index) +hot_reload_stub_field_parent (MonoImage *image, uint32_t field_index) { return 0; } +static uint32_t +hot_reload_stub_get_field_idx (MonoClassField *field) +{ + return 0; +} + +static MonoClassField * +hot_reload_stub_get_field (MonoClass *klass, uint32_t fielddef_token) +{ + return NULL; +} + +static gpointer +hot_reload_stub_get_static_field_addr (MonoClassField *field) +{ + return NULL; +} + +static MonoMethod * +hot_reload_stub_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error) +{ + return NULL; +} + MONO_COMPONENT_EXPORT_ENTRYPOINT MonoComponentHotReload * diff --git a/src/mono/mono/component/hot_reload.c b/src/mono/mono/component/hot_reload.c index bd8c3db635c88..e44ae56e5f4af 100644 --- a/src/mono/mono/component/hot_reload.c +++ b/src/mono/mono/component/hot_reload.c @@ -8,8 +8,11 @@ #include #include "mono/utils/mono-compiler.h" +#include "mono/component/hot_reload-internals.h" + #include #include "mono/metadata/assembly-internals.h" +#include "mono/metadata/mono-hash-internals.h" #include "mono/metadata/metadata-internals.h" #include "mono/metadata/metadata-update.h" #include "mono/metadata/object-internals.h" @@ -22,14 +25,18 @@ #include "mono/metadata/debug-internals.h" #include "mono/metadata/mono-debug.h" #include "mono/metadata/debug-mono-ppdb.h" +#include "mono/utils/bsearch.h" #include #include -#undef ALLOW_METHOD_ADD +#define ALLOW_CLASS_ADD +#define ALLOW_METHOD_ADD +#define ALLOW_FIELD_ADD +typedef struct _BaselineInfo BaselineInfo; typedef struct _DeltaInfo DeltaInfo; static void @@ -89,12 +96,32 @@ hot_reload_has_modified_rows (const MonoTableInfo *table); static int hot_reload_table_num_rows_slow (MonoImage *image, int table_index); -static GArray* -hot_reload_get_added_methods (MonoClass *klass); +static GSList* +hot_reload_get_added_members (MonoClass *klass); static uint32_t hot_reload_method_parent (MonoImage *base, uint32_t method_token); +static void* +hot_reload_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer); + +static uint32_t +hot_reload_field_parent (MonoImage *base, uint32_t field_token); + +static uint32_t +hot_reload_get_field_idx (MonoClassField *field); + +static MonoClassField * +hot_reload_get_field (MonoClass *klass, uint32_t fielddef_token); + +static gpointer +hot_reload_get_static_field_addr (MonoClassField *field); + +static MonoMethod * +hot_reload_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error); + +static MonoClassMetadataUpdateField * +metadata_update_field_setup_basic_info_and_resolve (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, DeltaInfo *delta_info, MonoClass *parent_klass, uint32_t fielddef_token, MonoError *error); static MonoComponentHotReload fn_table = { { MONO_COMPONENT_ITF_VERSION, &hot_reload_available }, @@ -114,8 +141,13 @@ static MonoComponentHotReload fn_table = { &hot_reload_get_updated_method_ppdb, &hot_reload_has_modified_rows, &hot_reload_table_num_rows_slow, - &hot_reload_get_added_methods, &hot_reload_method_parent, + &hot_reload_metadata_linear_search, + &hot_reload_field_parent, + &hot_reload_get_field_idx, + &hot_reload_get_field, + &hot_reload_get_static_field_addr, + &hot_reload_find_method_by_name, }; MonoComponentHotReload * @@ -190,7 +222,7 @@ struct _DeltaInfo { /* Additional informaiton for baseline MonoImages */ -typedef struct _BaselineInfo { +struct _BaselineInfo { /* List of DeltaInfos of deltas*/ GList *delta_info; /* Tail of delta_info for fast appends */ @@ -202,9 +234,12 @@ typedef struct _BaselineInfo { /* TRUE if any published update modified an existing row */ gboolean any_modified_rows [MONO_TABLE_NUM]; - GHashTable *added_methods; /* maps each MonoClass to a GArray of added method tokens */ - GHashTable *method_parent; /* maps added methoddef tokens to typedef tokens */ -} BaselineInfo; + /* A list of MonoClassMetadataUpdateInfo* that need to be cleaned up */ + GSList *klass_info; + + /* Parents for added methods, fields, etc */ + GHashTable *member_parent; /* maps added methoddef or fielddef tokens to typedef tokens */ +}; #define DOTNET_MODIFIABLE_ASSEMBLIES "DOTNET_MODIFIABLE_ASSEMBLIES" @@ -312,11 +347,34 @@ baseline_info_init (MonoImage *image_base) return baseline_info; } +static void +klass_info_destroy (gpointer value, gpointer user_data G_GNUC_UNUSED) +{ + MonoClassMetadataUpdateInfo *info = (MonoClassMetadataUpdateInfo *)value; + /* added_members is allocated from the class mempool, don't free it here */ + /* The MonoClassMetadataUpdateField is allocated from the class mempool, don't free it here */ + g_ptr_array_free (info->added_fields, TRUE); + + if (info->runtime.static_fields) { + mono_g_hash_table_destroy (info->runtime.static_fields); + info->runtime.static_fields = NULL; + } + + mono_coop_mutex_destroy (&info->runtime.static_fields_lock); + + /* The MonoClassMetadataUpdateInfo itself is allocated from the class mempool, don't free it here */ +} + static void baseline_info_destroy (BaselineInfo *info) { if (info->method_table_update) g_hash_table_destroy (info->method_table_update); + + if (info->klass_info) { + g_slist_foreach (info->klass_info, klass_info_destroy, NULL); + g_slist_free (info->klass_info); + } g_free (info); } @@ -515,9 +573,15 @@ image_open_dmeta_from_data (MonoImage *base_image, uint32_t generation, gconstpo static DeltaInfo* image_append_delta (MonoImage *base, BaselineInfo *base_info, MonoImage *delta, DeltaInfo *delta_info); +/* common method, don't use directly, use add_method_to_baseline, add_field_to_baseline, etc */ +static void +add_member_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t member_token); + static void add_method_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t method_token, MonoDebugInformationEnc* pdb_address); +static void +add_field_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t field_token); void hot_reload_init (void) @@ -660,6 +724,33 @@ hot_reload_update_cancel (uint32_t generation) publish_unlock (); } +static void +add_class_info_to_baseline (MonoClass *klass, MonoClassMetadataUpdateInfo *klass_info) +{ + MonoImage *image = m_class_get_image (klass); + BaselineInfo *baseline_info = baseline_info_lookup (image); + baseline_info->klass_info = g_slist_prepend (baseline_info->klass_info, klass_info); +} + +static MonoClassMetadataUpdateInfo * +mono_class_get_or_add_metadata_update_info (MonoClass *klass) +{ + MonoClassMetadataUpdateInfo *info = NULL; + info = mono_class_get_metadata_update_info (klass); + if (info) + return info; + mono_loader_lock (); + info = mono_class_get_metadata_update_info (klass); + if (!info) { + info = mono_class_alloc0 (klass, sizeof (MonoClassMetadataUpdateInfo)); + add_class_info_to_baseline (klass, info); + mono_class_set_metadata_update_info (klass, info); + } + mono_loader_unlock (); + g_assert (info); + return info; +} + /* * Given a baseline and an (optional) previous delta, allocate space for new tables for the current delta. * @@ -695,12 +786,6 @@ delta_info_initialize_mutants (const MonoImage *base, const BaselineInfo *base_i guint32 rows = count->prev_gen_rows + count->inserted_rows; - MonoTableInfo *tbl = &delta->mutants [i]; - tbl->row_size = base->tables[i].row_size; - tbl->size_bitfield = base->tables[i].size_bitfield; - tbl->rows_ = rows; - - tbl->base = mono_mempool_alloc (delta->pool, tbl->row_size * rows); const MonoTableInfo *prev_table; if (!prev_delta || prev_delta->mutants [i].base == NULL) prev_table = &base->tables [i]; @@ -708,6 +793,21 @@ delta_info_initialize_mutants (const MonoImage *base, const BaselineInfo *base_i prev_table = &prev_delta->mutants [i]; g_assert (prev_table != NULL); + + MonoTableInfo *tbl = &delta->mutants [i]; + if (prev_table->rows_ == 0) { + /* table was empty in the baseline and it was empty in the prior generation, but now we have some rows. Use the format of the mutant table. */ + g_assert (prev_table->row_size == 0); + tbl->row_size = delta->delta_image->tables [i].row_size; + tbl->size_bitfield = delta->delta_image->tables [i].size_bitfield; + } else { + tbl->row_size = prev_table->row_size; + tbl->size_bitfield = prev_table->size_bitfield; + } + tbl->rows_ = rows; + g_assert (tbl->rows_ > 0 && tbl->row_size != 0); + + tbl->base = mono_mempool_alloc (delta->pool, tbl->row_size * rows); g_assert (table_info_get_rows (prev_table) == count->prev_gen_rows); /* copy the old rows and zero out the new ones */ @@ -877,8 +977,13 @@ dump_update_summary (MonoImage *image_base, MonoImage *image_dmeta) } +/* + * Finds the latest mutated version of the table given by tbl_index + * + * On success returns TRUE, modifies *t and optionally updates *delta_out + */ static gboolean -effective_table_mutant (MonoImage *base, BaselineInfo *info, int tbl_index, const MonoTableInfo **t, int idx) +effective_table_mutant (MonoImage *base, BaselineInfo *info, int tbl_index, const MonoTableInfo **t, DeltaInfo **delta_out) { GList *ptr =info->delta_info_last; uint32_t exposed_gen = hot_reload_get_thread_generation (); @@ -899,6 +1004,8 @@ effective_table_mutant (MonoImage *base, BaselineInfo *info, int tbl_index, cons g_assert (delta_info != NULL); *t = &delta_info->mutants [tbl_index]; + if (delta_out) + *delta_out = delta_info; return TRUE; } @@ -917,7 +1024,7 @@ hot_reload_effective_table_slow (const MonoTableInfo **t, int idx) if (!info) return; - gboolean success = effective_table_mutant (base, info, tbl_index, t, idx); + gboolean success = effective_table_mutant (base, info, tbl_index, t, NULL); g_assert (success); } @@ -1129,7 +1236,7 @@ funccode_to_str (int func_code) * */ static void -delta_info_mutate_row (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *cur_delta, guint32 log_token) +delta_info_mutate_row (MonoImage *image_dmeta, DeltaInfo *cur_delta, guint32 log_token) { int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); /* 1-based */ @@ -1139,16 +1246,16 @@ delta_info_mutate_row (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo int delta_index = hot_reload_relative_delta_index (image_dmeta, cur_delta, log_token); /* The complication here is that we want the mutant table to look like the table in - * image_base with respect to column widths, but the delta tables are generally coming in + * the baseline image with respect to column widths, but the delta tables are generally coming in * uncompressed (4-byte columns). So we have to copy one column at a time and adjust the * widths as we go. */ - guint32 dst_bitfield = image_base->tables [token_table].size_bitfield; + guint32 dst_bitfield = cur_delta->mutants [token_table].size_bitfield; guint32 src_bitfield = image_dmeta->tables [token_table].size_bitfield; const char *src_base = image_dmeta->tables [token_table].base + (delta_index - 1) * image_dmeta->tables [token_table].row_size; - char *dst_base = (char*)cur_delta->mutants [token_table].base + (token_index - 1) * image_base->tables [token_table].row_size; + char *dst_base = (char*)cur_delta->mutants [token_table].base + (token_index - 1) * cur_delta->mutants [token_table].row_size; guint32 src_offset = 0, dst_offset = 0; for (int col = 0; col < mono_metadata_table_count (dst_bitfield); ++col) { @@ -1190,12 +1297,11 @@ delta_info_mutate_row (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo default: g_assert_not_reached (); } - } src_offset += src_col_size; dst_offset += dst_col_size; } - g_assert (dst_offset == image_base->tables [token_table].row_size); + g_assert (dst_offset == cur_delta->mutants [token_table].row_size); mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "mutate: table=0x%02x row=0x%04x delta row=0x%04x %s", token_table, token_index, delta_index, modified ? "Mod" : "Add"); } @@ -1215,7 +1321,7 @@ prepare_mutated_rows (const MonoTableInfo *table_enclog, MonoImage *image_base, if (func_code != ENC_FUNC_DEFAULT) continue; - delta_info_mutate_row (image_base, image_dmeta, delta_info, log_token); + delta_info_mutate_row (image_dmeta, delta_info, log_token); } } @@ -1248,7 +1354,10 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); - mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x (%s idx=0x%02x) (base table has 0x%04x rows)\tfunc=0x%02x (\"%s\")\n", i, log_token, mono_meta_table_name (token_table), token_index, table_info_get_rows (&image_base->tables [token_table]), func_code, funccode_to_str (func_code)); + gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; + + + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x (%s idx=0x%02x) (base table has 0x%04x rows; prev gen had 0x%04x rows)\t%s\tfunc=0x%02x (\"%s\")\n", i, log_token, mono_meta_table_name (token_table), token_index, table_info_get_rows (&image_base->tables [token_table]), delta_info->count[token_table].prev_gen_rows, (is_addition ? "ADD" : "UPDATE"), func_code, funccode_to_str (func_code)); if (token_table != MONO_TABLE_METHOD) @@ -1256,7 +1365,7 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de #ifndef ALLOW_METHOD_ADD - if (token_index > table_info_get_rows (&image_base->tables [token_table])) { + if (is_addition) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "\tcannot add new method with token 0x%08x", log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: cannot add new method with token 0x%08x", log_token); unsupported_edits = TRUE; @@ -1266,8 +1375,7 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de #ifdef ALLOW_METHOD_ADD /* adding a new parameter to a new method is ok */ - /* FIXME: total rows, not just the baseline rows */ - if (func_code == ENC_FUNC_ADD_PARAM && token_index > table_info_get_rows (&image_base->tables [token_table])) + if (func_code == ENC_FUNC_ADD_PARAM && is_addition) continue; #endif @@ -1284,6 +1392,8 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); + gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; + switch (token_table) { case MONO_TABLE_ASSEMBLYREF: /* okay, supported */ @@ -1295,9 +1405,20 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de #endif /* handled above */ break; + case MONO_TABLE_FIELD: +#ifdef ALLOW_FIELD_ADD + if (func_code == ENC_FUNC_DEFAULT) + continue; /* ok, allowed */ +#else + /* adding or modifying a field */ + mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support adding or modifying fields.", i, log_token); + mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding or modifying fields. token=0x%08x", log_token); + unsupported_edits = TRUE; + break; +#endif case MONO_TABLE_PROPERTY: { /* modifying a property, ok */ - if (token_index <= table_info_get_rows (&image_base->tables [token_table])) + if (!is_addition) break; /* adding a property */ mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support adding new properties.", i, log_token); @@ -1306,8 +1427,7 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de continue; } case MONO_TABLE_METHODSEMANTICS: { - /* FIXME: this should get the current table size, not the base stable size */ - if (token_index > table_info_get_rows (&image_base->tables [token_table])) { + if (is_addition) { /* new rows are fine, as long as they point at existing methods */ guint32 sema_cols [MONO_METHOD_SEMA_SIZE]; int mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, mono_metadata_make_token (token_table, token_index)); @@ -1319,7 +1439,8 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de case METHOD_SEMANTIC_SETTER: { int prop_method_index = sema_cols [MONO_METHOD_SEMA_METHOD]; /* ok, if it's pointing to an existing getter/setter */ - if (prop_method_index < table_info_get_rows (&image_base->tables [MONO_TABLE_METHOD])) + gboolean is_prop_method_add = prop_method_index-1 >= delta_info->count[MONO_TABLE_METHOD].prev_gen_rows; + if (!is_prop_method_add) break; mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x adding new getter/setter method 0x%08x to a property is not supported", i, log_token, prop_method_index); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support adding a new getter or setter to a property, token=0x%08x", log_token); @@ -1340,8 +1461,7 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de } } case MONO_TABLE_CUSTOMATTRIBUTE: { - /* FIXME: this should get the current table size, not the base stable size */ - if (token_index <= table_info_get_rows (&image_base->tables [token_table])) { + if (!is_addition) { /* modifying existing rows is ok, as long as the parent and ctor are the same */ guint32 ca_upd_cols [MONO_CUSTOM_ATTR_SIZE]; guint32 ca_base_cols [MONO_CUSTOM_ATTR_SIZE]; @@ -1375,8 +1495,7 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de } } case MONO_TABLE_PARAM: { - /* FIXME: this should get the current table size, not the base stable size */ - if (token_index <= table_info_get_rows (&image_base->tables [token_table])) { + if (!is_addition) { /* We only allow modifications where the parameter name doesn't change. */ uint32_t base_param [MONO_PARAM_SIZE]; uint32_t upd_param [MONO_PARAM_SIZE]; @@ -1401,11 +1520,14 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de break; /* added a row. ok */ } case MONO_TABLE_TYPEDEF: { + gboolean new_class G_GNUC_UNUSED = is_addition; #ifdef ALLOW_METHOD_ADD - /* FIXME: wrong for cumulative updates - need to look at DeltaInfo:count.prev_gen_rows */ - gboolean new_class = token_index > table_info_get_rows (&image_base->tables [token_table]); /* only allow adding methods to existing classes for now */ - if (!new_class && func_code == ENC_FUNC_ADD_METHOD) { + if ( +#ifndef ALLOW_CLASS_ADD + !new_class && +#endif + func_code == ENC_FUNC_ADD_METHOD) { /* next record should be a MONO_TABLE_METHOD addition (func == default) */ g_assert (i + 1 < rows); guint32 next_cols [MONO_ENCLOG_SIZE]; @@ -1415,7 +1537,29 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de int next_table = mono_metadata_token_table (next_token); int next_index = mono_metadata_token_index (next_token); g_assert (next_table == MONO_TABLE_METHOD); - g_assert (next_index > table_info_get_rows (&image_base->tables [next_table])); + /* expecting an added method */ + g_assert (next_index-1 >= delta_info->count[next_table].prev_gen_rows); + i++; /* skip the next record */ + continue; + } +#endif +#ifdef ALLOW_FIELD_ADD + if ( +#ifndef ALLOW_CLASS_ADD + !new_class && +#endif + func_code == ENC_FUNC_ADD_FIELD) { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x AddField to klass 0x%08x, skipping next EnClog record", i, log_token, token_index); + g_assert (i + 1 < rows); + guint32 next_cols [MONO_ENCLOG_SIZE]; + mono_metadata_decode_row (table_enclog, i + 1, next_cols, MONO_ENCLOG_SIZE); + g_assert (next_cols [MONO_ENCLOG_FUNC_CODE] == ENC_FUNC_DEFAULT); + int next_token = next_cols [MONO_ENCLOG_TOKEN]; + int next_table = mono_metadata_token_table (next_token); + int next_index = mono_metadata_token_index (next_token); + g_assert (next_table == MONO_TABLE_FIELD); + /* expecting an added field */ + g_assert (next_index-1 >= delta_info->count[next_table].prev_gen_rows); i++; /* skip the next record */ continue; } @@ -1423,8 +1567,7 @@ apply_enclog_pass1 (MonoImage *image_base, MonoImage *image_dmeta, DeltaInfo *de /* fallthru */ } default: - /* FIXME: this bounds check is wrong for cumulative updates - need to look at the DeltaInfo:count.prev_gen_rows */ - if (token_index <= table_info_get_rows (&image_base->tables [token_table])) { + if (!is_addition) { mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_METADATA_UPDATE, "row[0x%02x]:0x%08x we do not support patching of existing table cols.", i, log_token); mono_error_set_type_load_name (error, NULL, image_base->name, "EnC: we do not support patching of existing table cols. token=0x%08x", log_token); unsupported_edits = TRUE; @@ -1544,9 +1687,12 @@ apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t gen * have it in writable memory (and not mmap-ed pages), so we can rewrite the table values. */ + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Pass 2 begin: base '%s' delta image=%p", image_base->name, image_dmeta); +#if defined(ALLOW_METHOD_ADD) || defined(ALLOW_FIELD_ADD) + MonoClass *add_member_klass = NULL; +#endif #ifdef ALLOW_METHOD_ADD - MonoClass *add_method_klass = NULL; uint32_t add_param_method_index = 0; #endif @@ -1560,7 +1706,11 @@ apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t gen int token_table = mono_metadata_token_table (log_token); int token_index = mono_metadata_token_index (log_token); - mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "enclog i=%d: token=0x%08x (table=%s): %d", i, log_token, mono_meta_table_name (token_table), func_code); + + gboolean is_addition = token_index-1 >= delta_info->count[token_table].prev_gen_rows ; + + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "enclog i=%d: token=0x%08x (table=%s): %d:\t%s", i, log_token, mono_meta_table_name (token_table), func_code, (is_addition ? "ADD" : "UPDATE")); + /* TODO: See CMiniMdRW::ApplyDelta for how to drive this. */ @@ -1570,14 +1720,12 @@ apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t gen #ifdef ALLOW_METHOD_ADD case ENC_FUNC_ADD_METHOD: { g_assert (token_table == MONO_TABLE_TYPEDEF); - /* FIXME: this bounds check is wrong for cumulative updates - need to look at the DeltaInfo:count.prev_gen_rows */ - /* should've been caught by pass1 if we're adding a new method to a new class. */ MonoClass *klass = mono_class_get_checked (image_base, log_token, error); if (!is_ok (error)) { mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Can't get class with token 0x%08x due to: %s", log_token, mono_error_get_message (error)); return FALSE; } - add_method_klass = klass; + add_member_klass = klass; break; } @@ -1586,6 +1734,18 @@ apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t gen add_param_method_index = token_index; break; } +#endif +#ifdef ALLOW_FIELD_ADD + case ENC_FUNC_ADD_FIELD: { + g_assert (token_table == MONO_TABLE_TYPEDEF); + MonoClass *klass = mono_class_get_checked (image_base, log_token, error); + if (!is_ok (error)) { + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Can't get class with token 0x%08x due to: %s", log_token, mono_error_get_message (error)); + return FALSE; + } + add_member_klass = klass; + break; + } #endif default: g_error ("EnC: unsupported FuncCode, should be caught by pass1"); @@ -1637,14 +1797,14 @@ apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t gen if (func_code == ENC_FUNC_ADD_PARAM) break; - if (token_index > table_info_get_rows (&image_base->tables [token_table])) { - if (!add_method_klass) + if (is_addition) { + if (!add_member_klass) g_error ("EnC: new method added but I don't know the class, should be caught by pass1"); - g_assert (add_method_klass); - mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Adding new method 0x%08x to class %s.%s", token_index, m_class_get_name_space (add_method_klass), m_class_get_name (add_method_klass)); + g_assert (add_member_klass); + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Adding new method 0x%08x to class %s.%s", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); MonoDebugInformationEnc *method_debug_information = hot_reload_get_method_debug_information (delta_info->ppdb_file, token_index); - add_method_to_baseline (base_info, delta_info, add_method_klass, token_index, method_debug_information); - add_method_klass = NULL; + add_method_to_baseline (base_info, delta_info, add_member_klass, log_token, method_debug_information); + add_member_klass = NULL; } #endif @@ -1666,17 +1826,78 @@ apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t gen /* rva points probably into image_base IL stream. can this ever happen? */ g_print ("TODO: this case is still a bit contrived. token=0x%08x with rva=0x%04x\n", log_token, rva); } -#ifdef ALLOW_METHOD_ADD - add_method_klass = NULL; +#if defined(ALLOW_METHOD_ADD) || defined(ALLOW_FIELD_ADD) + add_member_klass = NULL; #endif break; } - case MONO_TABLE_TYPEDEF: { - /* TODO: throw? */ - /* TODO: happens changing the class (adding field or method). we ignore it, but dragons are here */ + case MONO_TABLE_FIELD: { +#ifdef ALLOW_FIELD_ADD + g_assert (is_addition); + g_assert (add_member_klass); + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "Adding new field 0x%08x to class %s.%s", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); + + uint32_t mapped_token = hot_reload_relative_delta_index (image_dmeta, delta_info, log_token); + uint32_t field_flags = mono_metadata_decode_row_col (&image_dmeta->tables [MONO_TABLE_FIELD], mapped_token - 1, MONO_FIELD_FLAGS); + + if ((field_flags & FIELD_ATTRIBUTE_STATIC) == 0) { + /* TODO: implement instance (and literal?) fields */ + mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_METADATA_UPDATE, "Adding non-static fields isn't implemented yet (token 0x%08x, class %s.%s)", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); + mono_error_set_not_implemented (error, "Adding non-static fields isn't implemented yet (token 0x%08x, class %s.%s)", log_token, m_class_get_name_space (add_member_klass), m_class_get_name (add_member_klass)); + return FALSE; + } - /* existing entries are supposed to be patched */ - g_assert (token_index <= table_info_get_rows (&image_base->tables [token_table])); + add_field_to_baseline (base_info, delta_info, add_member_klass, log_token); + + /* This actually does more than mono_class_setup_basic_field_info and + * resolves MonoClassField:type and sets MonoClassField:offset to -1 to make + * it easier to spot that the field is special. + */ + metadata_update_field_setup_basic_info_and_resolve (image_base, base_info, generation, delta_info, add_member_klass, log_token, error); + if (!is_ok (error)) { + mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_METADATA_UPDATE, "Could not setup field (token 0x%08x) due to: %s", log_token, mono_error_get_message (error)); + return FALSE; + } + + add_member_klass = NULL; +#else + g_assert_not_reached (); +#endif + break; + } + case MONO_TABLE_TYPEDEF: { +#ifdef ALLOW_CLASS_ADD + if (is_addition) { + /* Adding a new class. ok */ + switch (func_code) { + case ENC_FUNC_DEFAULT: + /* ok, added a new class */ + /* TODO: do things here */ + break; + case ENC_FUNC_ADD_METHOD: + case ENC_FUNC_ADD_FIELD: + /* ok, adding a new field or method to a new class */ + /* TODO: do we need to do anything special? Conceptually + * this is the same as modifying an existing class - + * especially since from the next generation's point of view + * that's what adding a field/method will be. */ + break; + case ENC_FUNC_ADD_PROPERTY: + case ENC_FUNC_ADD_EVENT: + g_assert_not_reached (); /* FIXME: implement me */ + default: + g_assert_not_reached (); /* unknown func_code */ + } + break; + } +#endif + /* modifying an existing class by adding a method or field, etc. */ + g_assert (!is_addition); +#if !defined(ALLOW_METHOD_ADD) && !defined(ALLOW_FIELD_ADD) + g_assert_not_reached (); +#else + g_assert (func_code != ENC_FUNC_DEFAULT); +#endif break; } case MONO_TABLE_PROPERTY: { @@ -1709,7 +1930,7 @@ apply_enclog_pass2 (MonoImage *image_base, BaselineInfo *base_info, uint32_t gen * * So by the time we see the param additions, the methods are already in. * - * FIXME: we need a lookaside table (like method_parent) for every place + * FIXME: we need a lookaside table (like member_parent) for every place * that looks at MONO_METHOD_PARAMLIST */ break; @@ -1909,8 +2130,9 @@ hot_reload_get_updated_method_ppdb (MonoImage *base_image, uint32_t idx) if (G_UNLIKELY (gen > 0)) { loc = get_method_update_rva (base_image, info, idx, TRUE); } - /* Check the method_parent table as a way of checking if the method was added by a later generation. If so, still look for its PPDB info in our update tables */ - if (G_UNLIKELY (loc == 0 && info->method_parent && GPOINTER_TO_UINT (g_hash_table_lookup (info->method_parent, GUINT_TO_POINTER (idx))) > 0)) { + /* Check the member_parent table as a way of checking if the method was added by a later generation. If so, still look for its PPDB info in our update tables */ + uint32_t token = mono_metadata_make_token (MONO_TABLE_METHOD, mono_metadata_token_index (idx)); + if (G_UNLIKELY (loc == 0 && info->member_parent && GPOINTER_TO_UINT (g_hash_table_lookup (info->member_parent, GUINT_TO_POINTER (token))) > 0)) { loc = get_method_update_rva (base_image, info, idx, TRUE); } } @@ -2039,52 +2261,321 @@ hot_reload_table_num_rows_slow (MonoImage *base, int table_index) } static void -add_method_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t method_token, MonoDebugInformationEnc* pdb_address) +add_member_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t member_token) { - if (!base_info->added_methods) { - base_info->added_methods = g_hash_table_new (g_direct_hash, g_direct_equal); - } - if (!base_info->method_parent) { - base_info->method_parent = g_hash_table_new (g_direct_hash, g_direct_equal); - } - /* FIXME: locking for readers/writers of the GArray */ - GArray *arr = g_hash_table_lookup (base_info->added_methods, klass); - if (!arr) { - arr = g_array_new (FALSE, FALSE, sizeof(uint32_t)); - g_hash_table_insert (base_info->added_methods, klass, arr); + /* Check they really passed a table token, not just a table row index */ + g_assert (mono_metadata_token_table (member_token) != 0); + + if (!base_info->member_parent) { + base_info->member_parent = g_hash_table_new (g_direct_hash, g_direct_equal); } - g_array_append_val (arr, method_token); - g_hash_table_insert (base_info->method_parent, GUINT_TO_POINTER (method_token), GUINT_TO_POINTER (m_class_get_type_token (klass))); + MonoClassMetadataUpdateInfo *klass_info = mono_class_get_or_add_metadata_update_info (klass); + GSList *members = klass_info->added_members; + klass_info->added_members = g_slist_prepend_mem_manager (m_class_get_mem_manager (klass), members, GUINT_TO_POINTER (member_token)); + g_hash_table_insert (base_info->member_parent, GUINT_TO_POINTER (member_token), GUINT_TO_POINTER (m_class_get_type_token (klass))); +} + +static void +add_method_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t method_token, MonoDebugInformationEnc* pdb_address) +{ + add_member_to_baseline (base_info, delta_info, klass, method_token); if (pdb_address) set_delta_method_debug_info (delta_info, method_token, pdb_address); } -static GArray* -hot_reload_get_added_methods (MonoClass *klass) +static GSList* +hot_reload_get_added_members (MonoClass *klass) { /* FIXME: locking for the GArray? */ MonoImage *image = m_class_get_image (klass); if (!image->has_updates) return NULL; - BaselineInfo *base_info = baseline_info_lookup (image); - if (!base_info || base_info->added_methods == NULL) + MonoClassMetadataUpdateInfo *klass_info = mono_class_get_metadata_update_info (klass); + if (!klass_info) return NULL; - - return g_hash_table_lookup (base_info->added_methods, klass); + return klass_info->added_members; } static uint32_t -hot_reload_method_parent (MonoImage *base_image, uint32_t method_token) +hot_reload_member_parent (MonoImage *base_image, uint32_t member_token) { + /* make sure they passed a token, not just a table row index */ + g_assert (mono_metadata_token_table (member_token) != 0); + if (!base_image->has_updates) return 0; BaselineInfo *base_info = baseline_info_lookup (base_image); - if (!base_info || base_info->method_parent == NULL) + if (!base_info || base_info->member_parent == NULL) return 0; - uint32_t res = GPOINTER_TO_UINT (g_hash_table_lookup (base_info->method_parent, GUINT_TO_POINTER (method_token))); - mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "method_parent lookup: 0x%08x returned 0x%08x\n", method_token, res); + uint32_t res = GPOINTER_TO_UINT (g_hash_table_lookup (base_info->member_parent, GUINT_TO_POINTER (member_token))); + mono_trace (G_LOG_LEVEL_DEBUG, MONO_TRACE_METADATA_UPDATE, "member_parent lookup: 0x%08x returned 0x%08x\n", member_token, res); + + return res; +} + +static uint32_t +hot_reload_method_parent (MonoImage *base_image, uint32_t method_token) +{ + /* the callers might pass just an index without a table */ + uint32_t lookup_token = mono_metadata_make_token (MONO_TABLE_METHOD, mono_metadata_token_index (method_token)); + + return hot_reload_member_parent (base_image, lookup_token); +} + +static void +add_field_to_baseline (BaselineInfo *base_info, DeltaInfo *delta_info, MonoClass *klass, uint32_t field_token) +{ + add_member_to_baseline (base_info, delta_info, klass, field_token); +} + +static uint32_t +hot_reload_field_parent (MonoImage *base_image, uint32_t field_token) +{ + /* the callers might pass just an index without a table */ + uint32_t lookup_token = mono_metadata_make_token (MONO_TABLE_FIELD, mono_metadata_token_index (field_token)); + + return hot_reload_member_parent (base_image, lookup_token); +} + + +/* HACK - keep in sync with locator_t in metadata/metadata.c */ +typedef struct { + int idx; /* The index that we are trying to locate */ + int col_idx; /* The index in the row where idx may be stored */ + MonoTableInfo *t; /* pointer to the table */ + guint32 result; +} upd_locator_t; + +void* +hot_reload_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer) +{ + BaselineInfo *base_info = baseline_info_lookup (base_image); + g_assert (base_info); + + g_assert (base_image->tables < base_table && base_table < &base_image->tables [MONO_TABLE_LAST]); + + int tbl_index; + { + size_t s = ALIGN_TO (sizeof (MonoTableInfo), sizeof (gpointer)); + tbl_index = ((intptr_t) base_table - (intptr_t) base_image->tables) / s; + } + + DeltaInfo *delta_info = NULL; + const MonoTableInfo *latest_mod_table = base_table; + gboolean success = effective_table_mutant (base_image, base_info, tbl_index, &latest_mod_table, &delta_info); + g_assert (success); + uint32_t rows = table_info_get_rows (latest_mod_table); + + upd_locator_t *loc = (upd_locator_t*)key; + g_assert (loc); + loc->result = 0; + /* HACK: this is so that the locator can compute the row index of the given row. but passing the mutant table to other metadata functions could backfire. */ + loc->t = (MonoTableInfo*)latest_mod_table; + for (uint32_t idx = 0; idx < rows; ++idx) { + const char *row = latest_mod_table->base + idx * latest_mod_table->row_size; + if (!comparer (loc, row)) + return (void*)row; + } + return NULL; +} + +static uint32_t +hot_reload_get_field_idx (MonoClassField *field) +{ + g_assert (m_field_is_from_update (field)); + MonoClassMetadataUpdateField *field_info = (MonoClassMetadataUpdateField*)field; + return mono_metadata_token_index (field_info->token); +} + +static MonoClassField * +hot_reload_get_field (MonoClass *klass, uint32_t fielddef_token) { + MonoClassMetadataUpdateInfo *info = mono_class_get_or_add_metadata_update_info (klass); + g_assert (mono_metadata_token_table (fielddef_token) == MONO_TABLE_FIELD); + /* FIXME: this needs locking in the multi-threaded case. There could be an update happening that resizes the array. */ + GPtrArray *added_fields = info->added_fields; + uint32_t count = added_fields->len; + for (uint32_t i = 0; i < count; ++i) { + MonoClassMetadataUpdateField *field = (MonoClassMetadataUpdateField *)g_ptr_array_index (added_fields, i); + if (field->token == fielddef_token) + return &field->field; + } + return NULL; +} + + +static MonoClassMetadataUpdateField * +metadata_update_field_setup_basic_info_and_resolve (MonoImage *image_base, BaselineInfo *base_info, uint32_t generation, DeltaInfo *delta_info, MonoClass *parent_klass, uint32_t fielddef_token, MonoError *error) +{ + // TODO: hang a "pending field" struct off the parent_klass if !parent_klass->fields + // In that case we can do things simpler, maybe by just creating the MonoClassField array as usual, and just relying on the normal layout algorithm to make space for the instance. + + MonoClassMetadataUpdateInfo *parent_info = mono_class_get_or_add_metadata_update_info (parent_klass); + + MonoClassMetadataUpdateField *field = mono_class_alloc0 (parent_klass, sizeof (MonoClassMetadataUpdateField)); + + m_field_set_parent (&field->field, parent_klass); + m_field_set_meta_flags (&field->field, MONO_CLASS_FIELD_META_FLAG_FROM_UPDATE); + /* It's a special field */ + field->field.offset = -1; + field->generation = generation; + field->token = fielddef_token; + + uint32_t name_idx = mono_metadata_decode_table_row_col (image_base, MONO_TABLE_FIELD, mono_metadata_token_index (fielddef_token) - 1, MONO_FIELD_NAME); + field->field.name = mono_metadata_string_heap (image_base, name_idx); + + mono_field_resolve_type (&field->field, error); + if (!is_ok (error)) + return NULL; + + if (!parent_info->added_fields) { + parent_info->added_fields = g_ptr_array_new (); + } + + g_ptr_array_add (parent_info->added_fields, field); + + return field; +} + +static void +ensure_class_runtime_info_inited (MonoClass *klass, MonoClassRuntimeMetadataUpdateInfo *runtime_info) +{ + if (runtime_info->inited) + return; + mono_loader_lock (); + if (runtime_info->inited) { + mono_loader_unlock (); + return; + } + + mono_coop_mutex_init (&runtime_info->static_fields_lock); + + /* FIXME: is it ok to re-use MONO_ROOT_SOURCE_STATIC here? */ + runtime_info->static_fields = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_STATIC, NULL, "Hot Reload Static Fields"); + + runtime_info->inited = TRUE; + + mono_loader_unlock (); +} + +static void +class_runtime_info_static_fields_lock (MonoClassRuntimeMetadataUpdateInfo *runtime_info) +{ + mono_coop_mutex_lock (&runtime_info->static_fields_lock); +} + +static void +class_runtime_info_static_fields_unlock (MonoClassRuntimeMetadataUpdateInfo *runtime_info) +{ + mono_coop_mutex_unlock (&runtime_info->static_fields_lock); +} + +static GENERATE_GET_CLASS_WITH_CACHE_DECL (hot_reload_field_store); + +static GENERATE_GET_CLASS_WITH_CACHE(hot_reload_field_store, "Mono.HotReload", "FieldStore"); + + +static MonoObject* +create_static_field_storage (MonoType *t, MonoError *error) +{ + MonoClass *klass; + if (!mono_type_is_reference (t)) + klass = mono_class_from_mono_type_internal (t); + else + klass = mono_class_get_hot_reload_field_store_class (); + + return mono_object_new_pinned (klass, error); +} + +static gpointer +hot_reload_get_static_field_addr (MonoClassField *field) +{ + g_assert (m_field_is_from_update (field)); + MonoClassMetadataUpdateField *f = (MonoClassMetadataUpdateField *)field; + g_assert ((f->field.type->attrs & FIELD_ATTRIBUTE_STATIC) != 0); + g_assert (!m_type_is_byref(f->field.type)); // byref fields only in ref structs, which aren't allowed in EnC updates + + MonoClass *parent = m_field_get_parent (&f->field); + MonoClassMetadataUpdateInfo *parent_info = mono_class_get_or_add_metadata_update_info (parent); + MonoClassRuntimeMetadataUpdateInfo *runtime_info = &parent_info->runtime; + + ensure_class_runtime_info_inited (parent, runtime_info); + + MonoObject *obj = NULL; + class_runtime_info_static_fields_lock (runtime_info); + obj = (MonoObject*) mono_g_hash_table_lookup (runtime_info->static_fields, GUINT_TO_POINTER (f->token)); + class_runtime_info_static_fields_unlock (runtime_info); + if (!obj) { + ERROR_DECL (error); + obj = create_static_field_storage (f->field.type, error); + class_runtime_info_static_fields_lock (runtime_info); + mono_error_assert_ok (error); + MonoObject *obj2 = (MonoObject*) mono_g_hash_table_lookup (runtime_info->static_fields, GUINT_TO_POINTER (f->token)); + if (!obj2) { + // Noone else created it, use ours + mono_g_hash_table_insert_internal (runtime_info->static_fields, GUINT_TO_POINTER (f->token), obj); + } else { + /* beaten by another thread, silently drop our storage object and use theirs */ + obj = obj2; + } + class_runtime_info_static_fields_unlock (runtime_info); + } + g_assert (obj); + + gpointer addr = NULL; + if (!mono_type_is_reference (f->field.type)) { + // object is just the boxed value + addr = mono_object_unbox_internal (obj); + } else { + // object is a Mono.HotReload.FieldStore, and the static field value is obj._loc + MonoHotReloadFieldStoreObject *store = (MonoHotReloadFieldStoreObject *)obj; + addr = (gpointer)&store->_loc; + } + g_assert (addr); + + return addr; +} + +static MonoMethod * +hot_reload_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error) +{ + GSList *members = hot_reload_get_added_members (klass); + if (!members) + return NULL; + + MonoImage *image = m_class_get_image (klass); + MonoMethod *res = NULL; + for (GSList *ptr = members; ptr; ptr = ptr->next) { + uint32_t token = GPOINTER_TO_UINT(ptr->data); + if (mono_metadata_token_table (token) != MONO_TABLE_METHOD) + continue; + uint32_t idx = mono_metadata_token_index (token); + uint32_t cols [MONO_METHOD_SIZE]; + mono_metadata_decode_table_row (image, MONO_TABLE_METHOD, idx - 1, cols, MONO_METHOD_SIZE); + + if (!strcmp (mono_metadata_string_heap (image, cols [MONO_METHOD_NAME]), name)) { + ERROR_DECL (local_error); + MonoMethod *method = mono_get_method_checked (image, MONO_TOKEN_METHOD_DEF | idx, klass, NULL, local_error); + if (!method) { + mono_error_cleanup (local_error); + continue; + } + if (param_count == -1) { + res = method; + break; + } + MonoMethodSignature *sig = mono_method_signature_checked (method, local_error); + if (!sig) { + mono_error_cleanup (error); + continue; + } + if ((method->flags & flags) == flags && sig->param_count == param_count) { + res = method; + break; + } + } + } return res; } diff --git a/src/mono/mono/component/hot_reload.h b/src/mono/mono/component/hot_reload.h index 416ff56e70eab..790234e557718 100644 --- a/src/mono/mono/component/hot_reload.h +++ b/src/mono/mono/component/hot_reload.h @@ -8,7 +8,9 @@ #include #include "mono/metadata/object-forward.h" #include "mono/metadata/metadata-internals.h" +#include "mono/metadata/class-internals.h" #include "mono/metadata/metadata-update.h" +#include "mono/utils/bsearch.h" #include "mono/utils/mono-error.h" #include "mono/utils/mono-compiler.h" #include "mono/component/component.h" @@ -31,8 +33,13 @@ typedef struct _MonoComponentHotReload { gpointer (*get_updated_method_ppdb) (MonoImage *base_image, uint32_t idx); gboolean (*has_modified_rows) (const MonoTableInfo *table); gboolean (*table_num_rows_slow) (MonoImage *base_image, int table_index); - GArray* (*get_added_methods) (MonoClass *klass); uint32_t (*method_parent) (MonoImage *base_image, uint32_t method_index); + void* (*metadata_linear_search) (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer); + uint32_t (*field_parent) (MonoImage *base_image, uint32_t method_index); + uint32_t (*get_field_idx) (MonoClassField *field); + MonoClassField* (*get_field) (MonoClass *klass, uint32_t fielddef_token); + gpointer (*get_static_field_addr) (MonoClassField *field); + MonoMethod* (*find_method_by_name) (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error); } MonoComponentHotReload; MONO_COMPONENT_EXPORT_ENTRYPOINT diff --git a/src/mono/mono/component/mini-wasm-debugger.c b/src/mono/mono/component/mini-wasm-debugger.c index 0cfcd5cce9588..81a2011e1ef54 100644 --- a/src/mono/mono/component/mini-wasm-debugger.c +++ b/src/mono/mono/component/mini-wasm-debugger.c @@ -141,7 +141,7 @@ mono_wasm_enable_debugging_internal (int debug_level) } static void -mono_wasm_debugger_init (MonoDefaults *mono_defaults) +mono_wasm_debugger_init (void) { int debug_level = mono_wasm_get_debug_level(); mono_wasm_enable_debugging_internal (debug_level); @@ -149,8 +149,6 @@ mono_wasm_debugger_init (MonoDefaults *mono_defaults) if (!debugger_enabled) return; - mdbg_mono_defaults = mono_defaults; - DebuggerEngineCallbacks cbs = { .tls_get_restore_state = tls_get_restore_state, .try_process_suspend = try_process_suspend, @@ -433,7 +431,7 @@ mono_wasm_breakpoint_hit (void) } static void -mono_wasm_debugger_init (MonoDefaults *mono_defaults) +mono_wasm_debugger_init (void) { } diff --git a/src/mono/mono/metadata/class-accessors.c b/src/mono/mono/metadata/class-accessors.c index 76065cb45c456..a9d950d9e0fa0 100644 --- a/src/mono/mono/metadata/class-accessors.c +++ b/src/mono/mono/metadata/class-accessors.c @@ -28,7 +28,8 @@ typedef enum { PROP_DIM_CONFLICTS = 10, /* GSList of MonoMethod* */ PROP_FIELD_DEF_VALUES_2BYTESWIZZLE = 11, /* MonoFieldDefaultValue* with default values swizzled at 2 byte boundaries*/ PROP_FIELD_DEF_VALUES_4BYTESWIZZLE = 12, /* MonoFieldDefaultValue* with default values swizzled at 4 byte boundaries*/ - PROP_FIELD_DEF_VALUES_8BYTESWIZZLE = 13 /* MonoFieldDefaultValue* with default values swizzled at 8 byte boundaries*/ + PROP_FIELD_DEF_VALUES_8BYTESWIZZLE = 13, /* MonoFieldDefaultValue* with default values swizzled at 8 byte boundaries*/ + PROP_METADATA_UPDATE_INFO = 14, /* MonoClassMetadataUpdateInfo* */ } InfrequentDataKind; /* Accessors based on class kind*/ @@ -67,7 +68,9 @@ mono_class_try_get_generic_class (MonoClass *klass) guint32 mono_class_get_flags (MonoClass *klass) { - switch (m_class_get_class_kind (klass)) { + g_assert (klass); + guint32 kind = m_class_get_class_kind (klass); + switch (kind) { case MONO_CLASS_DEF: case MONO_CLASS_GTD: return m_classdef_get_flags ((MonoClassDef*)klass); @@ -589,6 +592,67 @@ mono_class_publish_gc_descriptor (MonoClass *klass, MonoGCDescriptor gc_descr) return ret; } +MonoClassMetadataUpdateInfo* +mono_class_get_metadata_update_info (MonoClass *klass) +{ + switch (m_class_get_class_kind (klass)) { + case MONO_CLASS_GTD: + return NULL; + case MONO_CLASS_DEF: + return (MonoClassMetadataUpdateInfo *)get_pointer_property (klass, PROP_METADATA_UPDATE_INFO); + case MONO_CLASS_GINST: + case MONO_CLASS_GPARAM: + case MONO_CLASS_POINTER: + case MONO_CLASS_GC_FILLER: + return NULL; + default: + g_assert_not_reached (); + } +} + +/* + * LOCKING: assumes the loader lock is held + */ +void +mono_class_set_metadata_update_info (MonoClass *klass, MonoClassMetadataUpdateInfo *value) +{ + switch (m_class_get_class_kind (klass)) { + case MONO_CLASS_GTD: + g_assertf (0, "%s: EnC metadata update info on generic types is not supported", __func__); + break; + case MONO_CLASS_DEF: + set_pointer_property (klass, PROP_METADATA_UPDATE_INFO, value); + return; + case MONO_CLASS_GINST: + case MONO_CLASS_GPARAM: + case MONO_CLASS_POINTER: + case MONO_CLASS_GC_FILLER: + g_assert_not_reached (); + break; + default: + g_assert_not_reached (); + } +} + +gboolean +mono_class_has_metadata_update_info (MonoClass *klass) +{ + switch (m_class_get_class_kind (klass)) { + case MONO_CLASS_GTD: + return FALSE; + case MONO_CLASS_DEF: + return get_pointer_property (klass, PROP_METADATA_UPDATE_INFO) != NULL; + case MONO_CLASS_GINST: + case MONO_CLASS_GPARAM: + case MONO_CLASS_POINTER: + case MONO_CLASS_GC_FILLER: + return FALSE; + default: + g_assert_not_reached (); + } +} + + #ifdef MONO_CLASS_DEF_PRIVATE #define MONO_CLASS_GETTER(funcname, rettype, optref, argtype, fieldname) rettype funcname (argtype *klass) { return optref klass-> fieldname ; } #define MONO_CLASS_OFFSET(funcname, argtype, fieldname) intptr_t funcname (void) { return MONO_STRUCT_OFFSET (argtype, fieldname); } diff --git a/src/mono/mono/metadata/class-init.c b/src/mono/mono/metadata/class-init.c index 6164476ba9a91..750dcff22d70b 100644 --- a/src/mono/mono/metadata/class-init.c +++ b/src/mono/mono/metadata/class-init.c @@ -434,7 +434,7 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError error_init (error); /* FIXME: metadata-update - this function needs extensive work */ - if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || tidx > table_info_get_rows (tt)) { + if (mono_metadata_token_table (type_token) != MONO_TABLE_TYPEDEF || mono_metadata_table_bounds_check (image, MONO_TABLE_TYPEDEF, tidx)) { mono_error_set_bad_image (error, image, "Invalid typedef token %x", type_token); return NULL; } @@ -614,27 +614,33 @@ mono_class_create_from_typedef (MonoImage *image, guint32 type_token, MonoError /* * Compute the field and method lists */ - int first_field_idx; - first_field_idx = cols [MONO_TYPEDEF_FIELD_LIST] - 1; - mono_class_set_first_field_idx (klass, first_field_idx); - int first_method_idx; - first_method_idx = cols [MONO_TYPEDEF_METHOD_LIST] - 1; - mono_class_set_first_method_idx (klass, first_method_idx); - - if (table_info_get_rows (tt) > tidx){ - mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE); - field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1; - method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1; - } else { - field_last = table_info_get_rows (&image->tables [MONO_TABLE_FIELD]); - method_last = table_info_get_rows (&image->tables [MONO_TABLE_METHOD]); - } + /* + * EnC metadata-update: new classes are added with method and field indices set to 0, new + * methods are added using the EnCLog AddMethod or AddField functions that will be added to + * MonoClassMetadataUpdateInfo + */ + if (G_LIKELY (cols [MONO_TYPEDEF_FIELD_LIST] != 0 || cols [MONO_TYPEDEF_METHOD_LIST] != 0)) { + int first_field_idx; + first_field_idx = cols [MONO_TYPEDEF_FIELD_LIST] - 1; + mono_class_set_first_field_idx (klass, first_field_idx); + int first_method_idx; + first_method_idx = cols [MONO_TYPEDEF_METHOD_LIST] - 1; + mono_class_set_first_method_idx (klass, first_method_idx); + if (table_info_get_rows (tt) > tidx) { + mono_metadata_decode_row (tt, tidx, cols_next, MONO_TYPEDEF_SIZE); + field_last = cols_next [MONO_TYPEDEF_FIELD_LIST] - 1; + method_last = cols_next [MONO_TYPEDEF_METHOD_LIST] - 1; + } else { + field_last = table_info_get_rows (&image->tables [MONO_TABLE_FIELD]); + method_last = table_info_get_rows (&image->tables [MONO_TABLE_METHOD]); + } - if (cols [MONO_TYPEDEF_FIELD_LIST] && - cols [MONO_TYPEDEF_FIELD_LIST] <= table_info_get_rows (&image->tables [MONO_TABLE_FIELD])) - mono_class_set_field_count (klass, field_last - first_field_idx); - if (cols [MONO_TYPEDEF_METHOD_LIST] <= table_info_get_rows (&image->tables [MONO_TABLE_METHOD])) - mono_class_set_method_count (klass, method_last - first_method_idx); + if (cols [MONO_TYPEDEF_FIELD_LIST] && + cols [MONO_TYPEDEF_FIELD_LIST] <= table_info_get_rows (&image->tables [MONO_TABLE_FIELD])) + mono_class_set_field_count (klass, field_last - first_field_idx); + if (cols [MONO_TYPEDEF_METHOD_LIST] <= table_info_get_rows (&image->tables [MONO_TABLE_METHOD])) + mono_class_set_method_count (klass, method_last - first_method_idx); + } /* reserve space to store vector pointer in arrays */ if (mono_is_corlib_image (image) && !strcmp (nspace, "System") && !strcmp (name, "Array")) { @@ -4080,16 +4086,3 @@ mono_classes_init (void) mono_counters_register ("MonoClass size", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &classes_size); } - -void -m_field_set_parent (MonoClassField *field, MonoClass *klass) -{ - uintptr_t old_flags = m_field_get_meta_flags (field); - field->parent_and_flags = ((uintptr_t)klass) | old_flags; -} - -void -m_field_set_meta_flags (MonoClassField *field, unsigned int flags) -{ - field->parent_and_flags |= (field->parent_and_flags & ~MONO_CLASS_FIELD_META_FLAG_MASK) | flags; -} diff --git a/src/mono/mono/metadata/class-inlines.h b/src/mono/mono/metadata/class-inlines.h index a9aa3c992a541..e45350a8bc4aa 100644 --- a/src/mono/mono/metadata/class-inlines.h +++ b/src/mono/mono/metadata/class-inlines.h @@ -253,4 +253,18 @@ m_method_is_wrapper (MonoMethod *method) return method->wrapper_type != 0; } + +static inline void +m_field_set_parent (MonoClassField *field, MonoClass *klass) +{ + uintptr_t old_flags = m_field_get_meta_flags (field); + field->parent_and_flags = ((uintptr_t)klass) | old_flags; +} + +static inline void +m_field_set_meta_flags (MonoClassField *field, unsigned int flags) +{ + field->parent_and_flags |= (field->parent_and_flags & ~MONO_CLASS_FIELD_META_FLAG_MASK) | flags; +} + #endif diff --git a/src/mono/mono/metadata/class-internals.h b/src/mono/mono/metadata/class-internals.h index e553e64849ccc..4a7992875bf68 100644 --- a/src/mono/mono/metadata/class-internals.h +++ b/src/mono/mono/metadata/class-internals.h @@ -984,12 +984,29 @@ typedef struct { MonoClass *appcontext_class; } MonoDefaults; +/* If you need a MonoType, use one of the mono_get_*_type () functions in class-inlines.h */ +extern MonoDefaults mono_defaults; + +MONO_COMPONENT_API +MonoDefaults * +mono_get_defaults (void); + #define GENERATE_GET_CLASS_WITH_CACHE_DECL(shortname) \ MonoClass* mono_class_get_##shortname##_class (void); #define GENERATE_TRY_GET_CLASS_WITH_CACHE_DECL(shortname) \ MonoClass* mono_class_try_get_##shortname##_class (void); +static inline MonoImage * +mono_class_generate_get_corlib_impl (void) +{ +#ifdef COMPILING_COMPONENT_DYNAMIC + return mono_get_corlib (); +#else + return mono_defaults.corlib; +#endif +} + // GENERATE_GET_CLASS_WITH_CACHE attempts mono_class_load_from_name whenever // its cache is null. i.e. potentially repeatedly, though it is expected to succeed // the first time. @@ -1001,7 +1018,7 @@ mono_class_get_##shortname##_class (void) \ static MonoClass *tmp_class; \ MonoClass *klass = tmp_class; \ if (!klass) { \ - klass = mono_class_load_from_name (mono_defaults.corlib, name_space, name); \ + klass = mono_class_load_from_name (mono_class_generate_get_corlib_impl (), name_space, name); \ mono_memory_barrier (); /* FIXME excessive? */ \ tmp_class = klass; \ } \ @@ -1023,7 +1040,7 @@ mono_class_try_get_##shortname##_class (void) \ MonoClass *klass = (MonoClass *)tmp_class; \ mono_memory_barrier (); \ if (!inited) { \ - klass = mono_class_try_load_from_name (mono_defaults.corlib, name_space, name); \ + klass = mono_class_try_load_from_name (mono_class_generate_get_corlib_impl (), name_space, name); \ tmp_class = klass; \ mono_memory_barrier (); \ inited = TRUE; \ @@ -1055,9 +1072,6 @@ GENERATE_TRY_GET_CLASS_WITH_CACHE_DECL(handleref) GENERATE_GET_CLASS_WITH_CACHE_DECL (assembly_load_context) GENERATE_GET_CLASS_WITH_CACHE_DECL (native_library) -/* If you need a MonoType, use one of the mono_get_*_type () functions in class-inlines.h */ -extern MonoDefaults mono_defaults; - void mono_loader_init (void); @@ -1217,7 +1231,7 @@ mono_class_get_generic_container (MonoClass *klass); gpointer mono_class_alloc (MonoClass *klass, int size); -gpointer +MONO_COMPONENT_API gpointer mono_class_alloc0 (MonoClass *klass, int size); #define mono_class_alloc0(klass, size) (g_cast (mono_class_alloc0 ((klass), (size)))) @@ -1441,6 +1455,18 @@ mono_class_set_dim_conflicts (MonoClass *klass, GSList *conflicts); GSList* mono_class_get_dim_conflicts (MonoClass *klass); +/* opaque struct of class specific hot reload info */ +typedef struct _MonoClassMetadataUpdateInfo MonoClassMetadataUpdateInfo; + +MONO_COMPONENT_API gboolean +mono_class_has_metadata_update_info (MonoClass *klass); + +MONO_COMPONENT_API MonoClassMetadataUpdateInfo * +mono_class_get_metadata_update_info (MonoClass *klass); + +MONO_COMPONENT_API void +mono_class_set_metadata_update_info (MonoClass *klass, MonoClassMetadataUpdateInfo *value); + MONO_COMPONENT_API MonoMethod * mono_class_get_method_from_name_checked (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error); @@ -1478,7 +1504,7 @@ mono_class_get_default_finalize_method (void); const char * mono_field_get_rva (MonoClassField *field, int swizzle); -void +MONO_COMPONENT_API void mono_field_resolve_type (MonoClassField *field, MonoError *error); gboolean @@ -1561,12 +1587,6 @@ m_field_get_meta_flags (MonoClassField *field) return (unsigned int)(field->parent_and_flags & MONO_CLASS_FIELD_META_FLAG_MASK); } -void -m_field_set_parent (MonoClassField *field, MonoClass *klass); - -void -m_field_set_meta_flags (MonoClassField *field, unsigned int flags); - static inline gboolean m_field_get_offset (MonoClassField *field) { diff --git a/src/mono/mono/metadata/class.c b/src/mono/mono/metadata/class.c index 04af2642f252d..895a654cbfeaa 100644 --- a/src/mono/mono/metadata/class.c +++ b/src/mono/mono/metadata/class.c @@ -39,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -2401,6 +2402,10 @@ mono_class_get_field_idx (MonoClass *klass, int idx) return &klass_fields [idx - first_field_idx]; } } + if (G_UNLIKELY (m_class_get_image (klass)->has_updates && mono_class_has_metadata_update_info (klass))) { + uint32_t token = mono_metadata_make_token (MONO_TABLE_FIELD, idx + 1); + return mono_metadata_update_get_field (klass, token); + } } klass = m_class_get_parent (klass); } @@ -5715,6 +5720,14 @@ mono_find_method_in_metadata (MonoClass *klass, const char *name, int param_coun } } + if (G_UNLIKELY (!res && klass_image->has_updates)) { + if (mono_class_has_metadata_update_info (klass)) { + ERROR_DECL (error); + res = mono_metadata_update_find_method_by_name (klass, name, param_count, flags, error); + mono_error_cleanup (error); + } + } + return res; } @@ -5777,7 +5790,8 @@ mono_class_get_method_from_name_checked (MonoClass *klass, const char *name, FIXME we should better report this error to the caller */ MonoMethod **klass_methods = m_class_get_methods (klass); - if (!klass_methods) + gboolean has_updates = m_class_get_image (klass)->has_updates; + if (!klass_methods && !has_updates) return NULL; int mcount = mono_class_get_method_count (klass); for (i = 0; i < mcount; ++i) { @@ -5791,6 +5805,9 @@ mono_class_get_method_from_name_checked (MonoClass *klass, const char *name, break; } } + if (G_UNLIKELY (!res && has_updates && mono_class_has_metadata_update_info (klass))) { + res = mono_metadata_update_find_method_by_name (klass, name, param_count, flags, error); + } } else { res = mono_find_method_in_metadata (klass, name, param_count, flags); @@ -6417,11 +6434,18 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error) MonoImage *image = m_class_get_image (klass); MonoClass *gtd = mono_class_is_ginst (klass) ? mono_class_get_generic_type_definition (klass) : NULL; MonoType *ftype; - int field_idx = field - m_class_get_fields (klass); + int field_idx; + + if (G_UNLIKELY (m_field_is_from_update (field))) { + field_idx = -1; + } else { + field_idx = field - m_class_get_fields (klass); + } error_init (error); if (gtd) { + g_assert (field_idx != -1); MonoClassField *gfield = &m_class_get_fields (gtd) [field_idx]; MonoType *gtype = mono_field_get_type_checked (gfield, error); if (!is_ok (error)) { @@ -6440,7 +6464,13 @@ mono_field_resolve_type (MonoClassField *field, MonoError *error) const char *sig; guint32 cols [MONO_FIELD_SIZE]; MonoGenericContainer *container = NULL; - int idx = mono_class_get_first_field_idx (klass) + field_idx; + int idx; + + if (G_UNLIKELY (m_field_is_from_update (field))) { + idx = mono_metadata_update_get_field_idx (field) - 1; + } else { + idx = mono_class_get_first_field_idx (klass) + field_idx; + } /*FIXME, in theory we do not lazy load SRE fields*/ g_assert (!image_is_dynamic (image)); diff --git a/src/mono/mono/metadata/custom-attrs.c b/src/mono/mono/metadata/custom-attrs.c index 580a51b497d37..59a3ce25983e1 100644 --- a/src/mono/mono/metadata/custom-attrs.c +++ b/src/mono/mono/metadata/custom-attrs.c @@ -25,6 +25,7 @@ #include "mono/metadata/tabledefs.h" #include "mono/metadata/tokentype.h" #include "mono/metadata/icall-decl.h" +#include "mono/metadata/metadata-update.h" #include "mono/utils/checked-build.h" #define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a)) @@ -150,6 +151,8 @@ free_param_data (MonoMethodSignature *sig, void **params) { */ static guint32 find_field_index (MonoClass *klass, MonoClassField *field) { + if (G_UNLIKELY (m_field_is_from_update (field))) + return mono_metadata_update_get_field_idx (field); int fcount = mono_class_get_field_count (klass); MonoClassField *klass_fields = m_class_get_fields (klass); int index = field - klass_fields; @@ -1626,8 +1629,6 @@ mono_custom_attrs_from_index_checked (MonoImage *image, guint32 idx, gboolean ig error_init (error); ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE]; - /* FIXME: metadata-update */ - int rows = table_info_get_rows (ca); i = mono_metadata_custom_attrs_from_index (image, idx); if (!i) @@ -1635,9 +1636,17 @@ mono_custom_attrs_from_index_checked (MonoImage *image, guint32 idx, gboolean ig i --; // initial size chosen arbitrarily, but default is 16 which is rather small attr_array = g_array_sized_new (TRUE, TRUE, sizeof (guint32), 128); - while (i < rows) { - if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx) - break; + while (!mono_metadata_table_bounds_check (image, MONO_TABLE_CUSTOMATTRIBUTE, i + 1)) { + if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx) { + if (G_LIKELY (!image->has_updates)) { + break; + } else { + // if there are updates, the new custom attributes are not sorted, + // so we have to go until the end. + ++i; + continue; + } + } attr_array = g_array_append_val (attr_array, i); ++i; } diff --git a/src/mono/mono/metadata/icall-decl.h b/src/mono/mono/metadata/icall-decl.h index d99cf1cee6c32..5b75710e6456a 100644 --- a/src/mono/mono/metadata/icall-decl.h +++ b/src/mono/mono/metadata/icall-decl.h @@ -68,7 +68,6 @@ ICALL_EXPORT void ves_icall_System_ArgIterator_Setup (MonoArgIterator*, char*, c ICALL_EXPORT MonoType* ves_icall_System_ArgIterator_IntGetNextArgType (MonoArgIterator*); ICALL_EXPORT void ves_icall_System_ArgIterator_IntGetNextArg (MonoArgIterator*, MonoTypedRef*); ICALL_EXPORT void ves_icall_System_ArgIterator_IntGetNextArgWithType (MonoArgIterator*, MonoTypedRef*, MonoType*); -ICALL_EXPORT double ves_icall_System_Math_Abs_double (double); ICALL_EXPORT double ves_icall_System_Math_Acos (double); ICALL_EXPORT double ves_icall_System_Math_Acosh (double); ICALL_EXPORT double ves_icall_System_Math_Asin (double); @@ -116,7 +115,6 @@ ICALL_EXPORT float ves_icall_System_MathF_Sinh (float); ICALL_EXPORT float ves_icall_System_MathF_Sqrt (float); ICALL_EXPORT float ves_icall_System_MathF_Tan (float); ICALL_EXPORT float ves_icall_System_MathF_Tanh (float); -ICALL_EXPORT float ves_icall_System_Math_Abs_single (float); ICALL_EXPORT double ves_icall_System_Math_Log2 (double); ICALL_EXPORT double ves_icall_System_Math_FusedMultiplyAdd (double, double, double); ICALL_EXPORT float ves_icall_System_MathF_Log2 (float); diff --git a/src/mono/mono/metadata/icall-def-netcore.h b/src/mono/mono/metadata/icall-def-netcore.h index f16c61677deda..45c65207a0849 100644 --- a/src/mono/mono/metadata/icall-def-netcore.h +++ b/src/mono/mono/metadata/icall-def-netcore.h @@ -108,9 +108,7 @@ ICALL_TYPE(STREAM, "System.IO.Stream", STREAM_1) HANDLES(STREAM_1, "HasOverriddenBeginEndRead", ves_icall_System_IO_Stream_HasOverriddenBeginEndRead, MonoBoolean, 1, (MonoObject)) HANDLES(STREAM_2, "HasOverriddenBeginEndWrite", ves_icall_System_IO_Stream_HasOverriddenBeginEndWrite, MonoBoolean, 1, (MonoObject)) -ICALL_TYPE(MATH, "System.Math", MATH_19) -NOHANDLES(ICALL(MATH_19, "Abs(double)", ves_icall_System_Math_Abs_double)) -NOHANDLES(ICALL(MATH_20, "Abs(single)", ves_icall_System_Math_Abs_single)) +ICALL_TYPE(MATH, "System.Math", MATH_1) NOHANDLES(ICALL(MATH_1, "Acos", ves_icall_System_Math_Acos)) NOHANDLES(ICALL(MATH_1a, "Acosh", ves_icall_System_Math_Acosh)) NOHANDLES(ICALL(MATH_2, "Asin", ves_icall_System_Math_Asin)) @@ -235,20 +233,16 @@ HANDLES(MMETHI_2, "get_parameter_info", ves_icall_System_Reflection_MonoMethodIn HANDLES(MMETHI_3, "get_retval_marshal", ves_icall_System_MonoMethodInfo_get_retval_marshal, MonoReflectionMarshalAsAttribute, 1, (MonoMethod_ptr)) ICALL_TYPE(RASSEM, "System.Reflection.RuntimeAssembly", RASSEM_1) -HANDLES(RASSEM_1, "GetExportedTypes", ves_icall_System_Reflection_RuntimeAssembly_GetExportedTypes, MonoArray, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_1a, "GetFilesInternal", ves_icall_System_Reflection_RuntimeAssembly_GetFilesInternal, MonoObject, 3, (MonoReflectionAssembly, MonoString, MonoBoolean)) -HANDLES(RASSEM_2, "GetManifestModuleInternal", ves_icall_System_Reflection_Assembly_GetManifestModuleInternal, MonoReflectionModule, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_3, "GetManifestResourceInfoInternal", ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInfoInternal, MonoBoolean, 3, (MonoReflectionAssembly, MonoString, MonoManifestResourceInfo)) -HANDLES(RASSEM_4, "GetManifestResourceInternal", ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInternal, gpointer, 4, (MonoReflectionAssembly, MonoString, gint32_ref, MonoReflectionModuleOut)) -HANDLES(RASSEM_5, "GetManifestResourceNames", ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceNames, MonoArray, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_6, "GetModulesInternal", ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal, MonoArray, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_6b, "GetTopLevelForwardedTypes", ves_icall_System_Reflection_RuntimeAssembly_GetTopLevelForwardedTypes, MonoArray, 1, (MonoReflectionAssembly)) +HANDLES(RASSEM_1, "GetEntryPoint", ves_icall_System_Reflection_RuntimeAssembly_GetEntryPoint, void, 2, (MonoQCallAssemblyHandle, MonoObjectHandleOnStack)) +HANDLES(RASSEM_9, "GetExportedTypes", ves_icall_System_Reflection_RuntimeAssembly_GetExportedTypes, void, 2, (MonoQCallAssemblyHandle, MonoObjectHandleOnStack)) +HANDLES(RASSEM_13, "GetInfo", ves_icall_System_Reflection_RuntimeAssembly_GetInfo, void, 3, (MonoQCallAssemblyHandle, MonoObjectHandleOnStack, guint32)) +HANDLES(RASSEM_2, "GetManifestModuleInternal", ves_icall_System_Reflection_Assembly_GetManifestModuleInternal, void, 2, (MonoQCallAssemblyHandle, MonoObjectHandleOnStack)) +HANDLES(RASSEM_3, "GetManifestResourceInfoInternal", ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInfoInternal, MonoBoolean, 3, (MonoQCallAssemblyHandle, MonoString, MonoManifestResourceInfo)) +HANDLES(RASSEM_4, "GetManifestResourceInternal", ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInternal, gpointer, 4, (MonoQCallAssemblyHandle, MonoString, gint32_ref, MonoObjectHandleOnStack)) +HANDLES(RASSEM_5, "GetManifestResourceNames", ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceNames, void, 2, (MonoQCallAssemblyHandle, MonoObjectHandleOnStack)) +HANDLES(RASSEM_6, "GetModulesInternal", ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal, void, 2, (MonoQCallAssemblyHandle, MonoObjectHandleOnStack)) +HANDLES(RASSEM_6b, "GetTopLevelForwardedTypes", ves_icall_System_Reflection_RuntimeAssembly_GetTopLevelForwardedTypes, void, 2, (MonoQCallAssemblyHandle, MonoObjectHandleOnStack)) HANDLES(RASSEM_7, "InternalGetReferencedAssemblies", ves_icall_System_Reflection_Assembly_InternalGetReferencedAssemblies, GPtrArray_ptr, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_8, "InternalImageRuntimeVersion", ves_icall_System_Reflection_RuntimeAssembly_InternalImageRuntimeVersion, MonoString, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_9, "get_EntryPoint", ves_icall_System_Reflection_RuntimeAssembly_get_EntryPoint, MonoReflectionMethod, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_10, "get_code_base", ves_icall_System_Reflection_RuntimeAssembly_get_code_base, MonoString, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_11, "get_fullname", ves_icall_System_Reflection_RuntimeAssembly_get_fullname, MonoString, 1, (MonoReflectionAssembly)) -HANDLES(RASSEM_12, "get_location", ves_icall_System_Reflection_RuntimeAssembly_get_location, MonoString, 1, (MonoReflectionAssembly)) ICALL_TYPE(MCMETH, "System.Reflection.RuntimeConstructorInfo", MCMETH_1) HANDLES(MCMETH_1, "GetGenericMethodDefinition_impl", ves_icall_RuntimeMethodInfo_GetGenericMethodDefinition, MonoReflectionMethod, 1, (MonoReflectionMethod)) diff --git a/src/mono/mono/metadata/icall.c b/src/mono/mono/metadata/icall.c index a4fecbec65193..39806dd249178 100644 --- a/src/mono/mono/metadata/icall.c +++ b/src/mono/mono/metadata/icall.c @@ -333,8 +333,6 @@ array_set_value_impl (MonoArrayHandle arr_handle, MonoObjectHandle value_handle, gboolean et_isenum = FALSE; gboolean vt_isenum = FALSE; - error_init (error); - if (!MONO_HANDLE_IS_NULL (value_handle)) vc = mono_handle_class (value_handle); else @@ -1556,8 +1554,6 @@ type_from_parsed_name (MonoTypeNameParse *info, MonoStackCrawlMark *stack_mark, MonoImage *rootimage = NULL; MonoAssemblyLoadContext *alc = mono_alc_get_ambient (); - error_init (error); - /* * We must compute the calling assembly as type loading must happen under a metadata context. * For example. The main assembly is a.exe and Type.GetType is called from dir/b.dll. Without @@ -2372,7 +2368,6 @@ static gboolean add_event_other_methods_to_array (MonoMethod *m, MonoArrayHandle dest, int i, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); MonoReflectionMethodHandle rm = mono_method_get_object_handle (m, NULL, error); goto_if_nok (error, leave); MONO_HANDLE_ARRAY_SETREF (dest, i, rm); @@ -2584,7 +2579,6 @@ static gboolean set_interface_map_data_method_object (MonoMethod *method, MonoClass *iclass, int ioffset, MonoClass *klass, MonoArrayHandle targets, MonoArrayHandle methods, int i, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); MonoReflectionMethodHandle member = mono_method_get_object_handle (method, iclass, error); goto_if_nok (error, leave); @@ -2801,7 +2795,6 @@ ves_icall_RuntimeTypeHandle_IsComObject (MonoQCallTypeHandle type_handle, MonoEr guint32 ves_icall_reflection_get_token (MonoObjectHandle obj, MonoError *error) { - error_init (error); return mono_reflection_get_token_checked (obj, error); } @@ -2917,7 +2910,6 @@ static gboolean set_type_object_in_array (MonoType *type, MonoArrayHandle dest, int i, MonoError *error) { HANDLE_FUNCTION_ENTER(); - error_init (error); MonoReflectionTypeHandle rt = mono_type_get_object_handle (type, error); goto_if_nok (error, leave); @@ -3002,8 +2994,6 @@ ves_icall_RuntimeTypeHandle_GetGenericTypeDefinition_impl (MonoQCallTypeHandle t void ves_icall_RuntimeType_MakeGenericType (MonoReflectionTypeHandle reftype, MonoArrayHandle type_array, MonoObjectHandleOnStack res, MonoError *error) { - error_init (error); - g_assert (IS_MONOTYPE_HANDLE (reftype)); MonoType *type = MONO_HANDLE_GETVAL (reftype, type); mono_class_init_checked (mono_class_from_mono_type_internal (type), error); @@ -3123,8 +3113,6 @@ ves_icall_RuntimeMethodInfo_GetPInvoke (MonoReflectionMethodHandle ref_method, i const char *import = NULL; const char *scope = NULL; - error_init (error); - if (image_is_dynamic (image)) { MonoReflectionMethodAux *method_aux = (MonoReflectionMethodAux *)g_hash_table_lookup (((MonoDynamicImage*)image)->method_aux_hash, method); @@ -3158,7 +3146,6 @@ ves_icall_RuntimeMethodInfo_GetPInvoke (MonoReflectionMethodHandle ref_method, i MonoReflectionMethodHandle ves_icall_RuntimeMethodInfo_GetGenericMethodDefinition (MonoReflectionMethodHandle ref_method, MonoError *error) { - error_init (error); MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method); if (method->is_generic) @@ -3302,7 +3289,6 @@ static gboolean set_array_generic_argument_handle_inflated (MonoGenericInst *inst, int i, MonoArrayHandle arr, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); MonoReflectionTypeHandle rt = mono_type_get_object_handle (inst->type_argv [i], error); goto_if_nok (error, leave); MONO_HANDLE_ARRAY_SETREF (arr, i, rt); @@ -3314,7 +3300,6 @@ static gboolean set_array_generic_argument_handle_gparam (MonoGenericContainer *container, int i, MonoArrayHandle arr, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); MonoGenericParam *param = mono_generic_container_get_param (container, i); MonoClass *pklass = mono_class_create_generic_parameter (param); MonoReflectionTypeHandle rt = mono_type_get_object_handle (m_class_get_byval_arg (pklass), error); @@ -3327,7 +3312,6 @@ set_array_generic_argument_handle_gparam (MonoGenericContainer *container, int i MonoArrayHandle ves_icall_RuntimeMethodInfo_GetGenericArguments (MonoReflectionMethodHandle ref_method, MonoError *error) { - error_init (error); MonoMethod *method = MONO_HANDLE_GETVAL (ref_method, method); if (method->is_inflated) { @@ -3601,7 +3585,6 @@ ves_icall_System_Enum_InternalGetCorElementType (MonoQCallTypeHandle type_handle static void get_enum_field (MonoArrayHandle names, MonoArrayHandle values, int base_type, MonoClassField *field, guint* j, guint64 *previous_value, gboolean *sorted, MonoError *error) { - error_init (error); HANDLE_FUNCTION_ENTER(); guint64 field_value; const char *p; @@ -3795,7 +3778,6 @@ mono_class_get_methods_by_name (MonoClass *klass, const char *name, guint32 bfla array = g_ptr_array_new (); startklass = klass; - error_init (error); compare_func = ((bflags & BFLAGS_IgnoreCase) || (mlisttype == MLISTTYPE_CaseInsensitive)) ? mono_utf8_strcasecmp : strcmp; @@ -4403,81 +4385,90 @@ ves_icall_System_Reflection_Assembly_InternalGetType (MonoReflectionAssemblyHand return MONO_HANDLE_CAST (MonoReflectionType, NULL_HANDLE); } -MonoStringHandle -ves_icall_System_Reflection_RuntimeAssembly_get_code_base (MonoReflectionAssemblyHandle assembly, MonoError *error) -{ - MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly); - - /* return NULL for bundled assemblies in single-file scenarios */ - const char* filename = m_image_get_filename (mass->image); +/* This corresponds to RuntimeAssembly.AssemblyInfoKind */ +typedef enum { + ASSEMBLY_INFO_KIND_LOCATION = 1, + ASSEMBLY_INFO_KIND_CODEBASE = 2, + ASSEMBLY_INFO_KIND_FULLNAME = 3, + ASSEMBLY_INFO_KIND_VERSION = 4 +} MonoAssemblyInfoKind; - if (!filename) - return NULL_HANDLE_STRING; +void +ves_icall_System_Reflection_RuntimeAssembly_GetInfo (MonoQCallAssemblyHandle assembly_h, MonoObjectHandleOnStack res, guint32 int_kind, MonoError *error) +{ + MonoAssembly *assembly = assembly_h.assembly; + MonoAssemblyInfoKind kind = (MonoAssemblyInfoKind)int_kind; - gchar *absolute; - if (g_path_is_absolute (filename)) { - absolute = g_strdup (filename); - } else { - absolute = g_build_filename (mass->basedir, filename, (const char*)NULL); + switch (kind) { + case ASSEMBLY_INFO_KIND_LOCATION: { + const char *image_name = m_image_get_filename (assembly->image); + HANDLE_ON_STACK_SET (res, mono_string_new_checked (image_name != NULL ? image_name : "", error)); + break; } + case ASSEMBLY_INFO_KIND_CODEBASE: { + /* return NULL for bundled assemblies in single-file scenarios */ + const char* filename = m_image_get_filename (assembly->image); - mono_icall_make_platform_path (absolute); + if (!filename) + break; - const gchar *prepend = mono_icall_get_file_path_prefix (absolute); - gchar *uri = g_strconcat (prepend, absolute, (const char*)NULL); + gchar *absolute; + if (g_path_is_absolute (filename)) + absolute = g_strdup (filename); + else + absolute = g_build_filename (assembly->basedir, filename, (const char*)NULL); - g_free (absolute); + mono_icall_make_platform_path (absolute); - MonoStringHandle res; - if (uri) { - res = mono_string_new_handle (uri, error); - g_free (uri); - } else { - res = MONO_HANDLE_NEW (MonoString, NULL); - } - return res; -} - -MonoStringHandle -ves_icall_System_Reflection_RuntimeAssembly_get_location (MonoReflectionAssemblyHandle refassembly, MonoError *error) -{ - MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly); - const char *image_name = m_image_get_filename (assembly->image); - return mono_string_new_handle (image_name != NULL ? image_name : "", error); -} + const gchar *prepend = mono_icall_get_file_path_prefix (absolute); + gchar *uri = g_strconcat (prepend, absolute, (const char*)NULL); -MonoStringHandle -ves_icall_System_Reflection_RuntimeAssembly_InternalImageRuntimeVersion (MonoReflectionAssemblyHandle refassembly, MonoError *error) -{ - MonoAssembly *assembly = MONO_HANDLE_GETVAL (refassembly, assembly); + g_free (absolute); - return mono_string_new_handle (assembly->image->version, error); + if (uri) { + HANDLE_ON_STACK_SET (res, mono_string_new_checked (uri, error)); + g_free (uri); + return_if_nok (error); + } + break; + } + case ASSEMBLY_INFO_KIND_FULLNAME: { + char *name = mono_stringify_assembly_name (&assembly->aname); + HANDLE_ON_STACK_SET (res, mono_string_new_checked (name, error)); + g_free (name); + return_if_nok (error); + break; + } + case ASSEMBLY_INFO_KIND_VERSION: { + HANDLE_ON_STACK_SET (res, mono_string_new_checked (assembly->image->version, error)); + return_if_nok (error); + break; + } + default: + g_assert_not_reached (); + } } -MonoReflectionMethodHandle -ves_icall_System_Reflection_RuntimeAssembly_get_EntryPoint (MonoReflectionAssemblyHandle assembly_h, MonoError *error) +void +ves_icall_System_Reflection_RuntimeAssembly_GetEntryPoint (MonoQCallAssemblyHandle assembly_h, MonoObjectHandleOnStack res, MonoError *error) { - MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly); + MonoAssembly *assembly = assembly_h.assembly; MonoMethod *method; - MonoReflectionMethodHandle res = MONO_HANDLE_NEW (MonoReflectionMethod, NULL); guint32 token = mono_image_get_entry_point (assembly->image); - if (!token) - goto leave; + return; method = mono_get_method_checked (assembly->image, token, NULL, NULL, error); - goto_if_nok (error, leave); + return_if_nok (error); - MONO_HANDLE_ASSIGN (res, mono_method_get_object_handle (method, NULL, error)); -leave: - return res; + HANDLE_ON_STACK_SET (res, mono_method_get_object_checked (method, NULL, error)); } -MonoReflectionModuleHandle -ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoReflectionAssemblyHandle assembly, MonoError *error) +void +ves_icall_System_Reflection_Assembly_GetManifestModuleInternal (MonoQCallAssemblyHandle assembly_h, MonoObjectHandleOnStack res, MonoError *error) { - MonoAssembly *a = MONO_HANDLE_GETVAL (assembly, assembly); - return mono_module_get_object_handle (a->image, error); + MonoAssembly *a = assembly_h.assembly; + HANDLE_ON_STACK_SET (res, MONO_HANDLE_RAW (mono_module_get_object_handle (a->image, error))); } static gboolean @@ -4492,24 +4483,21 @@ add_manifest_resource_name_to_array (MonoImage *image, MonoTableInfo *table, int HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); } -MonoArrayHandle -ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceNames (MonoReflectionAssemblyHandle assembly_h, MonoError *error) +void +ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceNames (MonoQCallAssemblyHandle assembly_h, MonoObjectHandleOnStack res, MonoError *error) { - MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly); + MonoAssembly *assembly = assembly_h.assembly; MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE]; /* FIXME: metadata-update */ int rows = table_info_get_rows (table); MonoArrayHandle result = mono_array_new_handle (mono_defaults.string_class, rows, error); - goto_if_nok (error, fail); - int i; + return_if_nok (error); - for (i = 0; i < rows; ++i) { + for (int i = 0; i < rows; ++i) { if (!add_manifest_resource_name_to_array (assembly->image, table, i, result, error)) - goto fail; + return; } - return result; -fail: - return NULL_HANDLE_ARRAY; + HANDLE_ON_STACK_SET (res, MONO_HANDLE_RAW (result)); } static MonoAssemblyName* @@ -4536,16 +4524,15 @@ create_referenced_assembly_name (MonoImage *image, int i, MonoError *error) } GPtrArray* -ves_icall_System_Reflection_Assembly_InternalGetReferencedAssemblies (MonoReflectionAssemblyHandle assembly, MonoError *error) +ves_icall_System_Reflection_Assembly_InternalGetReferencedAssemblies (MonoReflectionAssemblyHandle assembly_h, MonoError *error) { - error_init (error); - MonoAssembly *ass = MONO_HANDLE_GETVAL(assembly, assembly); - MonoImage *image = ass->image; + MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly); + MonoImage *image = assembly->image; int count; /* FIXME: metadata-update */ - if (image_is_dynamic (ass->image)) { + if (image_is_dynamic (assembly->image)) { MonoDynamicTable *t = &(((MonoDynamicImage*) image)->tables [MONO_TABLE_ASSEMBLYREF]); count = t->rows; } @@ -4626,10 +4613,10 @@ try_resource_resolve_name (MonoReflectionAssemblyHandle assembly_handle, MonoStr HANDLE_FUNCTION_RETURN_REF (MonoReflectionAssembly, MONO_HANDLE_CAST (MonoReflectionAssembly, ret)); } -static void * -get_manifest_resource_internal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, gint32 *size, MonoReflectionModuleHandleOut ref_module, MonoError *error) +void * +ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInternal (MonoQCallAssemblyHandle assembly_h, MonoStringHandle name, gint32 *size, MonoObjectHandleOnStack ref_module, MonoError *error) { - MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly); + MonoAssembly *assembly = assembly_h.assembly; MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE]; guint32 i; guint32 cols [MONO_MANIFEST_SIZE]; @@ -4664,37 +4651,21 @@ get_manifest_resource_internal (MonoReflectionAssemblyHandle assembly_h, MonoStr module = mono_image_load_file_for_image_checked (assembly->image, file_idx, error); if (!is_ok (error) || !module) return NULL; - } - else + } else { module = assembly->image; - + } MonoReflectionModuleHandle rm = mono_module_get_object_handle (module, error); return_val_if_nok (error, NULL); - MONO_HANDLE_ASSIGN (ref_module, rm); + HANDLE_ON_STACK_SET (ref_module, MONO_HANDLE_RAW (rm)); return (void*)mono_image_get_resource (module, cols [MONO_MANIFEST_OFFSET], (guint32*)size); } -void * -ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, gint32 *size, MonoReflectionModuleHandleOut ref_module, MonoError *error) -{ - gpointer ret = get_manifest_resource_internal (assembly_h, name, size, ref_module, error); - - if (!ret) { - MonoReflectionAssemblyHandle event_assembly_h = try_resource_resolve_name (assembly_h, name); - if (MONO_HANDLE_BOOL (event_assembly_h)) - ret = get_manifest_resource_internal (event_assembly_h, name, size, ref_module, error); - } - - return ret; -} - static gboolean -get_manifest_resource_info_internal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info, MonoError *error) +get_manifest_resource_info_internal (MonoAssembly *assembly, MonoStringHandle name, MonoManifestResourceInfoHandle info, MonoError *error) { HANDLE_FUNCTION_ENTER (); - MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly); MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_MANIFESTRESOURCE]; int i; guint32 cols [MONO_MANIFEST_SIZE]; @@ -4748,7 +4719,7 @@ get_manifest_resource_info_internal (MonoReflectionAssemblyHandle assembly_h, Mo MONO_HANDLE_SET (info, assembly, assm_obj); /* Obtain info recursively */ - get_manifest_resource_info_internal (assm_obj, name, info, error); + get_manifest_resource_info_internal (MONO_HANDLE_GETVAL (assm_obj, assembly), name, info, error); goto_if_nok (error, leave); guint32 location; location = MONO_HANDLE_GETVAL (info, location); @@ -4768,81 +4739,15 @@ get_manifest_resource_info_internal (MonoReflectionAssemblyHandle assembly_h, Mo } MonoBoolean -ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInfoInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info_h, MonoError *error) +ves_icall_System_Reflection_RuntimeAssembly_GetManifestResourceInfoInternal (MonoQCallAssemblyHandle assembly_h, MonoStringHandle name, MonoManifestResourceInfoHandle info_h, MonoError *error) { - return get_manifest_resource_info_internal (assembly_h, name, info_h, error); -} - -static gboolean -add_filename_to_files_array (MonoAssembly * assembly, MonoTableInfo *table, int i, MonoArrayHandle dest, int dest_idx, MonoError *error) -{ - HANDLE_FUNCTION_ENTER(); - const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME)); - char *n = g_concat_dir_and_file (assembly->basedir, val); - MonoStringHandle str = mono_string_new_handle (n, error); - g_free (n); - goto_if_nok (error, leave); - MONO_HANDLE_ARRAY_SETREF (dest, dest_idx, str); -leave: - HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); -} - -MonoObjectHandle -ves_icall_System_Reflection_RuntimeAssembly_GetFilesInternal (MonoReflectionAssemblyHandle assembly_h, MonoStringHandle name, MonoBoolean resource_modules, MonoError *error) -{ - MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly); - MonoTableInfo *table = &assembly->image->tables [MONO_TABLE_FILE]; - int i, count; - - int rows = table_info_get_rows (table); - /* check hash if needed */ - if (!MONO_HANDLE_IS_NULL(name)) { - char *n = mono_string_handle_to_utf8 (name, error); - goto_if_nok (error, fail); - - for (i = 0; i < rows; ++i) { - const char *val = mono_metadata_string_heap (assembly->image, mono_metadata_decode_row_col (table, i, MONO_FILE_NAME)); - if (strcmp (val, n) == 0) { - g_free (n); - n = g_concat_dir_and_file (assembly->basedir, val); - MonoStringHandle fn = mono_string_new_handle (n, error); - g_free (n); - goto_if_nok (error, fail); - return MONO_HANDLE_CAST (MonoObject, fn); - } - } - g_free (n); - return NULL_HANDLE; - } - - count = 0; - for (i = 0; i < rows; ++i) { - if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) - count ++; - } - - MonoArrayHandle result; - result = mono_array_new_handle (mono_defaults.string_class, count, error); - goto_if_nok (error, fail); - - count = 0; - for (i = 0; i < rows; ++i) { - if (resource_modules || !(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) { - if (!add_filename_to_files_array (assembly, table, i, result, count, error)) - goto fail; - count++; - } - } - return MONO_HANDLE_CAST (MonoObject, result); -fail: - return NULL_HANDLE; + return get_manifest_resource_info_internal (assembly_h.assembly, name, info_h, error); } static gboolean add_module_to_modules_array (MonoArrayHandle dest, int *dest_idx, MonoImage* module, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); if (module) { MonoReflectionModuleHandle rm = mono_module_get_object_handle (module, error); goto_if_nok (error, leave); @@ -4883,11 +4788,10 @@ add_file_to_modules_array (MonoArrayHandle dest, int dest_idx, MonoImage *image, HANDLE_FUNCTION_RETURN_VAL (is_ok (error)); } -MonoArrayHandle -ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal (MonoReflectionAssemblyHandle assembly_h, MonoError *error) +void +ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal (MonoQCallAssemblyHandle assembly_h, MonoObjectHandleOnStack res_h, MonoError *error) { - error_init (error); - MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly); + MonoAssembly *assembly = assembly_h.assembly; MonoClass *klass; int i, j, file_count = 0; MonoImage **modules; @@ -4911,27 +4815,24 @@ ves_icall_System_Reflection_RuntimeAssembly_GetModulesInternal (MonoReflectionAs klass = mono_class_get_module_class (); MonoArrayHandle res = mono_array_new_handle (klass, 1 + real_module_count + file_count, error); - goto_if_nok (error, fail); + return_if_nok (error); - MonoReflectionModuleHandle image_obj; - image_obj = mono_module_get_object_handle (image, error); - goto_if_nok (error, fail); + MonoReflectionModuleHandle image_obj = mono_module_get_object_handle (image, error); + return_if_nok (error); MONO_HANDLE_ARRAY_SETREF (res, 0, image_obj); j = 1; for (i = 0; i < module_count; ++i) if (!add_module_to_modules_array (res, &j, modules[i], error)) - goto fail; + return; for (i = 0; i < file_count; ++i, ++j) { if (!add_file_to_modules_array (res, j, image, table, i, error)) - goto fail; + return; } - return res; -fail: - return NULL_HANDLE_ARRAY; + HANDLE_ON_STACK_SET (res_h, MONO_HANDLE_RAW (res)); } MonoReflectionMethodHandle @@ -5039,7 +4940,6 @@ ves_icall_System_Reflection_Assembly_GetEntryAssembly (MonoError *error) MonoReflectionAssemblyHandle ves_icall_System_Reflection_Assembly_GetCallingAssembly (MonoError *error) { - error_init (error); MonoMethod *m; MonoMethod *dest; @@ -5084,18 +4984,6 @@ ves_icall_System_RuntimeType_getFullName (MonoQCallTypeHandle type_handle, MonoO g_free (name); } -MonoStringHandle -ves_icall_System_Reflection_RuntimeAssembly_get_fullname (MonoReflectionAssemblyHandle assembly, MonoError *error) -{ - MonoAssembly *mass = MONO_HANDLE_GETVAL (assembly, assembly); - gchar *name; - - name = mono_stringify_assembly_name (&mass->aname); - MonoStringHandle res = mono_string_new_handle (name, error); - g_free (name); - return res; -} - MonoAssemblyName * ves_icall_System_Reflection_AssemblyName_GetNativeName (MonoAssembly *mass) { @@ -5111,8 +4999,6 @@ ves_icall_System_Reflection_Assembly_InternalGetAssemblyName (MonoStringHandle f gboolean res; MonoImage *image; - error_init (error); - filename = mono_string_handle_to_utf8 (fname, error); return_if_nok (error); @@ -5176,7 +5062,6 @@ mono_module_type_is_visible (MonoTableInfo *tdef, MonoImage *image, int type) static void image_get_type (MonoImage *image, MonoTableInfo *tdef, int table_idx, int count, MonoArrayHandle res, MonoArrayHandle exceptions, MonoBoolean exportedOnly, MonoError *error) { - error_init (error); HANDLE_FUNCTION_ENTER (); ERROR_DECL (klass_error); MonoClass *klass = mono_class_get_checked (image, table_idx | MONO_TOKEN_TYPE_DEF, klass_error); @@ -5201,8 +5086,6 @@ mono_module_get_types (MonoImage *image, MonoArrayHandleOut exceptions, MonoBool int rows = table_info_get_rows (tdef); int i, count; - error_init (error); - /* we start the count from 1 because we skip the special type */ if (exportedOnly) { count = 0; @@ -5233,7 +5116,6 @@ static void append_module_types (MonoArrayHandleOut res, MonoArrayHandleOut exceptions, MonoImage *image, MonoBoolean exportedOnly, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); MonoArrayHandle ex2 = MONO_HANDLE_NEW (MonoArray, NULL); MonoArrayHandle res2 = mono_module_get_types (image, ex2, exportedOnly, error); goto_if_nok (error, leave); @@ -5275,30 +5157,30 @@ set_class_failure_in_array (MonoArrayHandle exl, int i, MonoClass *klass) HANDLE_FUNCTION_RETURN (); } -static MonoArrayHandle -assembly_get_types (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean exportedOnly, MonoError *error) +void +ves_icall_System_Reflection_RuntimeAssembly_GetExportedTypes (MonoQCallAssemblyHandle assembly_handle, MonoObjectHandleOnStack res_h, + MonoError *error) { MonoArrayHandle exceptions = MONO_HANDLE_NEW(MonoArray, NULL); + MonoAssembly *assembly = assembly_handle.assembly; int i; - MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_handle, assembly); - g_assert (!assembly_is_dynamic (assembly)); MonoImage *image = assembly->image; MonoTableInfo *table = &image->tables [MONO_TABLE_FILE]; - MonoArrayHandle res = mono_module_get_types (image, exceptions, exportedOnly, error); - return_val_if_nok (error, NULL_HANDLE_ARRAY); + MonoArrayHandle res = mono_module_get_types (image, exceptions, TRUE, error); + return_if_nok (error); /* Append data from all modules in the assembly */ int rows = table_info_get_rows (table); for (i = 0; i < rows; ++i) { if (!(mono_metadata_decode_row_col (table, i, MONO_FILE_FLAGS) & FILE_CONTAINS_NO_METADATA)) { MonoImage *loaded_image = mono_assembly_load_module_checked (image->assembly, i + 1, error); - return_val_if_nok (error, NULL_HANDLE_ARRAY); + return_if_nok (error); if (loaded_image) { - append_module_types (res, exceptions, loaded_image, exportedOnly, error); - return_val_if_nok (error, NULL_HANDLE_ARRAY); + append_module_types (res, exceptions, loaded_image, TRUE, error); + return_if_nok (error); } } } @@ -5336,7 +5218,7 @@ assembly_get_types (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean ex MonoArrayHandle exl = mono_array_new_handle (mono_defaults.exception_class, length, error); if (!is_ok (error)) { g_list_free (list); - return NULL_HANDLE_ARRAY; + return; } /* Types for which mono_class_get_checked () succeeded */ MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL); @@ -5356,18 +5238,12 @@ assembly_get_types (MonoReflectionAssemblyHandle assembly_handle, MonoBoolean ex list = NULL; MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (res, exl, error)); - return_val_if_nok (error, NULL_HANDLE_ARRAY); + return_if_nok (error); mono_error_set_exception_handle (error, exc); - return NULL_HANDLE_ARRAY; + return; } - return res; -} - -MonoArrayHandle -ves_icall_System_Reflection_RuntimeAssembly_GetExportedTypes (MonoReflectionAssemblyHandle assembly_handle, MonoError *error) -{ - return assembly_get_types (assembly_handle, TRUE, error); + HANDLE_ON_STACK_SET (res_h, MONO_HANDLE_RAW (res)); } static void @@ -5426,10 +5302,11 @@ get_top_level_forwarded_type (MonoImage *image, MonoTableInfo *table, int i, Mon HANDLE_FUNCTION_RETURN (); } -MonoArrayHandle -ves_icall_System_Reflection_RuntimeAssembly_GetTopLevelForwardedTypes (MonoReflectionAssemblyHandle assembly_h, MonoError *error) +void +ves_icall_System_Reflection_RuntimeAssembly_GetTopLevelForwardedTypes (MonoQCallAssemblyHandle assembly_h, MonoObjectHandleOnStack res, + MonoError *error) { - MonoAssembly *assembly = MONO_HANDLE_GETVAL (assembly_h, assembly); + MonoAssembly *assembly = assembly_h.assembly; MonoImage *image = assembly->image; int count = 0; @@ -5442,25 +5319,24 @@ ves_icall_System_Reflection_RuntimeAssembly_GetTopLevelForwardedTypes (MonoRefle } MonoArrayHandle types = mono_array_new_handle (mono_defaults.runtimetype_class, count, error); - return_val_if_nok (error, NULL_HANDLE_ARRAY); + return_if_nok (error); MonoArrayHandle exceptions = mono_array_new_handle (mono_defaults.exception_class, count, error); - return_val_if_nok (error, NULL_HANDLE_ARRAY); + return_if_nok (error); int aindex = 0; int exception_count = 0; - for (int i = 0; i < rows; ++i) { + for (int i = 0; i < rows; ++i) get_top_level_forwarded_type (image, table, i, types, exceptions, &aindex, &exception_count); - } if (exception_count > 0) { MonoExceptionHandle exc = MONO_HANDLE_NEW (MonoException, NULL); MONO_HANDLE_ASSIGN (exc, mono_get_exception_reflection_type_load_checked (types, exceptions, error)); - return_val_if_nok (error, NULL_HANDLE_ARRAY); + return_if_nok (error); mono_error_set_exception_handle (error, exc); - return NULL_HANDLE_ARRAY; + return; } - return types; + HANDLE_ON_STACK_SET (res, MONO_HANDLE_RAW (types)); } void @@ -5675,7 +5551,6 @@ static MonoType* module_resolve_type_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); MonoType *result = NULL; MonoClass *klass; int table = mono_metadata_token_table (token); @@ -5735,7 +5610,6 @@ static MonoMethod* module_resolve_method_token (MonoImage *image, guint32 token, MonoArrayHandle type_args, MonoArrayHandle method_args, MonoResolveTokenError *resolve_error, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); MonoMethod *method = NULL; int table = mono_metadata_token_table (token); int index = mono_metadata_token_index (token); @@ -5833,7 +5707,6 @@ module_resolve_field_token (MonoImage *image, guint32 token, MonoArrayHandle typ MonoGenericContext context; MonoClassField *field = NULL; - error_init (error); *resolve_error = ResolveTokenError_Other; /* Validate token */ @@ -5988,8 +5861,6 @@ check_for_invalid_array_type (MonoType *type, MonoError *error) gboolean allowed = TRUE; char *name; - error_init (error); - if (m_type_is_byref (type)) allowed = FALSE; else if (type->type == MONO_TYPE_TYPEDBYREF) @@ -6447,24 +6318,17 @@ ves_icall_System_TypedReference_InternalMakeTypedReference (MonoTypedRef *res, M res->value = (guint8*)MONO_HANDLE_RAW (target) + offset; } -static void -prelink_method (MonoMethod *method, MonoError *error) +void +ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethodHandle method_h, MonoError *error) { - error_init (error); + MonoMethod *method = MONO_HANDLE_GETVAL (method_h, method); + if (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) return; mono_lookup_pinvoke_call_internal (method, error); /* create the wrapper, too? */ } -void -ves_icall_System_Runtime_InteropServices_Marshal_Prelink (MonoReflectionMethodHandle method, MonoError *error) -{ - error_init (error); - - prelink_method (MONO_HANDLE_GETVAL (method, method), error); -} - int ves_icall_Interop_Sys_DoubleToString(double value, char *format, char *buffer, int bufferLength) { @@ -6487,7 +6351,6 @@ static gboolean add_modifier_to_array (MonoType *type, MonoArrayHandle dest, int dest_idx, MonoError *error) { HANDLE_FUNCTION_ENTER (); - error_init (error); MonoClass *klass = mono_class_from_mono_type_internal (type); MonoReflectionTypeHandle rt; @@ -6512,7 +6375,6 @@ type_array_from_modifiers (MonoType *type, int optional, MonoError *error) if (cmod_count == 0) goto fail; - error_init (error); for (i = 0; i < cmod_count; ++i) { gboolean required; (void) mono_type_get_custom_modifier (type, i, &required, error); @@ -6545,7 +6407,6 @@ type_array_from_modifiers (MonoType *type, int optional, MonoError *error) MonoArrayHandle ves_icall_RuntimeParameterInfo_GetTypeModifiers (MonoReflectionTypeHandle rt, MonoObjectHandle member, int pos, MonoBoolean optional, MonoError *error) { - error_init (error); MonoType *type = MONO_HANDLE_GETVAL (rt, type); MonoClass *member_class = mono_handle_class (member); MonoMethod *method = NULL; @@ -6597,7 +6458,6 @@ get_property_type (MonoProperty *prop) MonoArrayHandle ves_icall_RuntimePropertyInfo_GetTypeModifiers (MonoReflectionPropertyHandle property, MonoBoolean optional, MonoError *error) { - error_init (error); MonoProperty *prop = MONO_HANDLE_GETVAL (property, property); MonoType *type = get_property_type (prop); diff --git a/src/mono/mono/metadata/loader-internals.h b/src/mono/mono/metadata/loader-internals.h index bc79d38d4eb5b..772c2dc875ebb 100644 --- a/src/mono/mono/metadata/loader-internals.h +++ b/src/mono/mono/metadata/loader-internals.h @@ -356,6 +356,18 @@ mono_mem_manager_get_generic (MonoImage **images, int nimages); MonoMemoryManager* mono_mem_manager_merge (MonoMemoryManager *mm1, MonoMemoryManager *mm2); +static inline GSList* +g_slist_prepend_mem_manager (MonoMemoryManager *memory_manager, GSList *list, gpointer data) +{ + GSList *new_list; + + new_list = (GSList *) mono_mem_manager_alloc (memory_manager, sizeof (GSList)); + new_list->data = data; + new_list->next = list; + + return new_list; +} + G_END_DECLS #endif diff --git a/src/mono/mono/metadata/loader.c b/src/mono/mono/metadata/loader.c index 7098bb527a4b3..e0ce3f575ae06 100644 --- a/src/mono/mono/metadata/loader.c +++ b/src/mono/mono/metadata/loader.c @@ -107,6 +107,12 @@ mono_loader_init () } } +MonoDefaults * +mono_get_defaults (void) +{ + return &mono_defaults; +} + void mono_global_loader_data_lock (void) { diff --git a/src/mono/mono/metadata/metadata-update.c b/src/mono/mono/metadata/metadata-update.c index 800ffb9f04727..e24823ead81f3 100644 --- a/src/mono/mono/metadata/metadata-update.c +++ b/src/mono/mono/metadata/metadata-update.c @@ -12,6 +12,7 @@ #include "mono/metadata/metadata-update.h" #include "mono/metadata/components.h" +#include "mono/metadata/class-internals.h" #include "mono/component/hot_reload.h" gboolean @@ -147,3 +148,37 @@ mono_metadata_table_num_rows_slow (MonoImage *base_image, int table_index) { return mono_component_hot_reload()->table_num_rows_slow (base_image, table_index); } + +void* +mono_metadata_update_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer) +{ + return mono_component_hot_reload()->metadata_linear_search (base_image, base_table, key, comparer); +} + +/* + * Returns the (1-based) table row index of the fielddef of the given field + * (which must have m_field_is_from_update set). + */ +uint32_t +mono_metadata_update_get_field_idx (MonoClassField *field) +{ + return mono_component_hot_reload()->get_field_idx (field); +} + +MonoClassField * +mono_metadata_update_get_field (MonoClass *klass, uint32_t fielddef_token) +{ + return mono_component_hot_reload()->get_field (klass, fielddef_token); +} + +gpointer +mono_metadata_update_get_static_field_addr (MonoClassField *field) +{ + return mono_component_hot_reload()->get_static_field_addr (field); +} + +MonoMethod * +mono_metadata_update_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error) +{ + return mono_component_hot_reload()->find_method_by_name (klass, name, param_count, flags, error); +} diff --git a/src/mono/mono/metadata/metadata-update.h b/src/mono/mono/metadata/metadata-update.h index 15d0d51e10f4a..ee999a4f0a10f 100644 --- a/src/mono/mono/metadata/metadata-update.h +++ b/src/mono/mono/metadata/metadata-update.h @@ -6,6 +6,7 @@ #define __MONO_METADATA_UPDATE_H__ #include "mono/utils/mono-forward.h" +#include "mono/utils/bsearch.h" #include "mono/metadata/loader-internals.h" #include "mono/metadata/metadata-internals.h" @@ -57,4 +58,19 @@ mono_metadata_update_table_bounds_check (MonoImage *base_image, int table_index, gboolean mono_metadata_update_delta_heap_lookup (MonoImage *base_image, MetadataHeapGetterFunc get_heap, uint32_t orig_index, MonoImage **image_out, uint32_t *index_out); +void* +mono_metadata_update_metadata_linear_search (MonoImage *base_image, MonoTableInfo *base_table, const void *key, BinarySearchComparer comparer); + +MonoMethod* +mono_metadata_update_find_method_by_name (MonoClass *klass, const char *name, int param_count, int flags, MonoError *error); + +uint32_t +mono_metadata_update_get_field_idx (MonoClassField *field); + +MonoClassField * +mono_metadata_update_get_field (MonoClass *klass, uint32_t fielddef_token); + +gpointer +mono_metadata_update_get_static_field_addr (MonoClassField *field); + #endif /*__MONO_METADATA_UPDATE_H__*/ diff --git a/src/mono/mono/metadata/metadata.c b/src/mono/mono/metadata/metadata.c index 04a43f5e0076f..8aa7a921ab48c 100644 --- a/src/mono/mono/metadata/metadata.c +++ b/src/mono/mono/metadata/metadata.c @@ -4801,7 +4801,12 @@ mono_metadata_typedef_from_field (MonoImage *meta, guint32 index) if (meta->uncompressed_metadata) loc.idx = search_ptr_table (meta, MONO_TABLE_FIELD_POINTER, loc.idx); - /* FIXME: metadata-update */ + /* if it's not in the base image, look in the hot reload table */ + gboolean added = (loc.idx > table_info_get_rows (&meta->tables [MONO_TABLE_FIELD])); + if (added) { + uint32_t res = mono_component_hot_reload()->field_parent (meta, loc.idx); + return res; /* 0 if not found, otherwise 1-based */ + } if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, typedef_locator)) return 0; @@ -4974,18 +4979,22 @@ mono_metadata_nested_in_typedef (MonoImage *meta, guint32 index) MonoTableInfo *tdef = &meta->tables [MONO_TABLE_NESTEDCLASS]; locator_t loc; - if (!tdef->base) + if (!tdef->base && !meta->has_updates) return 0; loc.idx = mono_metadata_token_index (index); loc.col_idx = MONO_NESTED_CLASS_NESTED; loc.t = tdef; - /* FIXME: metadata-update */ - - if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) + gboolean found = tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator) != NULL; + if (!found && !meta->has_updates) return 0; + if (G_UNLIKELY (meta->has_updates)) { + if (!found && !mono_metadata_update_metadata_linear_search (meta, tdef, &loc, table_locator)) + return 0; + } + /* loc_result is 0..1, needs to be mapped to table index (that is +1) */ return mono_metadata_decode_row_col (tdef, loc.result, MONO_NESTED_CLASS_ENCLOSING) | MONO_TOKEN_TYPE_DEF; } @@ -5077,19 +5086,24 @@ mono_metadata_custom_attrs_from_index (MonoImage *meta, guint32 index) MonoTableInfo *tdef = &meta->tables [MONO_TABLE_CUSTOMATTRIBUTE]; locator_t loc; - if (!tdef->base) + if (!tdef->base && !meta->has_updates) return 0; loc.idx = index; loc.col_idx = MONO_CUSTOM_ATTR_PARENT; loc.t = tdef; - /* FIXME: metadata-update */ /* FIXME: Index translation */ - if (!mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator)) + gboolean found = tdef->base && mono_binary_search (&loc, tdef->base, table_info_get_rows (tdef), tdef->row_size, table_locator) != NULL; + if (!found && !meta->has_updates) return 0; + if (G_UNLIKELY (meta->has_updates)) { + if (!found && !mono_metadata_update_metadata_linear_search (meta, tdef, &loc, table_locator)) + return 0; + } + /* Find the first entry by searching backwards */ while ((loc.result > 0) && (mono_metadata_decode_row_col (tdef, loc.result - 1, MONO_CUSTOM_ATTR_PARENT) == index)) loc.result --; diff --git a/src/mono/mono/metadata/object-internals.h b/src/mono/mono/metadata/object-internals.h index 6c6d089ee2122..c1c4d939df2a1 100644 --- a/src/mono/mono/metadata/object-internals.h +++ b/src/mono/mono/metadata/object-internals.h @@ -1666,7 +1666,7 @@ mono_class_set_ref_info (MonoClass *klass, MonoObjectHandle obj); void mono_class_free_ref_info (MonoClass *klass); -MonoObject * +MONO_COMPONENT_API MonoObject * mono_object_new_pinned (MonoClass *klass, MonoError *error); MonoObjectHandle diff --git a/src/mono/mono/metadata/object.c b/src/mono/mono/metadata/object.c index 284e15b1ade8e..d87fade6e6122 100644 --- a/src/mono/mono/metadata/object.c +++ b/src/mono/mono/metadata/object.c @@ -44,6 +44,7 @@ #include #include #include +#include #include #include #include @@ -2854,6 +2855,9 @@ mono_static_field_get_addr (MonoVTable *vt, MonoClassField *field) g_assert (field->type->attrs & FIELD_ATTRIBUTE_STATIC); if (field->offset == -1) { + if (G_UNLIKELY (m_field_is_from_update (field))) { + return mono_metadata_update_get_static_field_addr (field); + } /* Special static */ ERROR_DECL (error); gpointer addr = mono_special_static_field_get_offset (field, error); @@ -6791,9 +6795,9 @@ mono_string_is_interned_lookup (MonoStringHandle str, gboolean insert, MonoError #ifdef HOST_WASM /** * mono_string_instance_is_interned: - * Searches the interned string table for the provided string instance. + * Checks to see if the string instance has its interned flag set. * \param str String to probe - * \returns TRUE if the string is interned, FALSE otherwise. + * \returns TRUE if the string instance is interned, FALSE otherwise. */ int mono_string_instance_is_interned (MonoString *str) diff --git a/src/mono/mono/metadata/sysmath.c b/src/mono/mono/metadata/sysmath.c index e8fef9f8e08e9..ec25a20fc0025 100644 --- a/src/mono/mono/metadata/sysmath.c +++ b/src/mono/mono/metadata/sysmath.c @@ -1,6 +1,6 @@ /** * \file - * these are based on bob smith's csharp routines + * these are based on bob smith's csharp routines * * Author: * Mono Project (http://www.mono-project.com) @@ -55,49 +55,49 @@ ves_icall_System_Math_ModF (gdouble x, gdouble *d) return modf (x, d); } -gdouble +gdouble ves_icall_System_Math_Sin (gdouble x) { return sin (x); } -gdouble +gdouble ves_icall_System_Math_Cos (gdouble x) { return cos (x); } -gdouble +gdouble ves_icall_System_Math_Cbrt (gdouble x) { return cbrt (x); } -gdouble +gdouble ves_icall_System_Math_Tan (gdouble x) { return tan (x); } -gdouble +gdouble ves_icall_System_Math_Sinh (gdouble x) { return sinh (x); } -gdouble +gdouble ves_icall_System_Math_Cosh (gdouble x) { return cosh (x); } -gdouble +gdouble ves_icall_System_Math_Tanh (gdouble x) { return tanh (x); } -gdouble +gdouble ves_icall_System_Math_Acos (gdouble x) { return acos (x); @@ -109,78 +109,66 @@ ves_icall_System_Math_Acosh (gdouble x) return acosh (x); } -gdouble +gdouble ves_icall_System_Math_Asin (gdouble x) { return asin (x); } -gdouble +gdouble ves_icall_System_Math_Asinh (gdouble x) { return asinh (x); } -gdouble +gdouble ves_icall_System_Math_Atan (gdouble x) { return atan (x); } -gdouble +gdouble ves_icall_System_Math_Atan2 (gdouble y, gdouble x) { return atan2 (y, x); } -gdouble +gdouble ves_icall_System_Math_Atanh (gdouble x) { return atanh (x); } -gdouble +gdouble ves_icall_System_Math_Exp (gdouble x) { return exp (x); } -gdouble +gdouble ves_icall_System_Math_Log (gdouble x) { return log (x); } -gdouble +gdouble ves_icall_System_Math_Log10 (gdouble x) { return log10 (x); } -gdouble +gdouble ves_icall_System_Math_Pow (gdouble x, gdouble y) { return pow (x, y); } -gdouble +gdouble ves_icall_System_Math_Sqrt (gdouble x) { return sqrt (x); } -gdouble -ves_icall_System_Math_Abs_double (gdouble v) -{ - return fabs (v); -} - -float -ves_icall_System_Math_Abs_single (float v) -{ - return fabsf (v); -} - gdouble ves_icall_System_Math_Ceiling (gdouble v) { diff --git a/src/mono/mono/mini/interp/interp.c b/src/mono/mono/mini/interp/interp.c index e5aef94c5c6ee..099c70695c138 100644 --- a/src/mono/mono/mini/interp/interp.c +++ b/src/mono/mono/mini/interp/interp.c @@ -1930,7 +1930,7 @@ dump_args (InterpFrame *inv) GString *str = g_string_new (""); int i; MonoMethodSignature *signature = mono_method_signature_internal (inv->imethod->method); - + if (signature->param_count == 0 && !signature->hasthis) return g_string_free (str, FALSE); @@ -3232,7 +3232,7 @@ static long opcode_counts[MINT_LASTOP]; #define COUNT_OP(op) opcode_counts[op]++ #else -#define COUNT_OP(op) +#define COUNT_OP(op) #endif #if DEBUG_INTERP @@ -3478,7 +3478,7 @@ interp_exec_method (InterpFrame *frame, ThreadContext *context, FrameClauseArgs #endif main_loop: /* - * using while (ip < end) may result in a 15% performance drop, + * using while (ip < end) may result in a 15% performance drop, * but it may be useful for debug */ while (1) { @@ -3559,7 +3559,7 @@ interp_exec_method (InterpFrame *frame, ThreadContext *context, FrameClauseArgs MINT_IN_CASE(MINT_LDC_I4_8) LDC(8); MINT_IN_BREAK; - MINT_IN_CASE(MINT_LDC_I4_S) + MINT_IN_CASE(MINT_LDC_I4_S) LOCAL_VAR (ip [1], gint32) = (short)ip [2]; ip += 3; MINT_IN_BREAK; @@ -3584,7 +3584,7 @@ interp_exec_method (InterpFrame *frame, ThreadContext *context, FrameClauseArgs ip += 4; MINT_IN_BREAK; } - MINT_IN_CASE(MINT_LDC_R8) + MINT_IN_CASE(MINT_LDC_R8) LOCAL_VAR (ip [1], gint64) = READ64 (ip + 2); /* note union usage */ ip += 6; MINT_IN_BREAK; @@ -3720,7 +3720,7 @@ interp_exec_method (InterpFrame *frame, ThreadContext *context, FrameClauseArgs call_args_offset = ip [3]; if (need_unbox) { - MonoObject *this_arg = LOCAL_VAR (call_args_offset, MonoObject*); + MonoObject *this_arg = LOCAL_VAR (call_args_offset, MonoObject*); LOCAL_VAR (call_args_offset, gpointer) = mono_object_unbox_internal (this_arg); } ip += 4; @@ -6450,8 +6450,8 @@ MINT_IN_CASE(MINT_BRTRUE_I8_SP) ZEROP_SP(gint64, !=); MINT_IN_BREAK; ip += short_offset ? (gint16)*(ip + 1) : (gint32)READ32 (ip + 1); MINT_IN_BREAK; } - MINT_IN_CASE(MINT_ICALL_V_V) - MINT_IN_CASE(MINT_ICALL_P_V) + MINT_IN_CASE(MINT_ICALL_V_V) + MINT_IN_CASE(MINT_ICALL_P_V) MINT_IN_CASE(MINT_ICALL_PP_V) MINT_IN_CASE(MINT_ICALL_PPP_V) MINT_IN_CASE(MINT_ICALL_PPPP_V) @@ -6476,7 +6476,7 @@ MINT_IN_CASE(MINT_BRTRUE_I8_SP) ZEROP_SP(gint64, !=); MINT_IN_BREAK; CHECK_RESUME_STATE (context); ip += 4; MINT_IN_BREAK; - MINT_IN_CASE(MINT_MONO_LDPTR) + MINT_IN_CASE(MINT_MONO_LDPTR) LOCAL_VAR (ip [1], gpointer) = frame->imethod->data_items [ip [2]]; ip += 3; MINT_IN_BREAK; @@ -6912,12 +6912,12 @@ MINT_IN_CASE(MINT_BRTRUE_I8_SP) ZEROP_SP(gint64, !=); MINT_IN_BREAK; MINT_IN_BREAK; } MINT_IN_CASE(MINT_MONO_RETHROW) { - /* + /* * need to clarify what this should actually do: * * Takes an exception from the stack and rethrows it. * This is useful for wrappers that don't want to have to - * use CEE_THROW and lose the exception stacktrace. + * use CEE_THROW and lose the exception stacktrace. */ MonoException *exc = LOCAL_VAR (ip [1], MonoException*); @@ -6950,7 +6950,6 @@ MINT_IN_CASE(MINT_BRTRUE_I8_SP) ZEROP_SP(gint64, !=); MINT_IN_BREAK; LOCAL_VAR (ip [1], double) = mathfunc (LOCAL_VAR (ip [2], double), LOCAL_VAR (ip [3], double)); \ ip += 4; - MINT_IN_CASE(MINT_ABS) MATH_UNOP(fabs); MINT_IN_BREAK; MINT_IN_CASE(MINT_ASIN) MATH_UNOP(asin); MINT_IN_BREAK; MINT_IN_CASE(MINT_ASINH) MATH_UNOP(asinh); MINT_IN_BREAK; MINT_IN_CASE(MINT_ACOS) MATH_UNOP(acos); MINT_IN_BREAK; @@ -6990,7 +6989,6 @@ MINT_IN_CASE(MINT_BRTRUE_I8_SP) ZEROP_SP(gint64, !=); MINT_IN_BREAK; #define MATH_BINOPF(mathfunc) \ LOCAL_VAR (ip [1], float) = mathfunc (LOCAL_VAR (ip [2], float), LOCAL_VAR (ip [3], float)); \ ip += 4; - MINT_IN_CASE(MINT_ABSF) MATH_UNOPF(fabsf); MINT_IN_BREAK; MINT_IN_CASE(MINT_ASINF) MATH_UNOPF(asinf); MINT_IN_BREAK; MINT_IN_CASE(MINT_ASINHF) MATH_UNOPF(asinhf); MINT_IN_BREAK; MINT_IN_CASE(MINT_ACOSF) MATH_UNOPF(acosf); MINT_IN_BREAK; diff --git a/src/mono/mono/mini/interp/mintops.def b/src/mono/mono/mini/interp/mintops.def index 52b2c4bb1522c..59f909b24b365 100644 --- a/src/mono/mono/mini/interp/mintops.def +++ b/src/mono/mono/mini/interp/mintops.def @@ -708,7 +708,6 @@ OPDEF(MINT_LD_DELEGATE_METHOD_PTR, "ld_delegate_method_ptr", 3, 1, 1, MintOpNoAr // Math intrinsics // double -OPDEF(MINT_ABS, "abs", 3, 1, 1, MintOpNoArgs) OPDEF(MINT_ASIN, "asin", 3, 1, 1, MintOpNoArgs) OPDEF(MINT_ASINH, "asinh", 3, 1, 1, MintOpNoArgs) OPDEF(MINT_ACOS, "acos", 3, 1, 1, MintOpNoArgs) @@ -735,7 +734,6 @@ OPDEF(MINT_TAN, "tan", 3, 1, 1, MintOpNoArgs) OPDEF(MINT_TANH, "tanh", 3, 1, 1, MintOpNoArgs) // float. These must be kept in the same order as their double counterpart -OPDEF(MINT_ABSF, "absf", 3, 1, 1, MintOpNoArgs) OPDEF(MINT_ASINF, "asinf", 3, 1, 1, MintOpNoArgs) OPDEF(MINT_ASINHF, "asinhf", 3, 1, 1, MintOpNoArgs) OPDEF(MINT_ACOSF, "acosf", 3, 1, 1, MintOpNoArgs) diff --git a/src/mono/mono/mini/interp/transform.c b/src/mono/mono/mini/interp/transform.c index 263603de741c1..a5d57007d885f 100644 --- a/src/mono/mono/mini/interp/transform.c +++ b/src/mono/mono/mini/interp/transform.c @@ -778,7 +778,7 @@ init_bb_stack_state (TransformData *td, InterpBasicBlock *bb) } } -static void +static void handle_branch (TransformData *td, int long_op, int offset) { int target = td->ip + offset - td->il_code; @@ -806,7 +806,7 @@ handle_branch (TransformData *td, int long_op, int offset) td->last_ins->info.target_bb = target_bb; } -static void +static void one_arg_branch(TransformData *td, int mint_op, int offset, int inst_size) { int type = td->sp [-1].type == STACK_TYPE_O || td->sp [-1].type == STACK_TYPE_MP ? STACK_TYPE_I : td->sp [-1].type; @@ -835,7 +835,7 @@ interp_add_conv (TransformData *td, StackInfo *sp, InterpInst *prev_ins, int typ interp_ins_set_dreg (new_inst, sp->local); } -static void +static void two_arg_branch(TransformData *td, int mint_op, int offset, int inst_size) { int type1 = td->sp [-1].type == STACK_TYPE_O || td->sp [-1].type == STACK_TYPE_MP ? STACK_TYPE_I : td->sp [-1].type; @@ -854,7 +854,7 @@ two_arg_branch(TransformData *td, int mint_op, int offset, int inst_size) } else if (type1 == STACK_TYPE_R8 && type2 == STACK_TYPE_R4) { interp_add_conv (td, td->sp - 2, td->last_ins, STACK_TYPE_R8, MINT_CONV_R8_R4); } else if (type1 != type2) { - g_warning("%s.%s: branch type mismatch %d %d", + g_warning("%s.%s: branch type mismatch %d %d", m_class_get_name (td->method->klass), td->method->name, td->sp [-1].type, td->sp [-2].type); } @@ -910,7 +910,7 @@ binary_arith_op(TransformData *td, int mint_op) if (type2 == STACK_TYPE_MP) type2 = STACK_TYPE_I; if (type1 != type2) { - g_warning("%s.%s: %04x arith type mismatch %s %d %d", + g_warning("%s.%s: %04x arith type mismatch %s %d %d", m_class_get_name (td->method->klass), td->method->name, td->ip - td->il_code, mono_interp_opname (mint_op), type1, type2); } @@ -929,7 +929,7 @@ shift_op(TransformData *td, int mint_op) int op = mint_op + td->sp [-2].type - STACK_TYPE_I4; CHECK_STACK(td, 2); if (td->sp [-1].type != STACK_TYPE_I4) { - g_warning("%s.%s: shift type mismatch %d", + g_warning("%s.%s: shift type mismatch %d", m_class_get_name (td->method->klass), td->method->name, td->sp [-2].type); } @@ -940,7 +940,7 @@ shift_op(TransformData *td, int mint_op) interp_ins_set_dreg (td->last_ins, td->sp [-1].local); } -static int +static int can_store (int st_value, int vt_value) { if (st_value == STACK_TYPE_O || st_value == STACK_TYPE_MP) @@ -967,7 +967,7 @@ get_arg_type_exact (TransformData *td, int n, int *mt) return type; } -static void +static void load_arg(TransformData *td, int n) { gint32 size = 0; @@ -1006,12 +1006,12 @@ load_arg(TransformData *td, int n) } interp_add_ins (td, get_mov_for_type (mt, TRUE)); interp_ins_set_sreg (td->last_ins, n); - interp_ins_set_dreg (td->last_ins, td->sp [-1].local); + interp_ins_set_dreg (td->last_ins, td->sp [-1].local); if (mt == MINT_TYPE_VT) td->last_ins->data [0] = size; } -static void +static void store_arg(TransformData *td, int n) { gint32 size = 0; @@ -1060,7 +1060,7 @@ load_local (TransformData *td, int local) td->last_ins->data [0] = size; } -static void +static void store_local (TransformData *td, int local) { int mt = td->locals [local].mt; @@ -1070,7 +1070,7 @@ store_local (TransformData *td, int local) interp_add_conv (td, td->sp - 1, NULL, STACK_TYPE_I8, MINT_CONV_I8_I4); #endif if (!can_store(td->sp [-1].type, stack_type [mt])) { - g_warning("%s.%s: Store local stack type mismatch %d %d", + g_warning("%s.%s: Store local stack type mismatch %d %d", m_class_get_name (td->method->klass), td->method->name, stack_type [mt], td->sp [-1].type); } @@ -2180,9 +2180,7 @@ interp_handle_intrinsics (TransformData *td, MonoMethod *target_method, MonoClas if (csignature->param_count == 1 && csignature->params [0]->type == param_type) { // unops if (tm [0] == 'A') { - if (strcmp (tm, "Abs") == 0) { - *op = MINT_ABS; - } else if (strcmp (tm, "Asin") == 0){ + if (strcmp (tm, "Asin") == 0){ *op = MINT_ASIN; } else if (strcmp (tm, "Asinh") == 0){ *op = MINT_ASINH; @@ -2245,7 +2243,7 @@ interp_handle_intrinsics (TransformData *td, MonoMethod *target_method, MonoClas } if (*op != -1 && is_float) { - *op = *op + (MINT_ABSF - MINT_ABS); + *op = *op + (MINT_ASINF - MINT_ASIN); } } else if (in_corlib && !strcmp (klass_name_space, "System") && (!strcmp (klass_name, "Span`1") || !strcmp (klass_name, "ReadOnlySpan`1"))) { if (!strcmp (tm, "get_Item")) { @@ -2830,7 +2828,7 @@ interp_inline_method (TransformData *td, MonoMethod *target_method, MonoMethodHe gboolean ret; unsigned int prev_max_stack_height, prev_locals_size; int prev_n_data_items; - int i; + int i; int prev_sp_offset; int prev_aggressive_inlining; MonoGenericContext *generic_context = NULL; @@ -3293,7 +3291,7 @@ interp_transform_call (TransformData *td, MonoMethod *method, MonoMethod *target CHECK_STACK (td, csignature->param_count + csignature->hasthis); if (tailcall && !td->gen_sdb_seq_points && !calli && op == -1 && - (target_method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) == 0 && + (target_method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) == 0 && (target_method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) == 0 && !(target_method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING)) { (void)mono_class_vtable_checked (target_method->klass, error); @@ -3332,7 +3330,7 @@ interp_transform_call (TransformData *td, MonoMethod *method, MonoMethod *target int in_offset = td->ip - td->il_code; if (interp_ip_in_cbb (td, in_offset + 5)) - ++td->ip; /* gobble the CEE_RET if it isn't branched to */ + ++td->ip; /* gobble the CEE_RET if it isn't branched to */ td->ip += 5; return TRUE; } @@ -3438,7 +3436,7 @@ interp_transform_call (TransformData *td, MonoMethod *method, MonoMethod *target else g_error ("Unsupported opcode"); } - + if (op == MINT_LDLEN) { #ifdef MONO_BIG_ARRAYS SET_SIMPLE_TYPE (td->sp - 1, STACK_TYPE_I8); @@ -4426,6 +4424,9 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, end = td->ip + header->code_size; td->cbb = td->entry_bb = (InterpBasicBlock*)mono_mempool_alloc0 (td->mempool, sizeof (InterpBasicBlock)); + if (td->gen_sdb_seq_points) + td->basic_blocks = g_list_prepend_mempool (td->mempool, td->basic_blocks, td->cbb); + td->cbb->index = td->bb_count++; td->cbb->native_offset = -1; td->cbb->stack_height = td->sp - td->stack; @@ -4655,7 +4656,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, } switch (*td->ip) { - case CEE_NOP: + case CEE_NOP: /* lose it */ emitted_funccall_seq_point = FALSE; ++td->ip; @@ -4825,7 +4826,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, interp_ins_set_dreg (td->last_ins, td->sp [-1].local); ++td->ip; break; - case CEE_LDC_I4_S: + case CEE_LDC_I4_S: interp_add_ins (td, MINT_LDC_I4_S); td->last_ins->data [0] = ((gint8 *) td->ip) [1]; push_simple_type (td, STACK_TYPE_I4); @@ -4930,7 +4931,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, last_seq_point->flags |= INTERP_INST_FLAG_SEQ_POINT_NESTED_CALL; } else - emitted_funccall_seq_point = TRUE; + emitted_funccall_seq_point = TRUE; } last_seq_point = interp_add_ins (td, MINT_SDB_SEQ_POINT); // This seq point is actually associated with the instruction following the call @@ -5394,7 +5395,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, } ++td->ip; break; - case CEE_CONV_I: + case CEE_CONV_I: CHECK_STACK (td, 1); switch (td->sp [-1].type) { case STACK_TYPE_R8: @@ -5868,7 +5869,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, case CEE_UNBOX: CHECK_STACK (td, 1); token = read32 (td->ip + 1); - + if (method->wrapper_type != MONO_WRAPPER_NONE) klass = (MonoClass *)mono_method_get_wrapper_data (method, token); else { @@ -6945,7 +6946,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, interp_add_ins (td, MINT_LD_DELEGATE_METHOD_PTR); interp_ins_set_sreg (td->last_ins, td->sp [0].local); push_simple_type (td, STACK_TYPE_I); - interp_ins_set_dreg (td->last_ins, td->sp [-1].local); + interp_ins_set_dreg (td->last_ins, td->sp [-1].local); break; case CEE_MONO_CALLI_EXTRA_ARG: { int saved_local = td->sp [-1].local; @@ -7078,7 +7079,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, td->sp--; interp_ins_set_sreg (td->last_ins, td->sp [0].local); klass = (MonoClass *)mono_method_get_wrapper_data (method, token); - + /*stackval_from_data (signature->ret, frame->retval, sp->data.vt, signature->pinvoke);*/ if (td->sp > td->stack) @@ -7181,7 +7182,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, * to take into account the number of prefix bytes (usually the * throw point is just (ip - n_prefix_bytes). */ - case CEE_PREFIX1: + case CEE_PREFIX1: ++td->ip; switch (*td->ip) { case CEE_ARGLIST: @@ -7330,7 +7331,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, td->ip += 5; break; } - + int index = get_data_item_index (td, mono_interp_get_imethod (m, error)); goto_if_nok (error, exit); if (*td->ip == CEE_LDVIRTFTN) { @@ -7423,7 +7424,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, #if SIZEOF_VOID_P == 8 if (td->sp [-1].type == STACK_TYPE_I8) interp_add_conv (td, td->sp - 1, NULL, STACK_TYPE_I4, MINT_MOV_8); -#endif +#endif interp_add_ins (td, MINT_LOCALLOC); if (td->sp != td->stack + 1) g_warning("CEE_LOCALLOC: stack not empty"); @@ -7539,7 +7540,7 @@ generate_code (TransformData *td, MonoMethod *method, MonoMethodHeader *header, THROW_EX (mono_exception_from_name (mono_defaults.corlib, "System", "InvalidProgramException"), ip - 5); #endif size = mono_type_size (m_class_get_byval_arg (szclass), &align); - } + } interp_add_ins (td, MINT_LDC_I4); WRITE32_INS (td->last_ins, 0, &size); push_simple_type (td, STACK_TYPE_I4); @@ -9130,7 +9131,7 @@ static void initialize_global_var_cb (TransformData *td, int var, gpointer data) { initialize_global_var (td, var, (int)(gsize)data); -} +} static void initialize_global_vars (TransformData *td) @@ -9549,7 +9550,7 @@ interp_fix_localloc_ret (TransformData *td) g_assert (td->has_localloc); for (InterpBasicBlock *bb = td->entry_bb; bb != NULL; bb = bb->next_bb) { InterpInst *ins = bb->first_ins; - while (ins) { + while (ins) { if (ins->opcode >= MINT_RET && ins->opcode <= MINT_RET_VT) ins->opcode += MINT_RET_LOCALLOC - MINT_RET; ins = ins->next; @@ -9803,7 +9804,7 @@ tiered_patcher (MiniTieredPatchPointContext *ctx, gpointer patchsite) #endif -void +void mono_interp_transform_init (void) { mono_os_mutex_init_recursive(&calc_section); diff --git a/src/mono/mono/mini/mini-generic-sharing.c b/src/mono/mono/mini/mini-generic-sharing.c index 449cf376fbaea..f05a78aa8d804 100644 --- a/src/mono/mono/mini/mini-generic-sharing.c +++ b/src/mono/mono/mini/mini-generic-sharing.c @@ -3521,19 +3521,29 @@ mono_method_is_generic_sharable_full (MonoMethod *method, gboolean allow_type_va if (method->is_inflated) { MonoMethodInflated *inflated = (MonoMethodInflated*)method; - MonoGenericContext *context = &inflated->context; + MonoGenericContext *ctx = &inflated->context; - if (!mono_generic_context_is_sharable_full (context, allow_type_vars, allow_partial)) + if (!mono_generic_context_is_sharable_full (ctx, allow_type_vars, allow_partial)) return FALSE; g_assert (inflated->declaring); -#if 0 - if (inflated->declaring->is_generic) { - if (has_constraints (mono_method_get_generic_container (inflated->declaring))) { + /* + * If all the parameters are primitive types and constraints prevent + * them from being instantiated with enums, then only the primitive + * type instantiation is possible, thus sharing is not useful. + * Happens with generic math interfaces. + */ + if ((!ctx->class_inst || is_primitive_inst (ctx->class_inst)) && + (!ctx->method_inst || is_primitive_inst (ctx->method_inst))) { + MonoGenericContainer *container = mono_method_get_generic_container (inflated->declaring); + if (container && has_constraints (container)) { + for (int i = 0; i < container->type_argc; ++i) { + if (!gparam_can_be_enum (&container->type_params [i])) + return FALSE; + } } } -#endif } if (mono_class_is_ginst (method->klass)) { @@ -3544,12 +3554,6 @@ mono_method_is_generic_sharable_full (MonoMethod *method, gboolean allow_type_va g_assert (mono_class_get_generic_class (method->klass)->container_class && mono_class_is_gtd (mono_class_get_generic_class (method->klass)->container_class)); - /* - * If all the parameters are primitive types and constraints prevent - * them from being instantiated with enums, then only the primitive - * type instantiation is possible, thus sharing is not useful. - * Happens with generic math interfaces. - */ if ((!ctx->class_inst || is_primitive_inst (ctx->class_inst)) && (!ctx->method_inst || is_primitive_inst (ctx->method_inst))) { MonoGenericContainer *container = mono_class_get_generic_container (mono_class_get_generic_class (method->klass)->container_class); diff --git a/src/mono/mono/mini/mini-runtime.c b/src/mono/mono/mini/mini-runtime.c index 5aa5426d4e4f3..78d588f38a435 100644 --- a/src/mono/mono/mini/mini-runtime.c +++ b/src/mono/mono/mini/mini-runtime.c @@ -4522,7 +4522,7 @@ mini_init (const char *filename, const char *runtime_version) if (default_opt & MONO_OPT_AOT) mono_aot_init (); - mono_component_debugger ()->init (&mono_defaults); + mono_component_debugger ()->init (); #ifdef MONO_ARCH_GSHARED_SUPPORTED mono_set_generic_sharing_supported (TRUE); diff --git a/src/mono/mono/tests/bug-81673-interface.cs b/src/mono/mono/tests/bug-81673-interface.cs index 95e1100912d85..566f4a67eeffc 100644 --- a/src/mono/mono/tests/bug-81673-interface.cs +++ b/src/mono/mono/tests/bug-81673-interface.cs @@ -1,5 +1,5 @@ // IMyInterface.cs created with MonoDevelop -// User: lluis at 15:47 18/05/2007 +// User: lluis at 15:47 18/05/2007 // using System; diff --git a/src/mono/mono/tests/bug-81673.cs b/src/mono/mono/tests/bug-81673.cs index e2ad02db6c0fe..0e858f7ecaaab 100644 --- a/src/mono/mono/tests/bug-81673.cs +++ b/src/mono/mono/tests/bug-81673.cs @@ -1,5 +1,5 @@ // App.cs created with MonoDevelop -// User: lluis at 15:46 18/05/2007 +// User: lluis at 15:46 18/05/2007 // using System; @@ -30,7 +30,7 @@ public static int Main () return 1; } } - + class MyClass: IMyInterface { public void Run () diff --git a/src/mono/mono/utils/mono-error-internals.h b/src/mono/mono/utils/mono-error-internals.h index a26558689ae1c..f43727dde76bf 100644 --- a/src/mono/mono/utils/mono-error-internals.h +++ b/src/mono/mono/utils/mono-error-internals.h @@ -202,6 +202,7 @@ mono_error_set_generic_error (MonoError *error, const char * name_space, const c void mono_error_set_execution_engine (MonoError *error, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(2,3); +MONO_COMPONENT_API void mono_error_set_not_implemented (MonoError *error, const char *msg_format, ...) MONO_ATTR_FORMAT_PRINTF(2,3); diff --git a/src/mono/nuget/mono-packages.proj b/src/mono/nuget/mono-packages.proj index a56c63f882764..75264e1029605 100644 --- a/src/mono/nuget/mono-packages.proj +++ b/src/mono/nuget/mono-packages.proj @@ -18,7 +18,7 @@ - + diff --git a/src/mono/sample/wasm/Directory.Build.targets b/src/mono/sample/wasm/Directory.Build.targets index 6eaaa941cdd5d..4e7b4c60aea30 100644 --- a/src/mono/sample/wasm/Directory.Build.targets +++ b/src/mono/sample/wasm/Directory.Build.targets @@ -41,5 +41,8 @@ - + diff --git a/src/mono/sample/wasm/browser-nextjs/components/deepThought.js b/src/mono/sample/wasm/browser-nextjs/components/deepThought.js index 7f62cd1ba36ad..44ccb9d7294bb 100644 --- a/src/mono/sample/wasm/browser-nextjs/components/deepThought.js +++ b/src/mono/sample/wasm/browser-nextjs/components/deepThought.js @@ -11,7 +11,9 @@ async function createRuntime() { return createDotnetRuntime({ configSrc: "./mono-config.json", disableDotnet6Compatibility: true, - scriptDirectory: "/", + locateFile: (path, prefix) => { + return '/' + path; + }, instantiateWasm: async (imports, successCallback) => { try { const arrayBufferResult = await WebAssembly.instantiate(arrayBuffer, imports); diff --git a/src/mono/sample/wasm/browser-webpack/app.js b/src/mono/sample/wasm/browser-webpack/app.js index 1171595d84c47..f96a1c9b40fef 100644 --- a/src/mono/sample/wasm/browser-webpack/app.js +++ b/src/mono/sample/wasm/browser-webpack/app.js @@ -5,7 +5,6 @@ async function dotnetMeaning() { try { const { BINDING } = await createDotnetRuntime({ configSrc: "./mono-config.json", - scriptDirectory: "./", }); const meaningFunction = BINDING.bind_static_method("[Wasm.Browser.WebPack.Sample] Sample.Test:Main"); return meaningFunction(); diff --git a/src/mono/sample/wasm/browser/main.js b/src/mono/sample/wasm/browser/main.js index 661af63b64ba8..e50bf9daebf00 100644 --- a/src/mono/sample/wasm/browser/main.js +++ b/src/mono/sample/wasm/browser/main.js @@ -17,10 +17,18 @@ async function loadRuntime() { async function main() { try { const createDotnetRuntime = await loadRuntime(); - const { MONO, BINDING, Module, RuntimeBuildInfo } = await createDotnetRuntime(() => ({ - disableDotnet6Compatibility: true, - configSrc: "./mono-config.json", - })); + const { MONO, BINDING, Module, RuntimeBuildInfo } = await createDotnetRuntime(() => { + console.log('user code in createDotnetRuntime') + return { + disableDotnet6Compatibility: true, + configSrc: "./mono-config.json", + preInit: () => { console.log('user code Module.preInit') }, + preRun: () => { console.log('user code Module.preRun') }, + onRuntimeInitialized: () => { console.log('user code Module.onRuntimeInitialized') }, + postRun: () => { console.log('user code Module.postRun') }, + } + }); + console.log('after createDotnetRuntime') const testMeaning = BINDING.bind_static_method("[Wasm.Browser.CJS.Sample] Sample.Test:TestMeaning"); const ret = testMeaning(); diff --git a/src/mono/sample/wasm/console-node-es6/main.mjs b/src/mono/sample/wasm/console-node-es6/main.mjs index 2325a97eb35f3..cb5584a5cf8c5 100644 --- a/src/mono/sample/wasm/console-node-es6/main.mjs +++ b/src/mono/sample/wasm/console-node-es6/main.mjs @@ -1,15 +1,6 @@ -import { createRequire } from 'module'; -import { dirname } from 'path'; -import { fileURLToPath } from 'url'; import createDotnetRuntime from './dotnet.js' const { MONO } = await createDotnetRuntime(() => ({ - imports: { - //TODO internalize into dotnet.js if possible - require: createRequire(import.meta.url) - }, - //TODO internalize into dotnet.js if possible - scriptDirectory: dirname(fileURLToPath(import.meta.url)) + '/', disableDotnet6Compatibility: true, configSrc: "./mono-config.json", })); diff --git a/src/mono/sample/wasm/console-node-ts/main.ts b/src/mono/sample/wasm/console-node-ts/main.ts index 5f9a0c706007c..4d1ec5673042b 100644 --- a/src/mono/sample/wasm/console-node-ts/main.ts +++ b/src/mono/sample/wasm/console-node-ts/main.ts @@ -1,15 +1,6 @@ -import { createRequire } from 'module'; -import { dirname } from 'path'; -import { fileURLToPath } from 'url'; import createDotnetRuntime from '@microsoft/dotnet-runtime' const { MONO } = await createDotnetRuntime(() => ({ - imports: { - //TODO internalize into dotnet.js if possible - require: createRequire(import.meta.url) - }, - //TODO internalize into dotnet.js if possible - scriptDirectory: dirname(fileURLToPath(import.meta.url)) + '/', disableDotnet6Compatibility: true, configSrc: "./mono-config.json", })); diff --git a/src/mono/wasm/build/README.md b/src/mono/wasm/build/README.md index faed3d05827f6..c6fb0a8681944 100644 --- a/src/mono/wasm/build/README.md +++ b/src/mono/wasm/build/README.md @@ -132,3 +132,13 @@ them for the new task assembly. - `eng/testing/linker/trimmingTests.targets`, - `src/tests/Common/wasm-test-runner/WasmTestRunner.proj` - `src/tests/Directory.Build.targets` + +## Profiling build performance + +If encountering build performance issues, you can use the rollup `--perf` option and the typescript compiler `--generateCpuProfile` option to get build profile data, like so: + +```../emsdk/node/14.15.5_64bit/bin/npm run rollup --perf -- --perf --environment Configuration:Release,NativeBinDir:./rollup-test-data,ProductVersion:12.3.4``` + +```node node_modules/typescript/lib/tsc.js --generateCpuProfile dotnet-tsc.cpuprofile -p tsconfig.json ``` + +The .cpuprofile file generated by node can be opened in the Performance tab of Chrome or Edge's devtools. \ No newline at end of file diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs index 669f37c62c3e7..88ad41efc2172 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs @@ -332,7 +332,7 @@ internal class MethodInfo internal LocalScopeHandleCollection localScopes; public bool IsStatic() => (methodDef.Attributes & MethodAttributes.Static) != 0; public int IsAsync { get; set; } - public bool IsHiddenFromDebugger { get; } + public DebuggerAttributesInfo DebuggerAttrInfo { get; set; } public TypeInfo TypeInfo { get; } public MethodInfo(AssemblyInfo assembly, MethodDefinitionHandle methodDefHandle, int token, SourceFile source, TypeInfo type, MetadataReader asmMetadataReader, MetadataReader pdbMetadataReader) @@ -370,6 +370,7 @@ public MethodInfo(AssemblyInfo assembly, MethodDefinitionHandle methodDefHandle, StartLocation = new SourceLocation(this, start); EndLocation = new SourceLocation(this, end); + DebuggerAttrInfo = new DebuggerAttributesInfo(); foreach (var cattr in methodDef.GetCustomAttributes()) { var ctorHandle = asmMetadataReader.GetCustomAttribute(cattr).Constructor; @@ -377,10 +378,20 @@ public MethodInfo(AssemblyInfo assembly, MethodDefinitionHandle methodDefHandle, { var container = asmMetadataReader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent; var name = asmMetadataReader.GetString(asmMetadataReader.GetTypeReference((TypeReferenceHandle)container).Name); - if (name == "DebuggerHiddenAttribute") + switch (name) { - this.IsHiddenFromDebugger = true; - break; + case "DebuggerHiddenAttribute": + DebuggerAttrInfo.HasDebuggerHidden = true; + break; + case "DebuggerStepThroughAttribute": + DebuggerAttrInfo.HasStepThrough = true; + break; + case "DebuggerNonUserCodeAttribute": + DebuggerAttrInfo.HasNonUserCode = true; + break; + case "DebuggerStepperBoundaryAttribute": + DebuggerAttrInfo.HasStepperBoundary = true; + break; } } @@ -472,6 +483,14 @@ public VarInfo[] GetLiveVarsAt(int offset) } public override string ToString() => "MethodInfo(" + Name + ")"; + + public class DebuggerAttributesInfo + { + public bool HasDebuggerHidden { get; internal set; } + public bool HasStepThrough { get; internal set; } + public bool HasNonUserCode { get; internal set; } + public bool HasStepperBoundary { get; internal set; } + } } internal class TypeInfo @@ -704,7 +723,7 @@ SourceFile FindSource(DocumentHandle doc, int rowid, string documentName) foreach (DocumentHandle dh in asmMetadataReader.Documents) { - var document = asmMetadataReader.GetDocument(dh); + asmMetadataReader.GetDocument(dh); } if (pdbMetadataReader != null) @@ -1030,7 +1049,7 @@ public IEnumerable EnC(AssemblyInfo asm, byte[] meta_data, byte[] pd public IEnumerable Add(SessionId id, string name, byte[] assembly_data, byte[] pdb_data, CancellationToken token) { - AssemblyInfo assembly = null; + AssemblyInfo assembly; try { assembly = new AssemblyInfo(monoProxy, id, name, assembly_data, pdb_data, token); diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsHelper.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsHelper.cs index e948c6abe0ebf..af1cead1c9593 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsHelper.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsHelper.cs @@ -86,7 +86,8 @@ public static bool TryParse(string id, out DotnetObjectId objectId) case "methodId": { parts = id.Split(":"); - objectId.SubValue = int.Parse(parts[3]); + if (parts.Length > 3) + objectId.SubValue = int.Parse(parts[3]); break; } } @@ -311,6 +312,8 @@ public ExecutionContext(MonoSDBHelper sdbAgent, int id, object auxData) public TaskCompletionSource ready; public bool IsRuntimeReady => ready != null && ready.Task.IsCompleted; public bool IsSkippingHiddenMethod { get; set; } + public bool IsSteppingThroughMethod { get; set; } + public bool IsResumedAfterBp { get; set; } public int ThreadId { get; set; } public int Id { get; set; } public object AuxData { get; set; } diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs index 7e8fe78eebd98..63e8025fc19ee 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DevToolsProxy.cs @@ -97,7 +97,6 @@ private void Send(WebSocket to, JObject o, CancellationToken token) { string sender = browser == to ? "Send-browser" : "Send-ide"; - string method = o["method"]?.ToString(); //if (method != "Debugger.scriptParsed" && method != "Runtime.consoleAPICalled") Log("protocol", $"{sender}: " + JsonConvert.SerializeObject(o)); byte[] bytes = Encoding.UTF8.GetBytes(o.ToString()); @@ -157,7 +156,6 @@ private void ProcessBrowserMessage(string msg, CancellationToken token) { var res = JObject.Parse(msg); - string method = res["method"]?.ToString(); //if (method != "Debugger.scriptParsed" && method != "Runtime.consoleAPICalled") Log("protocol", $"browser: {msg}"); diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MemberReferenceResolver.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MemberReferenceResolver.cs index bcef7dbed5272..b7df8863a1f1c 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MemberReferenceResolver.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MemberReferenceResolver.cs @@ -359,9 +359,8 @@ public async Task Resolve(ElementAccessExpressionSyntax elementAccess, } return null; } - catch (Exception ex) + catch (Exception) { - var e = ex; throw new Exception($"Unable to evaluate method '{elementAccess}'"); } } diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs index 6866feaf54c54..36d6289bf241c 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs @@ -26,6 +26,7 @@ internal class MonoProxy : DevToolsProxy private const string sPauseOnCaught = "pause_on_caught"; // index of the runtime in a same JS page/process public int RuntimeId { get; private init; } + public bool JustMyCode { get; private set; } public MonoProxy(ILoggerFactory loggerFactory, IList urlSymbolServerList, int runtimeId = 0) : base(loggerFactory) { @@ -573,10 +574,33 @@ protected override async Task AcceptCommand(MessageId id, string method, J return true; } } + case "DotnetDebugger.justMyCode": + { + try + { + SetJustMyCode(id, args, token); + } + catch (Exception) + { + SendResponse(id, + Result.Exception(new ArgumentException( + $"DotnetDebugger.justMyCode got incorrect argument ({args})")), + token); + } + return true; + } } return false; } + private void SetJustMyCode(MessageId id, JObject args, CancellationToken token) + { + var isEnabled = args["enabled"]?.Value(); + if (isEnabled == null) + throw new ArgumentException(); + JustMyCode = isEnabled.Value; + SendResponse(id, Result.OkFromObject(new { justMyCodeEnabled = JustMyCode }), token); + } private async Task CallOnFunction(MessageId id, JObject args, CancellationToken token) { var context = GetContext(id); @@ -813,24 +837,51 @@ private async Task SendCallStack(SessionId sessionId, ExecutionContext con DebugStore store = await LoadStore(sessionId, token); var method = await context.SdbAgent.GetMethodInfo(methodId, token); - if (context.IsSkippingHiddenMethod == true) + var shouldReturn = await SkipMethod( + isSkippable: context.IsSkippingHiddenMethod, + shouldBeSkipped: event_kind != EventKind.UserBreak, + StepKind.Over); + context.IsSkippingHiddenMethod = false; + if (shouldReturn) + return true; + + shouldReturn = await SkipMethod( + isSkippable: context.IsSteppingThroughMethod, + shouldBeSkipped: event_kind != EventKind.UserBreak && event_kind != EventKind.Breakpoint, + StepKind.Over); + context.IsSteppingThroughMethod = false; + if (shouldReturn) + return true; + + if (j == 0 && + (method?.Info.DebuggerAttrInfo.HasStepThrough == true || + method?.Info.DebuggerAttrInfo.HasDebuggerHidden == true || + method?.Info.DebuggerAttrInfo.HasStepperBoundary == true || + (method?.Info.DebuggerAttrInfo.HasNonUserCode == true && JustMyCode))) { - context.IsSkippingHiddenMethod = false; - if (event_kind != EventKind.UserBreak) + if (method.Info.DebuggerAttrInfo.HasDebuggerHidden || + (method.Info.DebuggerAttrInfo.HasStepperBoundary && event_kind == EventKind.Step)) { - await context.SdbAgent.Step(context.ThreadId, StepKind.Over, token); - await SendCommand(sessionId, "Debugger.resume", new JObject(), token); - return true; + if (event_kind == EventKind.Step) + context.IsSkippingHiddenMethod = true; + if (await SkipMethod(isSkippable: true, shouldBeSkipped: true, StepKind.Out)) + return true; + } + if (!method.Info.DebuggerAttrInfo.HasStepperBoundary) + { + if (event_kind == EventKind.Step || + (JustMyCode && (event_kind == EventKind.Breakpoint || event_kind == EventKind.UserBreak))) + { + if (context.IsResumedAfterBp) + context.IsResumedAfterBp = false; + else if (event_kind != EventKind.UserBreak) + context.IsSteppingThroughMethod = true; + if (await SkipMethod(isSkippable: true, shouldBeSkipped: true, StepKind.Out)) + return true; + } + if (event_kind == EventKind.Breakpoint) + context.IsResumedAfterBp = true; } - } - - if (j == 0 && method?.Info.IsHiddenFromDebugger == true) - { - if (event_kind == EventKind.Step) - context.IsSkippingHiddenMethod = true; - await context.SdbAgent.Step(context.ThreadId, StepKind.Out, token); - await SendCommand(sessionId, "Debugger.resume", new JObject(), token); - return true; } SourceLocation location = method?.Info.GetLocationByIl(il_pos); @@ -910,6 +961,17 @@ private async Task SendCallStack(SessionId sessionId, ExecutionContext con SendEvent(sessionId, "Debugger.paused", o, token); return true; + + async Task SkipMethod(bool isSkippable, bool shouldBeSkipped, StepKind stepKind) + { + if (isSkippable && shouldBeSkipped) + { + await context.SdbAgent.Step(context.ThreadId, stepKind, token); + await SendCommand(sessionId, "Debugger.resume", new JObject(), token); + return true; + } + return false; + } } private async Task OnReceiveDebuggerAgentEvent(SessionId sessionId, JObject args, CancellationToken token) { @@ -1258,18 +1320,17 @@ internal async Task LoadStore(SessionId sessionId, CancellationToken try { - string[] loaded_files = context.LoadedFiles; - + string[] loaded_files = await GetLoadedFiles(sessionId, context, token); if (loaded_files == null) { - Result loaded = await SendMonoCommand(sessionId, MonoCommands.GetLoadedFiles(RuntimeId), token); - loaded_files = loaded.Value?["result"]?["value"]?.ToObject(); + SendLog(sessionId, $"Failed to get the list of loaded files. Managed code debugging won't work due to this.", token); } - - await - foreach (SourceFile source in context.store.Load(sessionId, loaded_files, token).WithCancellation(token)) + else { - await OnSourceFileAdded(sessionId, source, context, token); + await foreach (SourceFile source in context.store.Load(sessionId, loaded_files, token).WithCancellation(token)) + { + await OnSourceFileAdded(sessionId, source, context, token); + } } } catch (Exception e) @@ -1280,6 +1341,24 @@ internal async Task LoadStore(SessionId sessionId, CancellationToken if (!context.Source.Task.IsCompleted) context.Source.SetResult(context.store); return context.store; + async Task GetLoadedFiles(SessionId sessionId, ExecutionContext context, CancellationToken token) + { + if (context.LoadedFiles != null) + return context.LoadedFiles; + + Result loaded = await SendMonoCommand(sessionId, MonoCommands.GetLoadedFiles(RuntimeId), token); + if (!loaded.IsOk) + { + SendLog(sessionId, $"Error on mono_wasm_get_loaded_files {loaded}", token); + return null; + } + + string[] files = loaded.Value?["result"]?["value"]?.ToObject(); + if (files == null) + SendLog(sessionId, $"Error extracting the list of loaded_files from the result of mono_wasm_get_loaded_files: {loaded}", token); + + return files; + } } private async Task RuntimeReady(SessionId sessionId, CancellationToken token) @@ -1371,7 +1450,7 @@ private async Task SetBreakpoint(SessionId sessionId, DebugStore store, Breakpoi { SourceLocation loc = sourceId.First(); req.Method = loc.IlLocation.Method; - if (req.Method.IsHiddenFromDebugger) + if (req.Method.DebuggerAttrInfo.HasDebuggerHidden) continue; Breakpoint bp = await SetMonoBreakpoint(sessionId, req.Id, loc, req.Condition, token); diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs index f613922e6caec..3b1dc557259b6 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs @@ -379,16 +379,14 @@ internal string GetArrayIndexString(int idx) { if (idx < 0 || idx >= TotalLength) return "Invalid Index"; - int boundLimit = 1; - int lastBoundLimit = 1; int[] arrayStr = new int[Rank]; int rankStart = 0; while (idx > 0) { - boundLimit = 1; + int boundLimit = 1; for (int i = Rank - 1; i >= rankStart; i--) { - lastBoundLimit = boundLimit; + int lastBoundLimit = boundLimit; boundLimit *= Bounds[i]; if (idx < boundLimit) { @@ -733,8 +731,7 @@ public void ResetStore(DebugStore store) public async Task GetAssemblyInfo(int assemblyId, CancellationToken token) { - AssemblyInfo asm = null; - if (assemblies.TryGetValue(assemblyId, out asm)) + if (assemblies.TryGetValue(assemblyId, out AssemblyInfo asm)) { return asm; } @@ -759,8 +756,7 @@ public async Task GetAssemblyInfo(int assemblyId, CancellationToke public async Task GetMethodInfo(int methodId, CancellationToken token) { - MethodInfoWithDebugInformation methodDebugInfo = null; - if (methods.TryGetValue(methodId, out methodDebugInfo)) + if (methods.TryGetValue(methodId, out MethodInfoWithDebugInformation methodDebugInfo)) { return methodDebugInfo; } @@ -803,14 +799,11 @@ public async Task GetMethodInfo(int methodId, Ca public async Task GetTypeInfo(int typeId, CancellationToken token) { - TypeInfoWithDebugInformation typeDebugInfo = null; - if (types.TryGetValue(typeId, out typeDebugInfo)) + if (types.TryGetValue(typeId, out TypeInfoWithDebugInformation typeDebugInfo)) { return typeDebugInfo; } - TypeInfo type = null; - var typeToken = await GetTypeToken(typeId, token); var typeName = await GetTypeName(typeId, token); var assemblyId = await GetAssemblyFromType(typeId, token); @@ -822,7 +815,7 @@ public async Task GetTypeInfo(int typeId, Cancella return null; } - asm.TypesByToken.TryGetValue(typeToken, out type); + asm.TypesByToken.TryGetValue(typeToken, out TypeInfo type); if (type == null) { @@ -1172,7 +1165,6 @@ public async Task ClearSingleStep(int req_id, CancellationToken token) public async Task GetFieldValue(int typeId, int fieldId, CancellationToken token) { - var ret = new List(); using var commandParamsWriter = new MonoBinaryWriter(); commandParamsWriter.Write(typeId); commandParamsWriter.Write(1); @@ -1184,7 +1176,6 @@ public async Task GetFieldValue(int typeId, int fieldId, CancellationTo public async Task TypeIsInitialized(int typeId, CancellationToken token) { - var ret = new List(); using var commandParamsWriter = new MonoBinaryWriter(); commandParamsWriter.Write(typeId); @@ -1194,7 +1185,6 @@ public async Task TypeIsInitialized(int typeId, CancellationToken token) public async Task TypeInitialize(int typeId, CancellationToken token) { - var ret = new List(); using var commandParamsWriter = new MonoBinaryWriter(); commandParamsWriter.Write(typeId); @@ -1473,7 +1463,6 @@ public async Task GetClassNameFromObject(int object_id, CancellationToke public async Task GetTypeIdFromToken(int assemblyId, int typeToken, CancellationToken token) { - var ret = new List(); using var commandParamsWriter = new MonoBinaryWriter(); commandParamsWriter.Write((int)assemblyId); commandParamsWriter.Write((int)typeToken); @@ -1483,7 +1472,6 @@ public async Task GetTypeIdFromToken(int assemblyId, int typeToken, Cancell public async Task GetMethodIdByName(int type_id, string method_name, CancellationToken token) { - var ret = new List(); using var commandParamsWriter = new MonoBinaryWriter(); commandParamsWriter.Write((int)type_id); commandParamsWriter.Write(method_name); @@ -1496,7 +1484,6 @@ public async Task GetMethodIdByName(int type_id, string method_name, Cancel public async Task IsDelegate(int objectId, CancellationToken token) { - var ret = new List(); using var commandParamsWriter = new MonoBinaryWriter(); commandParamsWriter.Write((int)objectId); using var retDebuggerCmdReader = await SendDebuggerAgentCommand(CmdObject.RefIsDelegate, commandParamsWriter, token); @@ -1505,7 +1492,6 @@ public async Task IsDelegate(int objectId, CancellationToken token) public async Task GetDelegateMethod(int objectId, CancellationToken token) { - var ret = new List(); using var commandParamsWriter = new MonoBinaryWriter(); commandParamsWriter.Write((int)objectId); using var retDebuggerCmdReader = await SendDebuggerAgentCommand(CmdObject.RefDelegateGetMethod, commandParamsWriter, token); @@ -1542,6 +1528,9 @@ public async Task InvokeMethod(ArraySegment valueTypeBuffer, int public async Task InvokeMethodInObject(int objectId, int methodId, string varName, CancellationToken token) { + valueTypes.TryGetValue(objectId, out var valueType); + if (valueType != null) + return await InvokeMethod(valueType.valueTypeBuffer, methodId, varName, token); using var commandParamsObjWriter = new MonoBinaryWriter(); commandParamsObjWriter.Write(ElementType.Class, objectId); return await InvokeMethod(commandParamsObjWriter.GetParameterBuffer(), methodId, varName, token); @@ -1569,7 +1558,7 @@ public async Task GetPropertyMethodIdByName(int typeId, string propertyName return -1; } - public async Task CreateJArrayForProperties(int typeId, ArraySegment object_buffer, JArray attributes, bool isAutoExpandable, string objectIdStr, bool isOwn, CancellationToken token) + public async Task CreateJArrayForProperties(int typeId, ElementType elementType, ArraySegment object_buffer, JArray attributes, bool isAutoExpandable, string objectIdStr, bool isOwn, CancellationToken token) { JArray ret = new JArray(); using var retDebuggerCmdReader = await GetTypePropertiesReader(typeId, token); @@ -1606,7 +1595,7 @@ public async Task CreateJArrayForProperties(int typeId, ArraySegment CreateJArrayForProperties(int typeId, ArraySegment GetPointerContent(int pointerId, CancellationToken token) { - var ret = new List(); using var commandParamsWriter = new MonoBinaryWriter(); commandParamsWriter.Write(pointerValues[pointerId].address); commandParamsWriter.Write(pointerValues[pointerId].typeId); @@ -1650,7 +1638,7 @@ public async Task GetPropertiesValuesOfValueType(int valueTypeId, Cancel } for (int i = 0 ; i < typesToGetProperties.Count; i++) { - var properties = await CreateJArrayForProperties(typesToGetProperties[i], valueType.valueTypeBuffer, valueType.valueTypeJson, valueType.valueTypeAutoExpand, $"dotnet:valuetype:{valueType.Id}", i == 0, token); + var properties = await CreateJArrayForProperties(typesToGetProperties[i], ElementType.ValueType, valueType.valueTypeBuffer, valueType.valueTypeJson, valueType.valueTypeAutoExpand, $"dotnet:valuetype:{valueType.Id}", i == 0, token); ret = new JArray(ret.Union(properties)); } @@ -1725,7 +1713,7 @@ public async Task CreateJObjectForPtr(ElementType etype, MonoBinaryRead string value; long valueAddress = retDebuggerCmdReader.ReadInt64(); var typeId = retDebuggerCmdReader.ReadInt32(); - var className = ""; + string className; if (etype == ElementType.FnPtr) className = "(*())"; //to keep the old behavior else @@ -1770,9 +1758,8 @@ public async Task CreateJObjectForArray(MonoBinaryReader retDebuggerCmd public async Task CreateJObjectForObject(MonoBinaryReader retDebuggerCmdReader, int typeIdFromAttribute, bool forDebuggerDisplayAttribute, CancellationToken token) { var objectId = retDebuggerCmdReader.ReadInt32(); - var className = ""; var type_id = await GetTypeIdFromObject(objectId, false, token); - className = await GetTypeName(type_id[0], token); + string className = await GetTypeName(type_id[0], token); string debuggerDisplayAttribute = null; if (!forDebuggerDisplayAttribute) debuggerDisplayAttribute = await GetValueFromDebuggerDisplayAttribute(objectId, type_id[0], token); @@ -1847,7 +1834,7 @@ public async Task CreateJObjectForValueType(MonoBinaryReader retDebugge public async Task CreateJObjectForNull(MonoBinaryReader retDebuggerCmdReader, CancellationToken token) { - string className = ""; + string className; ElementType variableType = (ElementType)retDebuggerCmdReader.ReadByte(); switch (variableType) { @@ -1863,9 +1850,9 @@ public async Task CreateJObjectForNull(MonoBinaryReader retDebuggerCmdR case ElementType.Array: { ElementType byte_type = (ElementType)retDebuggerCmdReader.ReadByte(); - var rank = retDebuggerCmdReader.ReadInt32(); + retDebuggerCmdReader.ReadInt32(); // rank if (byte_type == ElementType.Class) { - var internal_type_id = retDebuggerCmdReader.ReadInt32(); + retDebuggerCmdReader.ReadInt32(); // internal_type_id } var type_id = retDebuggerCmdReader.ReadInt32(); className = await GetTypeName(type_id, token); @@ -2375,6 +2362,7 @@ public async Task GetObjectValues(int objectId, GetObjectCommandOptions commandParamsObjWriter.WriteObj(new DotnetObjectId("object", objectId), this); var props = await CreateJArrayForProperties( typeId, + ElementType.Class, commandParamsObjWriter.GetParameterBuffer(), new JArray(objects.Values), getCommandType.HasFlag(GetObjectCommandOptions.ForDebuggerProxyAttribute), diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/BreakpointTests.cs b/src/mono/wasm/debugger/DebuggerTestSuite/BreakpointTests.cs index 2c24a924f557e..b8c58a27f1e5f 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/BreakpointTests.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/BreakpointTests.cs @@ -668,7 +668,7 @@ await EvaluateAndCheck( [Fact] - public async Task DebuggerAttributeNoStopInDebuggerHidden() + public async Task DebuggerHiddenNoStopOnBp() { var bp_hidden = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", "HiddenMethod", 1); var bp_visible = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", "VisibleMethod", 1); @@ -683,7 +683,7 @@ await EvaluateAndCheck( } [Fact] - public async Task DebuggerAttributeStopOnDebuggerHiddenCallWithDebuggerBreakCall() + public async Task DebuggerHiddenStopOnUserBp() { var bp_init = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", "RunDebuggerBreak", 0); var init_location = await EvaluateAndCheck( @@ -707,5 +707,254 @@ await SendCommandAndCheck(null, "Debugger.resume", 8, "VisibleMethodDebuggerBreak"); } + + [Theory] + [InlineData(false, "RunStepThrough")] + [InlineData(true, "RunStepThrough")] + [InlineData(true, "RunNonUserCode")] + [InlineData(false, "RunNonUserCode")] + public async Task StepThroughOrNonUserCodeAttributeStepInNoBp(bool justMyCodeEnabled, string evalFunName) + { + var bp_init = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", evalFunName, 1); + if (justMyCodeEnabled) + await SetJustMyCode(true); + + var init_location = await EvaluateAndCheck( + $"window.setTimeout(function() {{ invoke_static_method('[debugger-test] DebuggerAttribute:{evalFunName}'); }}, 1);", + "dotnet://debugger-test.dll/debugger-test.cs", + bp_init.Value["locations"][0]["lineNumber"].Value(), + bp_init.Value["locations"][0]["columnNumber"].Value(), + evalFunName + ); + var (funcName, line, col) = (evalFunName, 868, 8); + if (evalFunName == "RunNonUserCode") + (funcName, line, col) = justMyCodeEnabled ? (evalFunName, 888, 8) : ("NonUserCodeBp", 873, 4); + await SendCommandAndCheck(null, "Debugger.stepInto", "dotnet://debugger-test.dll/debugger-test.cs", line, col, funcName); + } + + [Theory] + [InlineData(false, "RunStepThrough", "StepThrougBp")] + [InlineData(true, "RunStepThrough", "StepThrougBp")] + [InlineData(true, "RunNonUserCode", "NonUserCodeBp")] + [InlineData(false, "RunNonUserCode", "NonUserCodeBp")] + public async Task StepThroughOrNonUserCodeAttributeStepInWithBp(bool justMyCodeEnabled, string evalFunName, string decoratedFunName) + { + var bp_init = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", evalFunName, 1); + var init_location = await EvaluateAndCheck( + $"window.setTimeout(function() {{ invoke_static_method('[debugger-test] DebuggerAttribute:{evalFunName}'); }}, 1);", + "dotnet://debugger-test.dll/debugger-test.cs", + bp_init.Value["locations"][0]["lineNumber"].Value(), + bp_init.Value["locations"][0]["columnNumber"].Value(), + evalFunName + ); + + if (justMyCodeEnabled) + { + await SetJustMyCode(true); + var line = (evalFunName == "RunNonUserCode") ? 888 : 868; + await SendCommandAndCheck(null, "Debugger.stepInto", "dotnet://debugger-test.dll/debugger-test.cs", line, 8, evalFunName); + } + else + { + var (finalFunName, line3, col) = (decoratedFunName, 873, 4); + if (evalFunName == "RunStepThrough") + { + var bp1_decorated_fun = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", decoratedFunName, 1); + var bp2_decorated_fun = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", decoratedFunName, 3); + (finalFunName, line3, col) = (evalFunName, 867, 8); + var line1 = bp1_decorated_fun.Value["locations"][0]["lineNumber"].Value(); + var line2 = bp2_decorated_fun.Value["locations"][0]["lineNumber"].Value(); + await SendCommandAndCheck(null, "Debugger.stepInto", "dotnet://debugger-test.dll/debugger-test.cs", line1, col, decoratedFunName); + await SendCommandAndCheck(null, "Debugger.stepInto", "dotnet://debugger-test.dll/debugger-test.cs", line2, col, decoratedFunName); + } + await SendCommandAndCheck(null, "Debugger.stepInto", "dotnet://debugger-test.dll/debugger-test.cs", line3, col, finalFunName); + } + } + + [Theory] + [InlineData(false, "RunStepThrough", "StepThrougBp")] + [InlineData(true, "RunStepThrough", "StepThrougBp")] + [InlineData(true, "RunNonUserCode", "NonUserCodeBp")] + [InlineData(false, "RunNonUserCode", "NonUserCodeBp")] + public async Task StepThroughOrNonUserCodeAttributeResumeWithBp(bool justMyCodeEnabled, string evalFunName, string decoratedFunName) + { + var bp_init = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", evalFunName, 1); + var init_location = await EvaluateAndCheck( + $"window.setTimeout(function() {{ invoke_static_method('[debugger-test] DebuggerAttribute:{evalFunName}'); }}, 1);", + "dotnet://debugger-test.dll/debugger-test.cs", + bp_init.Value["locations"][0]["lineNumber"].Value(), + bp_init.Value["locations"][0]["columnNumber"].Value(), + evalFunName + ); + + if (justMyCodeEnabled) + await SetJustMyCode(true); + else + { + var bp1_decorated_fun = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", decoratedFunName, 1); + var line1 = bp1_decorated_fun.Value["locations"][0]["lineNumber"].Value(); + await SendCommandAndCheck(null, "Debugger.resume", "dotnet://debugger-test.dll/debugger-test.cs", line1, 8, decoratedFunName); + } + var bp_outside_decorated_fun = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", evalFunName, 2); + var line2 = bp_outside_decorated_fun.Value["locations"][0]["lineNumber"].Value(); + await SendCommandAndCheck(null, "Debugger.resume", "dotnet://debugger-test.dll/debugger-test.cs", line2, 8, evalFunName); + } + + [Theory] + [InlineData(false, "Debugger.resume", "RunStepThrough", "StepThrougUserBp")] + [InlineData(false, "Debugger.stepInto", "RunStepThrough", "StepThrougUserBp")] + [InlineData(true, "Debugger.stepInto", "RunStepThrough", null)] + [InlineData(true, "Debugger.resume", "RunStepThrough", null)] + [InlineData(true, "Debugger.stepInto", "RunNonUserCode", null)] + [InlineData(true, "Debugger.resume", "RunNonUserCode", null)] + [InlineData(false, "Debugger.stepInto", "RunNonUserCode", "NonUserCodeUserBp")] + [InlineData(false, "Debugger.resume", "RunNonUserCode", "NonUserCodeUserBp")] + public async Task StepThroughOrNonUserCodAttributeWithUserBp(bool justMyCodeEnabled, string debuggingFunction, string evalFunName, string decoratedFunName) + { + var bp_init = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", evalFunName, 2); + var bp_outside_decorated_fun = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", evalFunName, 3); + + var init_location = await EvaluateAndCheck( + $"window.setTimeout(function() {{ invoke_static_method('[debugger-test] DebuggerAttribute:{evalFunName}'); }}, 1);", + "dotnet://debugger-test.dll/debugger-test.cs", + bp_init.Value["locations"][0]["lineNumber"].Value(), + bp_init.Value["locations"][0]["columnNumber"].Value(), + evalFunName + ); + + int line1, line2; + var (col1, col2) = (8, 4); + string function_name1, function_name2; + + if (justMyCodeEnabled) + { + await SetJustMyCode(true); + line1 = bp_outside_decorated_fun.Value["locations"][0]["lineNumber"].Value() - 1; + line2 = bp_outside_decorated_fun.Value["locations"][0]["lineNumber"].Value(); + function_name1 = function_name2 = evalFunName; + } + else + { + if (debuggingFunction == "Debugger.stepInto" && evalFunName == "RunNonUserCode") + { + (line1, col1) = (881, 4); + (line2, col2) = (882, 8); + function_name1 = function_name2 = decoratedFunName; + } + else + { + line1 = evalFunName == "RunNonUserCode" ? 882 : 862; + function_name1 = decoratedFunName; + line2 = bp_outside_decorated_fun.Value["locations"][0]["lineNumber"].Value(); + function_name2 = evalFunName; + } + } + await SendCommandAndCheck(null, debuggingFunction, "dotnet://debugger-test.dll/debugger-test.cs", line1, col1, function_name1); + await SendCommandAndCheck(null, debuggingFunction, "dotnet://debugger-test.dll/debugger-test.cs", line2, col2, function_name2); + } + + [Theory] + [InlineData("Debugger.stepInto", 1, 2, false)] + [InlineData("Debugger.stepInto", 1, 2, true)] + [InlineData("Debugger.resume", 1, 2, true)] + [InlineData("Debugger.stepInto", 2, 3, false)] + [InlineData("Debugger.resume", 2, 3, false)] + public async Task StepperBoundary(string debuggingAction, int lineBpInit, int lineBpFinal, bool hasBpInDecoratedFun) + { + // behavior of StepperBoundary is the same for JMC enabled and disabled + // but the effect of NonUserCode escape is better visible for JMC: enabled + await SetJustMyCode(true); + var bp_init = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", "RunNoBoundary", lineBpInit); + var init_location = await EvaluateAndCheck( + $"window.setTimeout(function() {{ invoke_static_method('[debugger-test] DebuggerAttribute:RunNoBoundary'); }}, {lineBpInit});", + "dotnet://debugger-test.dll/debugger-test.cs", + bp_init.Value["locations"][0]["lineNumber"].Value(), + bp_init.Value["locations"][0]["columnNumber"].Value(), + "RunNoBoundary" + ); + var bp_final = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", "RunNoBoundary", lineBpFinal); + if (hasBpInDecoratedFun) + { + var bp_decorated_fun = await SetBreakpointInMethod("debugger-test.dll", "DebuggerAttribute", "BoundaryBp", 2); + var line_decorated_fun = bp_decorated_fun.Value["locations"][0]["lineNumber"].Value(); + var col_decorated_fun = bp_decorated_fun.Value["locations"][0]["columnNumber"].Value(); + await SendCommandAndCheck(null, debuggingAction, "dotnet://debugger-test.dll/debugger-test.cs", line_decorated_fun, col_decorated_fun, "BoundaryBp"); + } + if (lineBpInit == 2) + await SendCommandAndCheck(null, debuggingAction, "dotnet://debugger-test.dll/debugger-test.cs", 900, 8, "BoundaryUserBp"); + + var line = bp_final.Value["locations"][0]["lineNumber"].Value(); + var col = bp_final.Value["locations"][0]["columnNumber"].Value(); + await SendCommandAndCheck(null, debuggingAction, "dotnet://debugger-test.dll/debugger-test.cs", line, col, "RunNoBoundary"); + } + + [Fact] + public async Task CreateGoodBreakpointAndHitGoToWasmPageWithoutAssetsComeBackAndHitAgain() + { + var bp = await SetBreakpoint("dotnet://debugger-test.dll/debugger-test.cs", 10, 8); + var pause_location = await EvaluateAndCheck( + "window.setTimeout(function() { invoke_add(); }, 1);", + "dotnet://debugger-test.dll/debugger-test.cs", 10, 8, + "IntAdd"); + Assert.Equal("other", pause_location["reason"]?.Value()); + Assert.Equal(bp.Value["breakpointId"]?.ToString(), pause_location["hitBreakpoints"]?[0]?.Value()); + + var top_frame = pause_location["callFrames"][0]; + Assert.Equal("IntAdd", top_frame["functionName"].Value()); + Assert.Contains("debugger-test.cs", top_frame["url"].Value()); + + CheckLocation("dotnet://debugger-test.dll/debugger-test.cs", 8, 4, scripts, top_frame["functionLocation"]); + + //now check the scope + var scope = top_frame["scopeChain"][0]; + Assert.Equal("local", scope["type"]); + Assert.Equal("IntAdd", scope["name"]); + + Assert.Equal("object", scope["object"]["type"]); + CheckLocation("dotnet://debugger-test.dll/debugger-test.cs", 8, 4, scripts, scope["startLocation"]); + CheckLocation("dotnet://debugger-test.dll/debugger-test.cs", 14, 4, scripts, scope["endLocation"]); + + await cli.SendCommand("Debugger.resume", null, token); + + var run_method = JObject.FromObject(new + { + expression = "window.setTimeout(function() { load_wasm_page_without_assets(); }, 1);" + }); + await cli.SendCommand("Runtime.evaluate", run_method, token); + await Task.Delay(1000, token); + run_method = JObject.FromObject(new + { + expression = "window.setTimeout(function() { reload_wasm_page(); }, 1);" + }); + await cli.SendCommand("Runtime.evaluate", run_method, token); + await Task.Delay(1000, token); + await insp.WaitFor(Inspector.READY); + await EvaluateAndCheck( + "window.setTimeout(function() { invoke_add(); }, 1);", + "dotnet://debugger-test.dll/debugger-test.cs", 10, 8, + "IntAdd", + wait_for_event_fn: async (pause_location) => + { + Assert.Equal("other", pause_location["reason"]?.Value()); + Assert.Equal(bp.Value["breakpointId"]?.ToString(), pause_location["hitBreakpoints"]?[0]?.Value()); + + var top_frame = pause_location["callFrames"][0]; + Assert.Equal("IntAdd", top_frame["functionName"].Value()); + Assert.Contains("debugger-test.cs", top_frame["url"].Value()); + + CheckLocation("dotnet://debugger-test.dll/debugger-test.cs", 8, 4, scripts, top_frame["functionLocation"]); + + //now check the scope + var scope = top_frame["scopeChain"][0]; + Assert.Equal("local", scope["type"]); + Assert.Equal("IntAdd", scope["name"]); + + Assert.Equal("object", scope["object"]["type"]); + CheckLocation("dotnet://debugger-test.dll/debugger-test.cs", 8, 4, scripts, scope["startLocation"]); + CheckLocation("dotnet://debugger-test.dll/debugger-test.cs", 14, 4, scripts, scope["endLocation"]); + await Task.CompletedTask; + } + ); + } } } diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs index 5660e8c55011b..d49a2331e2a11 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/DebuggerTestBase.cs @@ -1237,6 +1237,14 @@ internal async Task LoadAssemblyAndTestHotReload(string asm_file, strin await cli.SendCommand("Runtime.evaluate", run_method, token); return await insp.WaitFor(Inspector.PAUSE); } + + internal async Task SetJustMyCode(bool enabled) + { + var req = JObject.FromObject(new { enabled = enabled }); + var res = await cli.SendCommand("DotnetDebugger.justMyCode", req, token); + Assert.True(res.IsOk); + Assert.Equal(res.Value["justMyCodeEnabled"], enabled); + } } class DotnetObjectId diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs b/src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs index 0b199cfc6183e..c38596af1e5c6 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/EvaluateOnCallFrameTests.cs @@ -1016,6 +1016,28 @@ public async Task EvaluateProtectionLevels() => await CheckInspectLocalsAtBreak Assert.Equal(internalAndProtected[1]["value"]["value"], "protected"); Assert.Equal(priv[0]["value"]["value"], "private"); }); + + [Fact] + public async Task StructureGetters() => await CheckInspectLocalsAtBreakpointSite( + "DebuggerTests.StructureGetters", "Evaluate", 2, "Evaluate", + "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.StructureGetters:Evaluate'); })", + wait_for_event_fn: async (pause_location) => + { + var id = pause_location["callFrames"][0]["callFrameId"].Value(); + var (obj, _) = await EvaluateOnCallFrame(id, "s"); + var props = await GetProperties(obj["objectId"]?.Value()); + + await CheckProps(props, new + { + Id = TGetter("Id", TNumber(123)) + }, "s#1"); + + var getter = props.FirstOrDefault(p => p["name"]?.Value() == "Id"); + Assert.NotNull(getter); + var getterId = getter["get"]["objectId"]?.Value(); + var getterProps = await GetProperties(getterId); + Assert.Equal(getterProps[0]?["value"]?["value"]?.Value(), 123); + }); } } diff --git a/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs b/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs index bb61841cdd1f7..76f79a663f6e9 100644 --- a/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs +++ b/src/mono/wasm/debugger/DebuggerTestSuite/MiscTests.cs @@ -913,7 +913,7 @@ public async Task InspectLocalsUsingClassFromLibraryUsingDebugTypeFull() await EvaluateAndCheck( "window.setTimeout(function() {" + expression + "; }, 1);", - "dotnet://debugger-test.dll/debugger-test.cs", 860, 8, + "dotnet://debugger-test.dll/debugger-test.cs", 924, 8, "CallToEvaluateLocal", wait_for_event_fn: async (pause_location) => { diff --git a/src/mono/wasm/debugger/tests/debugger-test/debugger-driver.html b/src/mono/wasm/debugger/tests/debugger-test/debugger-driver.html index a141d677744e3..e9c1ec673b246 100644 --- a/src/mono/wasm/debugger/tests/debugger-test/debugger-driver.html +++ b/src/mono/wasm/debugger/tests/debugger-test/debugger-driver.html @@ -82,11 +82,14 @@ function invoke_add_with_parms (a, b) { return App.int_add (a, b); } - function load_non_wasm_page () { console.log("load_non_wasm_page") window.location.replace("http://localhost:9400/non-wasm-page.html"); } + function load_wasm_page_without_assets () { + console.log("load_wasm_page_without_assets") + window.location.replace("http://localhost:9400/wasm-page-without-assets.html"); + } diff --git a/src/mono/wasm/debugger/tests/debugger-test/debugger-evaluate-test.cs b/src/mono/wasm/debugger/tests/debugger-test/debugger-evaluate-test.cs index 1eac05cf41c1c..aa6572af2c23b 100644 --- a/src/mono/wasm/debugger/tests/debugger-test/debugger-evaluate-test.cs +++ b/src/mono/wasm/debugger/tests/debugger-test/debugger-evaluate-test.cs @@ -838,6 +838,19 @@ public static void Evaluate() var testClass = new TestClass(); } } + + public static class StructureGetters + { + public struct Point + { + public int Id { get { return 123; } } + } + + public static void Evaluate() + { + var s = new Point(); + } + } } namespace DebuggerTestsV2 diff --git a/src/mono/wasm/debugger/tests/debugger-test/debugger-test.cs b/src/mono/wasm/debugger/tests/debugger-test/debugger-test.cs index 98b9cb00dc401..3ecd2869fa210 100644 --- a/src/mono/wasm/debugger/tests/debugger-test/debugger-test.cs +++ b/src/mono/wasm/debugger/tests/debugger-test/debugger-test.cs @@ -848,6 +848,70 @@ public static void RunDebuggerBreak() HiddenMethodDebuggerBreak(); VisibleMethodDebuggerBreak(); } + + [System.Diagnostics.DebuggerStepThroughAttribute] + public static void StepThrougBp() + { + var a = 0; + currentCount++; + var b = 1; + } + + [System.Diagnostics.DebuggerStepThroughAttribute] + public static void StepThrougUserBp() + { + System.Diagnostics.Debugger.Break(); + } + + public static void RunStepThrough() + { + StepThrougBp(); + StepThrougUserBp(); + } + + [System.Diagnostics.DebuggerNonUserCode] + public static void NonUserCodeBp(Action boundaryTestFun=null) + { + var a = 0; + currentCount++; + var b = 1; + } + + [System.Diagnostics.DebuggerNonUserCode] + public static void NonUserCodeUserBp() + { + System.Diagnostics.Debugger.Break(); + } + + public static void RunNonUserCode() + { + NonUserCodeBp(); + NonUserCodeUserBp(); + } + + [System.Diagnostics.DebuggerStepperBoundary] + public static void BoundaryBp() + { + var a = 5; + } + + [System.Diagnostics.DebuggerStepperBoundary] + public static void BoundaryUserBp() + { + System.Diagnostics.Debugger.Break(); + } + + [System.Diagnostics.DebuggerNonUserCode] + public static void NonUserCodeForBoundaryEscape(Action boundaryTestFun) + { + boundaryTestFun(); + } + + public static void RunNoBoundary() + { + NonUserCodeForBoundaryEscape(DebuggerAttribute.BoundaryBp); + NonUserCodeForBoundaryEscape(DebuggerAttribute.BoundaryUserBp); + } } public class DebugTypeFull diff --git a/src/mono/wasm/debugger/tests/debugger-test/debugger-test.csproj b/src/mono/wasm/debugger/tests/debugger-test/debugger-test.csproj index d68825274d05b..c431aa7821ea6 100644 --- a/src/mono/wasm/debugger/tests/debugger-test/debugger-test.csproj +++ b/src/mono/wasm/debugger/tests/debugger-test/debugger-test.csproj @@ -12,6 +12,7 @@ + diff --git a/src/mono/wasm/debugger/tests/debugger-test/wasm-page-without-assets.html b/src/mono/wasm/debugger/tests/debugger-test/wasm-page-without-assets.html new file mode 100644 index 0000000000000..6d66e182a5993 --- /dev/null +++ b/src/mono/wasm/debugger/tests/debugger-test/wasm-page-without-assets.html @@ -0,0 +1,21 @@ + + + + + + + + + + Stuff goes here + + diff --git a/src/mono/wasm/runtime/cjs/dotnet.cjs.lib.js b/src/mono/wasm/runtime/cjs/dotnet.cjs.lib.js index 636d97487fc79..a2add7ec2fd68 100644 --- a/src/mono/wasm/runtime/cjs/dotnet.cjs.lib.js +++ b/src/mono/wasm/runtime/cjs/dotnet.cjs.lib.js @@ -7,21 +7,17 @@ const DotnetSupportLib = { $DOTNET: {}, // these lines will be placed early on emscripten runtime creation, passing import and export objects into __dotnet_runtime IFFE + // we replace implementation of readAsync and fetch + // replacement of require is there for consistency with ES6 code $DOTNET__postset: ` -let __dotnet_replacements = {scriptDirectory, readAsync, fetch: globalThis.fetch, require}; +let __dotnet_replacements = {readAsync, fetch: globalThis.fetch, require}; let __dotnet_exportedAPI = __dotnet_runtime.__initializeImportsAndExports( - { isES6:false, isGlobal:ENVIRONMENT_IS_GLOBAL, isNode:ENVIRONMENT_IS_NODE, isShell:ENVIRONMENT_IS_SHELL, isWeb:ENVIRONMENT_IS_WEB, locateFile, quit_ }, + { isESM:false, isGlobal:ENVIRONMENT_IS_GLOBAL, isNode:ENVIRONMENT_IS_NODE, isShell:ENVIRONMENT_IS_SHELL, isWeb:ENVIRONMENT_IS_WEB, locateFile, quit_, requirePromise:Promise.resolve(require)}, { mono:MONO, binding:BINDING, internal:INTERNAL, module:Module }, __dotnet_replacements); - -// here we replace things which are not exposed in another way -scriptDirectory = __dotnet_replacements.scriptDirectory; readAsync = __dotnet_replacements.readAsync; var fetch = __dotnet_replacements.fetch; -if (ENVIRONMENT_IS_NODE) { - __dirname = __dotnet_replacements.scriptDirectory; - require = __dotnet_replacements.require; -} +require = __dotnet_replacements.requireOut; `, }; diff --git a/src/mono/wasm/runtime/cs-to-js.ts b/src/mono/wasm/runtime/cs-to-js.ts index 2a7646d85973f..de208efe3c93b 100644 --- a/src/mono/wasm/runtime/cs-to-js.ts +++ b/src/mono/wasm/runtime/cs-to-js.ts @@ -3,7 +3,7 @@ import { mono_wasm_new_root, WasmRoot } from "./roots"; import { - GCHandle, JSHandleDisposed, MonoArray, + GCHandle, JSHandleDisposed, MarshalError, MarshalType, MonoArray, MonoArrayNull, MonoObject, MonoObjectNull, MonoString, MonoType, MonoTypeNull } from "./types"; @@ -18,49 +18,6 @@ import { _are_promises_supported, _create_cancelable_promise } from "./cancelabl import { getU32, getI32, getF32, getF64 } from "./memory"; import { Int32Ptr, VoidPtr } from "./types/emscripten"; -// see src/mono/wasm/driver.c MARSHAL_TYPE_xxx and Runtime.cs MarshalType -export enum MarshalType { - NULL = 0, - INT = 1, - FP64 = 2, - STRING = 3, - VT = 4, - DELEGATE = 5, - TASK = 6, - OBJECT = 7, - BOOL = 8, - ENUM = 9, - URI = 22, - SAFEHANDLE = 23, - ARRAY_BYTE = 10, - ARRAY_UBYTE = 11, - ARRAY_UBYTE_C = 12, - ARRAY_SHORT = 13, - ARRAY_USHORT = 14, - ARRAY_INT = 15, - ARRAY_UINT = 16, - ARRAY_FLOAT = 17, - ARRAY_DOUBLE = 18, - FP32 = 24, - UINT32 = 25, - INT64 = 26, - UINT64 = 27, - CHAR = 28, - STRING_INTERNED = 29, - VOID = 30, - ENUM64 = 31, - POINTER = 32 -} - -// see src/mono/wasm/driver.c MARSHAL_ERROR_xxx and Runtime.cs -export enum MarshalError { - BUFFER_TOO_SMALL = 512, - NULL_CLASS_POINTER = 513, - NULL_TYPE_POINTER = 514, - UNSUPPORTED_TYPE = 515, - FIRST = BUFFER_TOO_SMALL -} - const delegate_invoke_symbol = Symbol.for("wasm delegate_invoke"); const delegate_invoke_signature_symbol = Symbol.for("wasm delegate_invoke_signature"); diff --git a/src/mono/wasm/runtime/cwraps.ts b/src/mono/wasm/runtime/cwraps.ts index 98dd8f8e4e9bb..fab4a0e264549 100644 --- a/src/mono/wasm/runtime/cwraps.ts +++ b/src/mono/wasm/runtime/cwraps.ts @@ -97,7 +97,7 @@ export interface t_Cwraps { mono_wasm_find_corlib_type(namespace: string, name: string): MonoType; mono_wasm_assembly_find_type(assembly: MonoAssembly, namespace: string, name: string): MonoType; mono_wasm_assembly_find_method(klass: MonoClass, name: string, args: number): MonoMethod; - mono_wasm_invoke_method(method: MonoMethod, this_arg: MonoObject, params: VoidPtr, out_exc: MonoObject): MonoObject; + mono_wasm_invoke_method(method: MonoMethod, this_arg: MonoObject, params: VoidPtr, out_exc: VoidPtr): MonoObject; mono_wasm_string_get_utf8(str: MonoString): CharPtr; mono_wasm_string_from_utf16(str: CharPtr, len: number): MonoString; mono_wasm_get_obj_type(str: MonoObject): number; diff --git a/src/mono/wasm/runtime/debug.ts b/src/mono/wasm/runtime/debug.ts index 8eb60b46e5478..2aa8f121a55b8 100644 --- a/src/mono/wasm/runtime/debug.ts +++ b/src/mono/wasm/runtime/debug.ts @@ -179,7 +179,7 @@ export function mono_wasm_call_function_on(request: CallRequest): CFOResponse { const fn_args = request.arguments != undefined ? request.arguments.map(a => JSON.stringify(a.value)) : []; - const fn_body_template = `var fn = ${request.functionDeclaration}; return fn.apply(proxy, [${fn_args}]);`; + const fn_body_template = `const fn = ${request.functionDeclaration}; return fn.apply(proxy, [${fn_args}]);`; const fn_defn = new Function("proxy", fn_body_template); const fn_res = fn_defn(proxy); diff --git a/src/mono/wasm/runtime/dotnet.d.ts b/src/mono/wasm/runtime/dotnet.d.ts index 0baceaec3c1a3..6d210e51ad7cc 100644 --- a/src/mono/wasm/runtime/dotnet.d.ts +++ b/src/mono/wasm/runtime/dotnet.d.ts @@ -100,10 +100,7 @@ declare class WasmRootBuffer { release(): void; toString(): string; } -declare class WasmRoot { - private __buffer; - private __index; - constructor(buffer: WasmRootBuffer, index: number); +interface WasmRoot { get_address(): NativePointer; get_address_32(): number; get(): T; @@ -155,6 +152,7 @@ declare type AssetEntry = { culture?: string; load_remote?: boolean; is_optional?: boolean; + buffer?: ArrayBuffer; }; interface AssemblyEntry extends AssetEntry { name: "assembly"; @@ -195,8 +193,7 @@ declare type DotnetModuleConfig = { disableDotnet6Compatibility?: boolean; config?: MonoConfig | MonoConfigError; configSrc?: string; - scriptDirectory?: string; - onConfigLoaded?: () => void; + onConfigLoaded?: (config: MonoConfig) => Promise; onDotnetReady?: () => void; imports?: DotnetModuleConfigImports; } & Partial; @@ -253,12 +250,13 @@ declare function mono_call_assembly_entry_point(assembly: string, args?: any[], declare function mono_wasm_load_bytes_into_heap(bytes: Uint8Array): VoidPtr; declare type _MemOffset = number | VoidPtr | NativePointer; +declare type _NumberOrPointer = number | VoidPtr | NativePointer | ManagedPointer; declare function setU8(offset: _MemOffset, value: number): void; declare function setU16(offset: _MemOffset, value: number): void; -declare function setU32(offset: _MemOffset, value: number): void; +declare function setU32(offset: _MemOffset, value: _NumberOrPointer): void; declare function setI8(offset: _MemOffset, value: number): void; declare function setI16(offset: _MemOffset, value: number): void; -declare function setI32(offset: _MemOffset, value: number): void; +declare function setI32(offset: _MemOffset, value: _NumberOrPointer): void; declare function setI64(offset: _MemOffset, value: number): void; declare function setF32(offset: _MemOffset, value: number): void; declare function setF64(offset: _MemOffset, value: number): void; diff --git a/src/mono/wasm/runtime/driver.c b/src/mono/wasm/runtime/driver.c index dbe9800b9f12d..a84d1d9b0ec04 100644 --- a/src/mono/wasm/runtime/driver.c +++ b/src/mono/wasm/runtime/driver.c @@ -575,7 +575,7 @@ mono_wasm_assembly_load (const char *name) return res; } -EMSCRIPTEN_KEEPALIVE MonoAssembly* +EMSCRIPTEN_KEEPALIVE MonoAssembly* mono_wasm_get_corlib () { return mono_image_get_assembly (mono_get_corlib()); @@ -656,7 +656,7 @@ mono_wasm_assembly_get_entry_point (MonoAssembly *assembly) uint32_t entry = mono_image_get_entry_point (image); if (!entry) return NULL; - + mono_domain_ensure_entry_assembly (root_domain, assembly); method = mono_get_method (image, entry, NULL); @@ -784,7 +784,8 @@ mono_wasm_marshal_type_from_mono_type (int mono_type, MonoClass *klass, MonoType return MARSHAL_TYPE_VOID; case MONO_TYPE_BOOLEAN: return MARSHAL_TYPE_BOOL; - case MONO_TYPE_I: // IntPtr + case MONO_TYPE_I: // IntPtr + case MONO_TYPE_U: // UIntPtr case MONO_TYPE_PTR: return MARSHAL_TYPE_POINTER; case MONO_TYPE_I1: @@ -929,7 +930,7 @@ mono_wasm_try_unbox_primitive_and_get_type (MonoObject *obj, void *result, int r MonoType *type = mono_class_get_type (klass), *original_type = type; if (!type) return MARSHAL_ERROR_NULL_TYPE_POINTER; - + if ((klass == mono_get_string_class ()) && mono_string_instance_is_interned ((MonoString *)obj)) { *resultL = 0; @@ -939,14 +940,14 @@ mono_wasm_try_unbox_primitive_and_get_type (MonoObject *obj, void *result, int r if (mono_class_is_enum (klass)) type = mono_type_get_underlying_type (type); - + if (!type) return MARSHAL_ERROR_NULL_TYPE_POINTER; - + int mono_type = mono_type_get_type (type); - + if (mono_type == MONO_TYPE_GENERICINST) { - // HACK: While the 'any other type' fallback is valid for classes, it will do the + // HACK: While the 'any other type' fallback is valid for classes, it will do the // wrong thing for structs, so we need to make sure the valuetype handler is used if (mono_type_generic_inst_is_valuetype (type)) mono_type = MONO_TYPE_VALUETYPE; @@ -994,7 +995,7 @@ mono_wasm_try_unbox_primitive_and_get_type (MonoObject *obj, void *result, int r break; case MONO_TYPE_VALUETYPE: { - int obj_size = mono_object_get_size (obj), + int obj_size = mono_object_get_size (obj), required_size = (sizeof (int)) + (sizeof (MonoType *)) + obj_size; // Check whether this struct has special-case marshaling @@ -1104,7 +1105,7 @@ mono_wasm_enable_on_demand_gc (int enable) } EMSCRIPTEN_KEEPALIVE MonoString * -mono_wasm_intern_string (MonoString *string) +mono_wasm_intern_string (MonoString *string) { return mono_string_intern (string); } @@ -1156,12 +1157,12 @@ mono_wasm_unbox_rooted (MonoObject *obj) return mono_object_unbox (obj); } -EMSCRIPTEN_KEEPALIVE char * +EMSCRIPTEN_KEEPALIVE char * mono_wasm_get_type_name (MonoType * typePtr) { return mono_type_get_name_full (typePtr, MONO_TYPE_NAME_FORMAT_REFLECTION); } -EMSCRIPTEN_KEEPALIVE char * +EMSCRIPTEN_KEEPALIVE char * mono_wasm_get_type_aqn (MonoType * typePtr) { return mono_type_get_name_full (typePtr, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED); } diff --git a/src/mono/wasm/runtime/es6/dotnet.es6.lib.js b/src/mono/wasm/runtime/es6/dotnet.es6.lib.js index fe2b969606179..36f5b106a1f4f 100644 --- a/src/mono/wasm/runtime/es6/dotnet.es6.lib.js +++ b/src/mono/wasm/runtime/es6/dotnet.es6.lib.js @@ -7,22 +7,23 @@ const DotnetSupportLib = { $DOTNET: {}, // this line will be placed early on emscripten runtime creation, passing import and export objects into __dotnet_runtime IFFE + // Emscripten uses require function for nodeJS even in ES6 module. We need https://nodejs.org/api/module.html#modulecreaterequirefilename + // We use dynamic import because there is no "module" module in the browser. + // This is async init of it, note it would become available only after first tick. + // Also fix of scriptDirectory would be delayed + // Emscripten's getBinaryPromise is not async for NodeJs, but we would like to have it async, so we replace it. + // We also replace implementation of readAsync and fetch $DOTNET__postset: ` -let __dotnet_replacements = {scriptDirectory, readAsync, fetch: globalThis.fetch, require}; -let __dotnet_exportedAPI = __dotnet_runtime.__initializeImportsAndExports( - { isES6:true, isGlobal:false, isNode:ENVIRONMENT_IS_NODE, isShell:ENVIRONMENT_IS_SHELL, isWeb:ENVIRONMENT_IS_WEB, locateFile, quit_ }, - { mono:MONO, binding:BINDING, internal:INTERNAL, module:Module }, - __dotnet_replacements); - -// here we replace things which are not exposed in another way -scriptDirectory = __dotnet_replacements.scriptDirectory; -readAsync = __dotnet_replacements.readAsync; -var fetch = __dotnet_replacements.fetch; - -// here we replace things which are broken on NodeJS for ES6 +let __dotnet_replacements = {readAsync, fetch: globalThis.fetch, require}; if (ENVIRONMENT_IS_NODE) { - __dirname = __dotnet_replacements.scriptDirectory; - require = __dotnet_replacements.require; + __dotnet_replacements.requirePromise = import('module').then(mod => { + const require = mod.createRequire(import.meta.url); + const path = require('path'); + const url = require('url'); + __dotnet_replacements.require = require; + __dirname = scriptDirectory = path.dirname(url.fileURLToPath(import.meta.url)) + '/'; + return require; + }); getBinaryPromise = async () => { if (!wasmBinary) { try { @@ -46,7 +47,15 @@ if (ENVIRONMENT_IS_NODE) { } return getBinary(wasmBinaryFile); } -}`, +} +let __dotnet_exportedAPI = __dotnet_runtime.__initializeImportsAndExports( + { isESM:true, isGlobal:false, isNode:ENVIRONMENT_IS_NODE, isShell:ENVIRONMENT_IS_SHELL, isWeb:ENVIRONMENT_IS_WEB, locateFile, quit_, requirePromise:__dotnet_replacements.requirePromise }, + { mono:MONO, binding:BINDING, internal:INTERNAL, module:Module }, + __dotnet_replacements); +readAsync = __dotnet_replacements.readAsync; +var fetch = __dotnet_replacements.fetch; +require = __dotnet_replacements.requireOut; +`, }; // the methods would be visible to EMCC linker diff --git a/src/mono/wasm/runtime/exports.ts b/src/mono/wasm/runtime/exports.ts index d960519e9b072..7942377aa411f 100644 --- a/src/mono/wasm/runtime/exports.ts +++ b/src/mono/wasm/runtime/exports.ts @@ -31,9 +31,7 @@ import { mono_load_runtime_and_bcl_args, mono_wasm_load_config, mono_wasm_setenv, mono_wasm_set_runtime_options, mono_wasm_load_data_archive, mono_wasm_asm_loaded, - mono_wasm_pre_init, - mono_wasm_runtime_is_initialized, - mono_wasm_on_runtime_initialized + configure_emscripten_startup } from "./startup"; import { mono_set_timeout, schedule_background_exec } from "./scheduling"; import { mono_wasm_load_icu_data, mono_wasm_get_icudt_name } from "./icu"; @@ -66,7 +64,7 @@ import { import { create_weak_ref } from "./weak-ref"; import { fetch_like, readAsync_like } from "./polyfills"; import { EmscriptenModule } from "./types/emscripten"; -import { mono_on_abort, mono_run_main, mono_run_main_and_exit } from "./run"; +import { mono_run_main, mono_run_main_and_exit } from "./run"; const MONO = { // current "public" MONO API @@ -133,9 +131,9 @@ let exportedAPI: DotnetPublicAPI; // it exports methods to global objects MONO, BINDING and Module in backward compatible way // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function initializeImportsAndExports( - imports: { isES6: boolean, isGlobal: boolean, isNode: boolean, isShell: boolean, isWeb: boolean, locateFile: Function, quit_: Function }, + imports: { isESM: boolean, isGlobal: boolean, isNode: boolean, isShell: boolean, isWeb: boolean, locateFile: Function, quit_: Function, requirePromise: Promise }, exports: { mono: any, binding: any, internal: any, module: any }, - replacements: { scriptDirectory: any, fetch: any, readAsync: any, require: any }, + replacements: { fetch: any, readAsync: any, require: any, requireOut: any }, ): DotnetPublicAPI { const module = exports.module as DotnetModule; const globalThisAny = globalThis as any; @@ -163,18 +161,6 @@ function initializeImportsAndExports( module.configSrc = "./mono-config.json"; } - // these could be overriden on DotnetModuleConfig - if (!module.preInit) { - module.preInit = []; - } else if (typeof module.preInit === "function") { - module.preInit = [module.preInit]; - } - if (!module.preRun) { - module.preRun = []; - } else if (typeof module.preRun === "function") { - module.preRun = [module.preRun]; - } - if (!module.print) { module.print = console.log.bind(console); } @@ -183,15 +169,15 @@ function initializeImportsAndExports( } module.imports = module.imports || {}; if (!module.imports.require) { - const originalRequire = replacements.require; module.imports.require = (name) => { - const resolve = (module.imports)[name]; - if (!resolve && originalRequire) { - return originalRequire(name); + const resolved = (module.imports)[name]; + if (resolved) { + return resolved; } - if (!resolve) - throw new Error(`Please provide Module.imports.${name} or Module.imports.require`); - return resolve; + if (replacements.require) { + return replacements.require(name); + } + throw new Error(`Please provide Module.imports.${name} or Module.imports.require`); }; } @@ -201,15 +187,12 @@ function initializeImportsAndExports( else { runtimeHelpers.fetch = fetch_like; } - if (module.scriptDirectory) { - replacements.scriptDirectory = module.scriptDirectory; - } replacements.fetch = runtimeHelpers.fetch; replacements.readAsync = readAsync_like; - replacements.require = module.imports.require; + replacements.requireOut = module.imports.require; if (typeof module.disableDotnet6Compatibility === "undefined") { - module.disableDotnet6Compatibility = imports.isES6; + module.disableDotnet6Compatibility = imports.isESM; } // here we expose objects global namespace for tests and backward compatibility if (imports.isGlobal || !module.disableDotnet6Compatibility) { @@ -254,37 +237,6 @@ function initializeImportsAndExports( warnWrap("removeRunDependency", () => module.removeRunDependency); } - // this is registration of the runtime pre_init, when user set configSrc - if (module.configSrc) { - module.preInit.push(async () => { - module.addRunDependency("mono_wasm_pre_init"); - // execution order == [0] == - await mono_wasm_pre_init(); - module.removeRunDependency("mono_wasm_pre_init"); - }); - } - - // if onRuntimeInitialized is set it's probably Blazor, we let them to do their own init sequence - if (!module.onRuntimeInitialized) { - // note this would keep running in async-parallel with emscripten's `run()` and `postRun()` - // because it's loading files asynchronously and the emscripten is not awaiting onRuntimeInitialized - // execution order == [1] == - module.onRuntimeInitialized = () => mono_wasm_on_runtime_initialized(); - - module.ready = module.ready.then(async () => { - // mono_wasm_runtime_is_initialized is set when finalize_startup is done - await mono_wasm_runtime_is_initialized; - // TODO we could take over Module.postRun and call it from here if necessary - - // execution order == [2] == - return exportedAPI; - }); - } - - if (!module.onAbort) { - module.onAbort = () => mono_on_abort; - } - // this code makes it possible to find dotnet runtime on a page via global namespace, even when there are multiple runtimes at the same time let list: RuntimeList; if (!globalThisAny.getDotnetRuntime) { @@ -296,6 +248,8 @@ function initializeImportsAndExports( } list.registerRuntime(exportedAPI); + configure_emscripten_startup(module, exportedAPI); + return exportedAPI; } diff --git a/src/mono/wasm/runtime/imports.ts b/src/mono/wasm/runtime/imports.ts index ecd5916b37c26..47e4da482f4b5 100644 --- a/src/mono/wasm/runtime/imports.ts +++ b/src/mono/wasm/runtime/imports.ts @@ -14,28 +14,30 @@ export let BINDING: any; export let INTERNAL: any; // these are imported and re-exported from emscripten internals -export let ENVIRONMENT_IS_GLOBAL: boolean; +export let ENVIRONMENT_IS_ESM: boolean; export let ENVIRONMENT_IS_NODE: boolean; export let ENVIRONMENT_IS_SHELL: boolean; export let ENVIRONMENT_IS_WEB: boolean; export let locateFile: Function; export let quit: Function; +export let requirePromise: Promise; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function setImportsAndExports( - imports: { isGlobal: boolean, isNode: boolean, isShell: boolean, isWeb: boolean, locateFile: Function, quit_: Function }, + imports: { isESM: boolean, isNode: boolean, isShell: boolean, isWeb: boolean, locateFile: Function, quit_: Function, requirePromise: Promise }, exports: { mono: any, binding: any, internal: any, module: any }, ): void { MONO = exports.mono; BINDING = exports.binding; INTERNAL = exports.internal; Module = exports.module; - ENVIRONMENT_IS_GLOBAL = imports.isGlobal; + ENVIRONMENT_IS_ESM = imports.isESM; ENVIRONMENT_IS_NODE = imports.isNode; ENVIRONMENT_IS_SHELL = imports.isShell; ENVIRONMENT_IS_WEB = imports.isWeb; locateFile = imports.locateFile; quit = imports.quit_; + requirePromise = imports.requirePromise; } let monoConfig: MonoConfig; diff --git a/src/mono/wasm/runtime/memory.ts b/src/mono/wasm/runtime/memory.ts index e8a89bd11a574..c8760a0c7a994 100644 --- a/src/mono/wasm/runtime/memory.ts +++ b/src/mono/wasm/runtime/memory.ts @@ -1,36 +1,44 @@ import { Module } from "./imports"; -import { VoidPtr, NativePointer } from "./types/emscripten"; +import { VoidPtr, NativePointer, ManagedPointer } from "./types/emscripten"; -const _temp_mallocs: Array | null> = []; +const alloca_stack: Array = []; +const alloca_buffer_size = 32 * 1024; +let alloca_base: VoidPtr, alloca_offset: VoidPtr, alloca_limit: VoidPtr; + +function _ensure_allocated(): void { + if (alloca_base) + return; + alloca_base = Module._malloc(alloca_buffer_size); + alloca_offset = alloca_base; + alloca_limit = (alloca_base + alloca_buffer_size); +} export function temp_malloc(size: number): VoidPtr { - if (!_temp_mallocs || !_temp_mallocs.length) + _ensure_allocated(); + if (!alloca_stack.length) throw new Error("No temp frames have been created at this point"); - const frame = _temp_mallocs[_temp_mallocs.length - 1] || []; - const result = Module._malloc(size); - frame.push(result); - _temp_mallocs[_temp_mallocs.length - 1] = frame; + const result = alloca_offset; + alloca_offset += size; + if (alloca_offset >= alloca_limit) + throw new Error("Out of temp storage space"); return result; } export function _create_temp_frame(): void { - _temp_mallocs.push(null); + _ensure_allocated(); + alloca_stack.push(alloca_offset); } export function _release_temp_frame(): void { - if (!_temp_mallocs.length) + if (!alloca_stack.length) throw new Error("No temp frames have been created at this point"); - const frame = _temp_mallocs.pop(); - if (!frame) - return; - - for (let i = 0, l = frame.length; i < l; i++) - Module._free(frame[i]); + alloca_offset = alloca_stack.pop(); } type _MemOffset = number | VoidPtr | NativePointer; +type _NumberOrPointer = number | VoidPtr | NativePointer | ManagedPointer; export function setU8(offset: _MemOffset, value: number): void { Module.HEAPU8[offset] = value; @@ -40,8 +48,8 @@ export function setU16(offset: _MemOffset, value: number): void { Module.HEAPU16[offset >>> 1] = value; } -export function setU32(offset: _MemOffset, value: number): void { - Module.HEAPU32[offset >>> 2] = value; +export function setU32 (offset: _MemOffset, value: _NumberOrPointer) : void { + Module.HEAPU32[offset >>> 2] = value; } export function setI8(offset: _MemOffset, value: number): void { @@ -52,8 +60,8 @@ export function setI16(offset: _MemOffset, value: number): void { Module.HEAP16[offset >>> 1] = value; } -export function setI32(offset: _MemOffset, value: number): void { - Module.HEAP32[offset >>> 2] = value; +export function setI32 (offset: _MemOffset, value: _NumberOrPointer) : void { + Module.HEAP32[offset >>> 2] = value; } // NOTE: Accepts a number, not a BigInt, so values over Number.MAX_SAFE_INTEGER will be corrupted diff --git a/src/mono/wasm/runtime/method-binding.ts b/src/mono/wasm/runtime/method-binding.ts index 4827766f88c49..04010b20ab72b 100644 --- a/src/mono/wasm/runtime/method-binding.ts +++ b/src/mono/wasm/runtime/method-binding.ts @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. import { WasmRoot, WasmRootBuffer, mono_wasm_new_root } from "./roots"; -import { MonoClass, MonoMethod, MonoObject, coerceNull, VoidPtrNull, MonoType } from "./types"; +import { MonoClass, MonoMethod, MonoObject, coerceNull, VoidPtrNull, MonoType, MarshalType } from "./types"; import { BINDING, Module, runtimeHelpers } from "./imports"; import { js_to_mono_enum, _js_to_mono_obj, _js_to_mono_uri } from "./js-to-cs"; import { js_string_to_mono_string, js_string_to_mono_string_interned } from "./strings"; -import { MarshalType, _unbox_mono_obj_root_with_known_nonprimitive_type } from "./cs-to-js"; +import { _unbox_mono_obj_root_with_known_nonprimitive_type } from "./cs-to-js"; import { _create_temp_frame, getI32, getU32, getF32, getF64, diff --git a/src/mono/wasm/runtime/polyfills.ts b/src/mono/wasm/runtime/polyfills.ts index 01d4d2ded9bc9..048a2477cc0a3 100644 --- a/src/mono/wasm/runtime/polyfills.ts +++ b/src/mono/wasm/runtime/polyfills.ts @@ -1,4 +1,7 @@ -import { ENVIRONMENT_IS_NODE, Module } from "./imports"; +import { ENVIRONMENT_IS_NODE, Module, requirePromise } from "./imports"; + +let node_fs: any | undefined = undefined; +let node_url: any | undefined = undefined; export async function fetch_like(url: string): Promise { try { @@ -6,8 +9,11 @@ export async function fetch_like(url: string): Promise { return globalThis.fetch(url, { credentials: "same-origin" }); } else if (ENVIRONMENT_IS_NODE) { - const node_fs = Module.imports!.require!("fs"); - const node_url = Module.imports!.require!("url"); + if (!node_fs) { + const node_require = await requirePromise; + node_url = node_require("url"); + node_fs = node_require("fs"); + } if (url.startsWith("file://")) { url = node_url.fileURLToPath(url); } @@ -21,6 +27,8 @@ export async function fetch_like(url: string): Promise { }; } else if (typeof (read) === "function") { + // note that it can't open files with unicode names, like Straße.xml + // https://bugs.chromium.org/p/v8/issues/detail?id=12541 const arrayBuffer = new Uint8Array(read(url, "binary")); return { ok: true, diff --git a/src/mono/wasm/runtime/roots.ts b/src/mono/wasm/runtime/roots.ts index 010732c23a894..2d473fb22ff20 100644 --- a/src/mono/wasm/runtime/roots.ts +++ b/src/mono/wasm/runtime/roots.ts @@ -10,6 +10,7 @@ let _scratch_root_buffer: WasmRootBuffer | null = null; let _scratch_root_free_indices: Int32Array | null = null; let _scratch_root_free_indices_count = 0; const _scratch_root_free_instances: WasmRoot[] = []; +const _external_root_free_instances: WasmExternalRoot[] = []; /** * Allocates a block of memory that can safely contain pointers into the managed heap. @@ -52,6 +53,26 @@ export function mono_wasm_new_root_buffer_from_pointer(offset: VoidPtr, capacity return new WasmRootBuffer(offset, capacity, false, name); } +/** + * Allocates a WasmRoot pointing to a root provided and controlled by external code. Typicaly on managed stack. + * Releasing this root will not de-allocate the root space. You still need to call .release(). + */ +export function mono_wasm_new_external_root(address: VoidPtr): WasmRoot { + let result: WasmExternalRoot; + + if (!address) + throw new Error("address must be a location in the native heap"); + + if (_external_root_free_instances.length > 0) { + result = _external_root_free_instances.pop()!; + result._set_address(address); + } else { + result = new WasmExternalRoot(address); + } + + return result; +} + /** * Allocates temporary storage for a pointer into the managed heap. * Pointers stored here will be visible to the GC, ensuring that the object they point to aren't moved or collected. @@ -68,7 +89,7 @@ export function mono_wasm_new_root(val const index = _mono_wasm_claim_scratch_index(); const buffer = _scratch_root_buffer; - result = new WasmRoot(buffer!, index); + result = new WasmJsOwnedRoot(buffer!, index); } if (value !== undefined) { @@ -239,7 +260,20 @@ export class WasmRootBuffer { } } -export class WasmRoot { +export interface WasmRoot { + get_address(): NativePointer; + get_address_32(): number; + get(): T; + set(value: T): T; + get value(): T; + set value(value: T); + valueOf(): T; + clear(): void; + release(): void; + toString(): string; +} + +class WasmJsOwnedRoot implements WasmRoot { private __buffer: WasmRootBuffer; private __index: number; @@ -301,3 +335,61 @@ export class WasmRoot { return `[root @${this.get_address()}]`; } } + +class WasmExternalRoot implements WasmRoot { + private __external_address: NativePointer = undefined; + private __external_address_32: number = undefined; + + constructor(address: NativePointer) { + this._set_address(address); + } + + _set_address(address: NativePointer): void { + this.__external_address = address; + this.__external_address_32 = address >>> 2; + } + + get_address(): NativePointer { + return this.__external_address; + } + + get_address_32(): number { + return this.__external_address_32; + } + + get(): T { + const result = Module.HEAPU32[this.__external_address_32]; + return result; + } + + set(value: T): T { + Module.HEAPU32[this.__external_address_32] = value; + return value; + } + + get value(): T { + return this.get(); + } + + set value(value: T) { + this.set(value); + } + + valueOf(): T { + return this.get(); + } + + clear(): void { + this.set(0); + } + + release(): void { + const maxPooledInstances = 128; + if (_external_root_free_instances.length < maxPooledInstances) + _external_root_free_instances.push(this); + } + + toString(): string { + return `[external root @${this.get_address()}]`; + } +} \ No newline at end of file diff --git a/src/mono/wasm/runtime/startup.ts b/src/mono/wasm/runtime/startup.ts index cc115366db6db..8801ac704b0eb 100644 --- a/src/mono/wasm/runtime/startup.ts +++ b/src/mono/wasm/runtime/startup.ts @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -import { AllAssetEntryTypes, AssetEntry, CharPtrNull, DotnetModule, GlobalizationMode, MonoConfig, MonoConfigError, wasm_type_symbol } from "./types"; -import { ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, INTERNAL, locateFile, Module, MONO, runtimeHelpers } from "./imports"; +import { AllAssetEntryTypes, assert, AssetEntry, CharPtrNull, DotnetModule, GlobalizationMode, MonoConfig, MonoConfigError, wasm_type_symbol } from "./types"; +import { ENVIRONMENT_IS_ESM, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_SHELL, INTERNAL, locateFile, Module, MONO, requirePromise, runtimeHelpers } from "./imports"; import cwraps from "./cwraps"; import { mono_wasm_raise_debug_event, mono_wasm_runtime_ready } from "./debug"; import { mono_wasm_globalization_init, mono_wasm_load_icu_data } from "./icu"; @@ -12,6 +12,8 @@ import { mono_wasm_load_bytes_into_heap } from "./buffers"; import { bind_runtime_method, get_method, _create_primitive_converters } from "./method-binding"; import { find_corlib_class } from "./class-loader"; import { VoidPtr, CharPtr } from "./types/emscripten"; +import { DotnetPublicAPI } from "./exports"; +import { mono_on_abort } from "./run"; export let runtime_is_initialized_resolve: Function; export let runtime_is_initialized_reject: Function; @@ -20,42 +22,123 @@ export const mono_wasm_runtime_is_initialized = new Promise((resolve, reject) => runtime_is_initialized_reject = reject; }); +let ctx: DownloadAssetsContext | null = null; -export async function mono_wasm_pre_init(): Promise { - const moduleExt = Module as DotnetModule; - if (!moduleExt.configSrc) { - return; +export function configure_emscripten_startup(module: DotnetModule, exportedAPI: DotnetPublicAPI): void { + // these could be overriden on DotnetModuleConfig + if (!module.preInit) { + module.preInit = []; + } else if (typeof module.preInit === "function") { + module.preInit = [module.preInit]; + } + if (!module.preRun) { + module.preRun = []; + } else if (typeof module.preRun === "function") { + module.preRun = [module.preRun]; + } + if (!module.postRun) { + module.postRun = []; + } else if (typeof module.postRun === "function") { + module.postRun = [module.postRun]; } - try { - // sets MONO.config implicitly - await mono_wasm_load_config(moduleExt.configSrc); + // when user set configSrc or config, we are running our default startup sequence. + if (module.configSrc || module.config) { + // execution order == [0] == + // - default or user Module.instantiateWasm (will start downloading dotnet.wasm) + // - all user Module.preInit + + // execution order == [1] == + module.preInit.push(mono_wasm_pre_init); + // - download Module.config from configSrc + // - download assets like DLLs + + // execution order == [2] == + // - all user Module.preRun callbacks + + // execution order == [3] == + // - user Module.onRuntimeInitialized callback + + // execution order == [4] == + module.postRun.unshift(mono_wasm_after_runtime_initialized); + // - load DLLs into WASM memory + // - apply globalization and other env variables + // - call mono_wasm_load_runtime + + // execution order == [5] == + // - all user Module.postRun callbacks + + // execution order == [6] == + module.ready = module.ready.then(async () => { + // mono_wasm_runtime_is_initialized promise is resolved when finalize_startup is done + await mono_wasm_runtime_is_initialized; + // - here we resolve the promise returned by createDotnetRuntime export + return exportedAPI; + // - any code after createDotnetRuntime is executed now + }); + } - catch (err: any) { - runtime_is_initialized_reject(err); - throw err; + // Otherwise startup sequence is up to user code, like Blazor + + if (!module.onAbort) { + module.onAbort = () => mono_on_abort; + } +} + +async function mono_wasm_pre_init(): Promise { + const moduleExt = Module as DotnetModule; + + Module.addRunDependency("mono_wasm_pre_init"); + + // wait for locateFile setup on NodeJs + if (ENVIRONMENT_IS_NODE && ENVIRONMENT_IS_ESM) { + await requirePromise; } - if (moduleExt.onConfigLoaded) { + if (moduleExt.configSrc) { try { - moduleExt.onConfigLoaded(); + // sets MONO.config implicitly + await mono_wasm_load_config(moduleExt.configSrc); + } + catch (err: any) { + runtime_is_initialized_reject(err); + throw err; + } + + if (moduleExt.onConfigLoaded) { + try { + await moduleExt.onConfigLoaded(runtimeHelpers.config); + } + catch (err: any) { + Module.printErr("MONO_WASM: onConfigLoaded () failed: " + err); + Module.printErr("MONO_WASM: Stacktrace: \n"); + Module.printErr(err.stack); + runtime_is_initialized_reject(err); + throw err; + } + } + } + + if (moduleExt.config) { + try { + // start downloading assets asynchronously + // next event of emscripten would bre triggered by last `removeRunDependency` + await mono_download_assets(Module.config); } catch (err: any) { - Module.printErr("MONO_WASM: onConfigLoaded () failed: " + err); - Module.printErr("MONO_WASM: Stacktrace: \n"); - Module.printErr(err.stack); runtime_is_initialized_reject(err); throw err; } } + Module.removeRunDependency("mono_wasm_pre_init"); } -export async function mono_wasm_on_runtime_initialized(): Promise { +function mono_wasm_after_runtime_initialized(): void { if (!Module.config || Module.config.isError) { return; } - await mono_load_runtime_and_bcl_args(Module.config); + finalize_assets(Module.config); finalize_startup(Module.config); } @@ -76,8 +159,12 @@ export function mono_wasm_set_runtime_options(options: string[]): void { cwraps.mono_wasm_parse_runtime_options(options.length, argv); } -function _handle_fetched_asset(ctx: MonoInitContext, asset: AssetEntry, url: string, blob: ArrayBuffer) { - const bytes = new Uint8Array(blob); +// this need to be run only after onRuntimeInitialized event, when the memory is ready +function _handle_fetched_asset(asset: AssetEntry, url?: string) { + assert(ctx, "Context is expected"); + assert(asset.buffer, "asset.buffer is expected"); + + const bytes = new Uint8Array(asset.buffer); if (ctx.tracing) console.log(`MONO_WASM: Loaded:${asset.name} as ${asset.behavior} size ${bytes.length} from ${url}`); @@ -110,7 +197,7 @@ function _handle_fetched_asset(ctx: MonoInitContext, asset: AssetEntry, url: str if (ctx.tracing) console.log(`MONO_WASM: Creating directory '${parentDirectory}'`); - ctx.createPath( + Module.FS_createPath( "/", parentDirectory, true, true // fixme: should canWrite be false? ); } else { @@ -121,7 +208,7 @@ function _handle_fetched_asset(ctx: MonoInitContext, asset: AssetEntry, url: str console.log(`MONO_WASM: Creating file '${fileName}' in directory '${parentDirectory}'`); if (!mono_wasm_load_data_archive(bytes, parentDirectory)) { - ctx.createDataFile( + Module.FS_createDataFile( parentDirectory, fileName, bytes, true /* canRead */, true /* canWrite */, true /* canOwn */ ); @@ -302,6 +389,11 @@ export function bindings_lazy_init(): void { // Initializes the runtime and loads assemblies, debug information, and other files. export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoConfigError | undefined): Promise { + await mono_download_assets(config); + finalize_assets(config); +} + +async function mono_download_assets(config: MonoConfig | MonoConfigError | undefined): Promise { if (!config || config.isError) { return; } @@ -312,14 +404,15 @@ export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoCo config.diagnostic_tracing = config.diagnostic_tracing || false; - const ctx: MonoInitContext = { + ctx = { tracing: config.diagnostic_tracing, pending_count: config.assets.length, + downloading_count: config.assets.length, + fetch_all_promises: null, + resolved_promises: [], loaded_assets: Object.create(null), // dlls and pdbs, used by blazor and the debugger loaded_files: [], - createPath: Module.FS_createPath, - createDataFile: Module.FS_createDataFile }; // fetch_file_cb is legacy do we really want to support it ? @@ -327,11 +420,37 @@ export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoCo runtimeHelpers.fetch = (config).fetch_file_cb; } - const load_asset = async (config: MonoConfig, asset: AllAssetEntryTypes): Promise => { - // TODO Module.addRunDependency(asset.name); + const max_parallel_downloads = 100; + // in order to prevent net::ERR_INSUFFICIENT_RESOURCES if we start downloading too many files at same time + let parallel_count = 0; + let throttling_promise: Promise | undefined = undefined; + let throttling_promise_resolve: Function | undefined = undefined; + + const load_asset = async (config: MonoConfig, asset: AllAssetEntryTypes): Promise => { + while (throttling_promise) { + await throttling_promise; + } + ++parallel_count; + if (parallel_count == max_parallel_downloads) { + if (ctx!.tracing) + console.log("MONO_WASM: Throttling further parallel downloads"); + + throttling_promise = new Promise((resolve) => { + throttling_promise_resolve = resolve; + }); + } + + Module.addRunDependency(asset.name); const sourcesList = asset.load_remote ? config.remote_sources! : [""]; let error = undefined; + let result: MonoInitFetchResult | undefined = undefined; + + if (asset.buffer) { + --ctx!.downloading_count; + return { asset, attemptUrl: undefined }; + } + for (let sourcePrefix of sourcesList) { // HACK: Special-case because MSBuild doesn't allow "" as an attribute if (sourcePrefix === "./") @@ -351,10 +470,10 @@ export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoCo attemptUrl = sourcePrefix + asset.name; } if (asset.name === attemptUrl) { - if (ctx.tracing) + if (ctx!.tracing) console.log(`MONO_WASM: Attempting to fetch '${attemptUrl}'`); } else { - if (ctx.tracing) + if (ctx!.tracing) console.log(`MONO_WASM: Attempting to fetch '${attemptUrl}' for ${asset.name}`); } try { @@ -364,9 +483,9 @@ export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoCo continue;// next source } - const buffer = await response.arrayBuffer(); - _handle_fetched_asset(ctx, asset, attemptUrl, buffer); - --ctx.pending_count; + asset.buffer = await response.arrayBuffer(); + result = { asset, attemptUrl }; + --ctx!.downloading_count; error = undefined; } catch (err) { @@ -378,20 +497,51 @@ export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoCo break; // this source worked, stop searching } } + + --parallel_count; + if (throttling_promise && parallel_count == ((max_parallel_downloads / 2) | 0)) { + if (ctx!.tracing) + console.log("MONO_WASM: Resuming more parallel downloads"); + throttling_promise_resolve!(); + throttling_promise = undefined; + } + if (error) { const isOkToFail = asset.is_optional || (asset.name.match(/\.pdb$/) && config.ignore_pdb_load_errors); if (!isOkToFail) throw error; } - // TODO Module.removeRunDependency(asset.name); + Module.removeRunDependency(asset.name); + + return result; }; - const fetch_promises: Promise[] = []; + const fetch_promises: Promise<(MonoInitFetchResult | undefined)>[] = []; + // start fetching all assets in parallel for (const asset of config.assets) { fetch_promises.push(load_asset(config, asset)); } - await Promise.all(fetch_promises); + ctx.fetch_all_promises = Promise.all(fetch_promises); + ctx.resolved_promises = await ctx.fetch_all_promises; + } catch (err: any) { + Module.printErr("MONO_WASM: Error in mono_download_assets: " + err); + runtime_is_initialized_reject(err); + throw err; + } +} + +function finalize_assets(config: MonoConfig | MonoConfigError | undefined): void { + assert(config && !config.isError, "Expected config"); + assert(ctx && ctx.downloading_count == 0, "Expected assets to be downloaded"); + + try { + for (const fetch_result of ctx.resolved_promises!) { + if (fetch_result) { + _handle_fetched_asset(fetch_result.asset, fetch_result.attemptUrl); + --ctx.pending_count; + } + } ctx.loaded_files.forEach(value => MONO.loaded_files.push(value.url)); if (ctx.tracing) { @@ -399,7 +549,7 @@ export async function mono_load_runtime_and_bcl_args(config: MonoConfig | MonoCo console.log("MONO_WASM: loaded_files: " + JSON.stringify(ctx.loaded_files)); } } catch (err: any) { - Module.printErr("MONO_WASM: Error in mono_load_runtime_and_bcl_args: " + err); + Module.printErr("MONO_WASM: Error in finalize_assets: " + err); runtime_is_initialized_reject(err); throw err; } @@ -525,11 +675,17 @@ export function mono_wasm_set_main_args(name: string, allRuntimeArguments: strin cwraps.mono_wasm_set_main_args(main_argc, main_argv); } -export type MonoInitContext = { +type MonoInitFetchResult = { + asset: AllAssetEntryTypes, + attemptUrl?: string, +} + +export type DownloadAssetsContext = { tracing: boolean, + downloading_count: number, pending_count: number, - loaded_files: { url: string, file: string }[], + fetch_all_promises: Promise<(MonoInitFetchResult | undefined)[]> | null; + resolved_promises: (MonoInitFetchResult | undefined)[] | null; + loaded_files: { url?: string, file: string }[], loaded_assets: { [id: string]: [VoidPtr, number] }, - createPath: Function, - createDataFile: Function } \ No newline at end of file diff --git a/src/mono/wasm/runtime/types.ts b/src/mono/wasm/runtime/types.ts index e9bd91d87940d..b208aeedcd06a 100644 --- a/src/mono/wasm/runtime/types.ts +++ b/src/mono/wasm/runtime/types.ts @@ -81,6 +81,7 @@ export type AssetEntry = { culture?: string, load_remote?: boolean, // if true, an attempt will be made to load the asset from each location in @args.remote_sources. is_optional?: boolean // if true, any failure to load this asset will be ignored. + buffer?: ArrayBuffer // if provided, we don't have to fetch it } export interface AssemblyEntry extends AssetEntry { @@ -161,8 +162,7 @@ export type DotnetModuleConfig = { config?: MonoConfig | MonoConfigError, configSrc?: string, - scriptDirectory?: string, - onConfigLoaded?: () => void; + onConfigLoaded?: (config: MonoConfig) => Promise; onDotnetReady?: () => void; imports?: DotnetModuleConfigImports; @@ -186,4 +186,54 @@ export type DotnetModuleConfigImports = { dirname?: (path: string) => string, }; url?: any; +} + +export function assert(condition: unknown, messsage: string): asserts condition { + if (!condition) { + throw new Error(`Assert failed: ${messsage}`); + } +} + +// see src/mono/wasm/driver.c MARSHAL_TYPE_xxx and Runtime.cs MarshalType +export enum MarshalType { + NULL = 0, + INT = 1, + FP64 = 2, + STRING = 3, + VT = 4, + DELEGATE = 5, + TASK = 6, + OBJECT = 7, + BOOL = 8, + ENUM = 9, + URI = 22, + SAFEHANDLE = 23, + ARRAY_BYTE = 10, + ARRAY_UBYTE = 11, + ARRAY_UBYTE_C = 12, + ARRAY_SHORT = 13, + ARRAY_USHORT = 14, + ARRAY_INT = 15, + ARRAY_UINT = 16, + ARRAY_FLOAT = 17, + ARRAY_DOUBLE = 18, + FP32 = 24, + UINT32 = 25, + INT64 = 26, + UINT64 = 27, + CHAR = 28, + STRING_INTERNED = 29, + VOID = 30, + ENUM64 = 31, + POINTER = 32, + SPAN_BYTE = 33, +} + +// see src/mono/wasm/driver.c MARSHAL_ERROR_xxx and Runtime.cs +export enum MarshalError { + BUFFER_TOO_SMALL = 512, + NULL_CLASS_POINTER = 513, + NULL_TYPE_POINTER = 514, + UNSUPPORTED_TYPE = 515, + FIRST = BUFFER_TOO_SMALL } \ No newline at end of file diff --git a/src/mono/wasm/test-main.js b/src/mono/wasm/test-main.js index 571acf06463f4..4348444be6299 100644 --- a/src/mono/wasm/test-main.js +++ b/src/mono/wasm/test-main.js @@ -124,7 +124,7 @@ loadDotnet("./dotnet.js").then((createDotnetRuntime) => { disableDotnet6Compatibility: true, config: null, configSrc: "./mono-config.json", - onConfigLoaded: () => { + onConfigLoaded: (config) => { if (!Module.config) { const err = new Error("Could not find ./mono-config.json. Cancelling run"); set_exit_code(1,); @@ -132,9 +132,11 @@ loadDotnet("./dotnet.js").then((createDotnetRuntime) => { } // Have to set env vars here to enable setting MONO_LOG_LEVEL etc. for (let variable in processedArguments.setenv) { - Module.config.environment_variables[variable] = processedArguments.setenv[variable]; + config.environment_variables[variable] = processedArguments.setenv[variable]; } - + config.diagnostic_tracing = !!processedArguments.diagnostic_tracing; + }, + preRun: () => { if (!processedArguments.enable_gc) { INTERNAL.mono_wasm_enable_on_demand_gc(0); } @@ -281,6 +283,7 @@ function processArguments(incomingArguments) { let setenv = {}; let runtime_args = []; let enable_gc = true; + let diagnostic_tracing = false; let working_dir = '/'; while (incomingArguments && incomingArguments.length > 0) { const currentArg = incomingArguments[0]; @@ -298,6 +301,8 @@ function processArguments(incomingArguments) { runtime_args.push(arg); } else if (currentArg == "--disable-on-demand-gc") { enable_gc = false; + } else if (currentArg == "--diagnostic_tracing") { + diagnostic_tracing = true; } else if (currentArg.startsWith("--working-dir=")) { const arg = currentArg.substring("--working-dir=".length); working_dir = arg; @@ -318,6 +323,7 @@ function processArguments(incomingArguments) { setenv, runtime_args, enable_gc, + diagnostic_tracing, working_dir, } } diff --git a/src/native/corehost/fxr/host_context.cpp b/src/native/corehost/fxr/host_context.cpp index 82fe8c2b494dc..73af214ed3b8a 100644 --- a/src/native/corehost/fxr/host_context.cpp +++ b/src/native/corehost/fxr/host_context.cpp @@ -129,8 +129,8 @@ host_context_t::host_context_t( const corehost_context_contract &hostpolicy_context_contract) : marker { valid_host_context_marker } , type { type } - , hostpolicy_contract { hostpolicy_contract } - , hostpolicy_context_contract { hostpolicy_context_contract } + , hostpolicy_contract (hostpolicy_contract) + , hostpolicy_context_contract (hostpolicy_context_contract) { } void host_context_t::initialize_frameworks(const corehost_init_t& init) diff --git a/src/native/libs/Common/pal_config.h.in b/src/native/libs/Common/pal_config.h.in index 431071204dfb8..1dc19840e56f8 100644 --- a/src/native/libs/Common/pal_config.h.in +++ b/src/native/libs/Common/pal_config.h.in @@ -12,6 +12,7 @@ #cmakedefine01 HAVE_F_FULLFSYNC #cmakedefine01 HAVE_O_CLOEXEC #cmakedefine01 HAVE_GETIFADDRS +#cmakedefine01 HAVE_IFADDRS #cmakedefine01 HAVE_UTSNAME_DOMAINNAME #cmakedefine01 HAVE_STAT64 #cmakedefine01 HAVE_FORK diff --git a/src/native/libs/Common/pal_utilities.h b/src/native/libs/Common/pal_utilities.h index 4e582ed6cd002..0bab812bd613e 100644 --- a/src/native/libs/Common/pal_utilities.h +++ b/src/native/libs/Common/pal_utilities.h @@ -43,6 +43,10 @@ #define CONST_CAST2(TOTYPE, FROMTYPE, X) ((union { FROMTYPE _q; TOTYPE _nq; }){ ._q = (X) }._nq) #define CONST_CAST(TYPE, X) CONST_CAST2(TYPE, const TYPE, (X)) +#ifndef __has_attribute +#define __has_attribute(x) (0) +#endif + #if __has_attribute(fallthrough) #define FALLTHROUGH __attribute__((fallthrough)) #else diff --git a/src/native/libs/System.Native/entrypoints.c b/src/native/libs/System.Native/entrypoints.c index 0e54f4b5f1519..9ac04de3e0d66 100644 --- a/src/native/libs/System.Native/entrypoints.c +++ b/src/native/libs/System.Native/entrypoints.c @@ -109,6 +109,7 @@ static const Entry s_sysNative[] = DllImportEntry(SystemNative_LockFileRegion) DllImportEntry(SystemNative_LChflags) DllImportEntry(SystemNative_LChflagsCanSetHiddenFlag) + DllImportEntry(SystemNative_CanGetHiddenFlag) DllImportEntry(SystemNative_ReadProcessStatusInfo) DllImportEntry(SystemNative_Log) DllImportEntry(SystemNative_LogError) diff --git a/src/native/libs/System.Native/pal_interfaceaddresses.c b/src/native/libs/System.Native/pal_interfaceaddresses.c index 953754e68443a..a876e7f172843 100644 --- a/src/native/libs/System.Native/pal_interfaceaddresses.c +++ b/src/native/libs/System.Native/pal_interfaceaddresses.c @@ -11,7 +11,13 @@ #include #include #include +#if HAVE_IFADDRS || HAVE_GETIFADDRS #include +#endif +#if !HAVE_GETIFADDRS && TARGET_ANDROID +#include +#include +#endif #include #include #include @@ -55,7 +61,6 @@ #endif #endif -#if HAVE_GETIFADDRS // Convert mask to prefix length e.g. 255.255.255.0 -> 24 // mask parameter is pointer to buffer where address starts and length is // buffer length e.g. 4 for IPv4 and 16 for IPv6. @@ -95,6 +100,50 @@ static inline uint8_t mask2prefix(uint8_t* mask, int length) return len; } + +#if !HAVE_IFADDRS && TARGET_ANDROID +// This structure is exactly the same as struct ifaddrs defined in ifaddrs.h but since the header +// might not be available (e.g., in bionics used in Android before API 24) we need to mirror it here +// so that we can dynamically load the getifaddrs function and use it. +struct ifaddrs +{ + struct ifaddrs *ifa_next; + char *ifa_name; + unsigned int ifa_flags; + struct sockaddr *ifa_addr; + struct sockaddr *ifa_netmask; + union + { + struct sockaddr *ifu_broadaddr; + struct sockaddr *ifu_dstaddr; + } ifa_ifu; + void *ifa_data; +}; +#endif + +#if !HAVE_GETIFADDRS && TARGET_ANDROID +// Try to load the getifaddrs and freeifaddrs functions manually. +// This workaround is necessary on Android prior to API 24 and it can be removed once +// we drop support for earlier Android versions. +static int (*getifaddrs)(struct ifaddrs**) = NULL; +static void (*freeifaddrs)(struct ifaddrs*) = NULL; + +static void try_loading_getifaddrs() +{ + void *libc = dlopen("libc.so", RTLD_NOW); + if (libc) + { + getifaddrs = (int (*)(struct ifaddrs**)) dlsym(libc, "getifaddrs"); + freeifaddrs = (void (*)(struct ifaddrs*)) dlsym(libc, "freeifaddrs"); + } +} + +static bool ensure_getifaddrs_is_loaded() +{ + static pthread_once_t getifaddrs_is_loaded = PTHREAD_ONCE_INIT; + pthread_once(&getifaddrs_is_loaded, try_loading_getifaddrs); + return getifaddrs != NULL && freeifaddrs != NULL; +} #endif int32_t SystemNative_EnumerateInterfaceAddresses(void* context, @@ -102,7 +151,16 @@ int32_t SystemNative_EnumerateInterfaceAddresses(void* context, IPv6AddressFound onIpv6Found, LinkLayerAddressFound onLinkLayerFound) { -#if HAVE_GETIFADDRS +#if !HAVE_GETIFADDRS && TARGET_ANDROID + // Workaround for Android API < 24 + if (!ensure_getifaddrs_is_loaded()) + { + errno = ENOTSUP; + return -1; + } +#endif + +#if HAVE_GETIFADDRS || TARGET_ANDROID struct ifaddrs* headAddr; if (getifaddrs(&headAddr) == -1) { @@ -235,7 +293,7 @@ int32_t SystemNative_EnumerateInterfaceAddresses(void* context, freeifaddrs(headAddr); return 0; #else - // Not supported on e.g. Android. Also, prevent a compiler error because parameters are unused + // Not supported. Also, prevent a compiler error because parameters are unused (void)context; (void)onIpv4Found; (void)onIpv6Found; @@ -247,7 +305,16 @@ int32_t SystemNative_EnumerateInterfaceAddresses(void* context, int32_t SystemNative_GetNetworkInterfaces(int32_t * interfaceCount, NetworkInterfaceInfo **interfaceList, int32_t * addressCount, IpAddressInfo **addressList ) { -#if HAVE_GETIFADDRS +#if !HAVE_GETIFADDRS && TARGET_ANDROID + // Workaround for Android API < 24 + if (!ensure_getifaddrs_is_loaded()) + { + errno = ENOTSUP; + return -1; + } +#endif + +#if HAVE_GETIFADDRS || TARGET_ANDROID struct ifaddrs* head; // Pointer to block allocated by getifaddrs(). struct ifaddrs* ifaddrsEntry; IpAddressInfo *ai; @@ -454,7 +521,7 @@ int32_t SystemNative_GetNetworkInterfaces(int32_t * interfaceCount, NetworkInter return 0; #else - // Not supported on e.g. Android. Also, prevent a compiler error because parameters are unused + // Not supported. Also, prevent a compiler error because parameters are unused (void)interfaceCount; (void)interfaceList; (void)addressCount; diff --git a/src/native/libs/System.Native/pal_io.c b/src/native/libs/System.Native/pal_io.c index 66c934ed182fa..d11ce950f1246 100644 --- a/src/native/libs/System.Native/pal_io.c +++ b/src/native/libs/System.Native/pal_io.c @@ -1553,7 +1553,16 @@ int32_t SystemNative_LChflags(const char* path, uint32_t flags) int32_t SystemNative_LChflagsCanSetHiddenFlag(void) { -#if defined(UF_HIDDEN) && defined(HAVE_STAT_FLAGS) && defined(HAVE_LCHFLAGS) +#if defined(HAVE_LCHFLAGS) + return SystemNative_CanGetHiddenFlag(); +#else + return false; +#endif +} + +int32_t SystemNative_CanGetHiddenFlag(void) +{ +#if defined(UF_HIDDEN) && defined(HAVE_STAT_FLAGS) return true; #else return false; diff --git a/src/native/libs/System.Native/pal_io.h b/src/native/libs/System.Native/pal_io.h index 726b097aff133..6ebde79230af9 100644 --- a/src/native/libs/System.Native/pal_io.h +++ b/src/native/libs/System.Native/pal_io.h @@ -744,6 +744,13 @@ PALEXPORT int32_t SystemNative_LChflags(const char* path, uint32_t flags); */ PALEXPORT int32_t SystemNative_LChflagsCanSetHiddenFlag(void); +/** + * Determines if the current platform supports getting UF_HIDDEN (0x8000) flag + * + * Returns true (non-zero) if supported, false (zero) if not. + */ +PALEXPORT int32_t SystemNative_CanGetHiddenFlag(void); + /** * Reads the psinfo_t struct and converts into ProcessStatus. * diff --git a/src/native/libs/System.Security.Cryptography.Native.Android/pal_sslstream.c b/src/native/libs/System.Security.Cryptography.Native.Android/pal_sslstream.c index 4b95faf7a191b..d9054e5c46f33 100644 --- a/src/native/libs/System.Security.Cryptography.Native.Android/pal_sslstream.c +++ b/src/native/libs/System.Security.Cryptography.Native.Android/pal_sslstream.c @@ -585,13 +585,14 @@ AndroidCryptoNative_SSLStreamRead(SSLStream* sslStream, uint8_t* buffer, int32_t if (rem > 0) { - data = make_java_byte_array(env, rem); + int32_t bytes_to_read = rem < length ? rem : length; + data = make_java_byte_array(env, bytes_to_read); IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appInBuffer, g_ByteBufferGet, data)); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); IGNORE_RETURN((*env)->CallObjectMethod(env, sslStream->appInBuffer, g_ByteBufferCompact)); ON_EXCEPTION_PRINT_AND_GOTO(cleanup); - (*env)->GetByteArrayRegion(env, data, 0, rem, (jbyte*)buffer); - *read = rem; + (*env)->GetByteArrayRegion(env, data, 0, bytes_to_read, (jbyte*)buffer); + *read = bytes_to_read; ret = SSLStreamStatus_OK; } else diff --git a/src/native/libs/System.Security.Cryptography.Native.Apple/entrypoints.c b/src/native/libs/System.Security.Cryptography.Native.Apple/entrypoints.c index 78b451a781f53..875ce80316562 100644 --- a/src/native/libs/System.Security.Cryptography.Native.Apple/entrypoints.c +++ b/src/native/libs/System.Security.Cryptography.Native.Apple/entrypoints.c @@ -56,6 +56,7 @@ static const Entry s_cryptoAppleNative[] = DllImportEntry(AppleCryptoNative_SslCopyCertChain) DllImportEntry(AppleCryptoNative_SslIsHostnameMatch) DllImportEntry(AppleCryptoNative_SslRead) + DllImportEntry(AppleCryptoNative_SslSetBreakOnCertRequested) DllImportEntry(AppleCryptoNative_SslSetBreakOnClientAuth) DllImportEntry(AppleCryptoNative_SslSetBreakOnServerAuth) DllImportEntry(AppleCryptoNative_SslSetIoCallbacks) diff --git a/src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.c b/src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.c index aff6eb8b25081..7a8a0eebe1317 100644 --- a/src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.c +++ b/src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.c @@ -156,6 +156,14 @@ int32_t AppleCryptoNative_SslSetBreakOnServerAuth(SSLContextRef sslContext, int3 #pragma clang diagnostic pop } +int32_t AppleCryptoNative_SslSetBreakOnCertRequested(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus) +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + return SslSetSessionOption(sslContext, kSSLSessionOptionBreakOnCertRequested, setBreak, pOSStatus); +#pragma clang diagnostic pop +} + int32_t AppleCryptoNative_SslSetBreakOnClientAuth(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus) { #pragma clang diagnostic push @@ -275,6 +283,8 @@ PAL_TlsHandshakeState AppleCryptoNative_SslHandshake(SSLContextRef sslContext) return PAL_TlsHandshakeState_WouldBlock; case errSSLServerAuthCompleted: return PAL_TlsHandshakeState_ServerAuthCompleted; + case errSSLClientCertRequested: + return PAL_TlsHandshakeState_ClientCertRequested; default: return osStatus; } diff --git a/src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.h b/src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.h index 8a992bb9a4bc9..2c5961a72ac09 100644 --- a/src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.h +++ b/src/native/libs/System.Security.Cryptography.Native.Apple/pal_ssl.h @@ -15,6 +15,7 @@ enum PAL_TlsHandshakeState_WouldBlock = 2, PAL_TlsHandshakeState_ServerAuthCompleted = 3, PAL_TlsHandshakeState_ClientAuthCompleted = 4, + PAL_TlsHandshakeState_ClientCertRequested = 5, }; typedef int32_t PAL_TlsHandshakeState; @@ -100,6 +101,17 @@ pOSStatus: Receives the value returned by SSLSetSessionOption PALEXPORT int32_t AppleCryptoNative_SslSetBreakOnServerAuth(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus); +/* +Sets the policy of whether or not to break when certificate request was received on client. + +Returns 1 on success, 0 on failure, other values on invalid state. + +Output: +pOSStatus: Receives the value returned by SSLSetSessionOption +*/ +PALEXPORT int32_t +AppleCryptoNative_SslSetBreakOnCertRequested(SSLContextRef sslContext, int32_t setBreak, int32_t* pOSStatus); + /* Sets the policy of whether or not to break when a client identity has been presented. diff --git a/src/native/libs/System.Security.Cryptography.Native/entrypoints.c b/src/native/libs/System.Security.Cryptography.Native/entrypoints.c index 5b5af80f5205c..bcca0693f63fb 100644 --- a/src/native/libs/System.Security.Cryptography.Native/entrypoints.c +++ b/src/native/libs/System.Security.Cryptography.Native/entrypoints.c @@ -298,6 +298,7 @@ static const Entry s_cryptoNative[] = DllImportEntry(CryptoNative_SslCtxSetQuietShutdown) DllImportEntry(CryptoNative_SslCtxUseCertificate) DllImportEntry(CryptoNative_SslCtxUsePrivateKey) + DllImportEntry(CryptoNative_SslAddExtraChainCert) DllImportEntry(CryptoNative_SslDestroy) DllImportEntry(CryptoNative_SslDoHandshake) DllImportEntry(CryptoNative_SslGetClientCAList) @@ -314,12 +315,15 @@ static const Entry s_cryptoNative[] = DllImportEntry(CryptoNative_SslSetAcceptState) DllImportEntry(CryptoNative_SslSetAlpnProtos) DllImportEntry(CryptoNative_SslSetBio) + DllImportEntry(CryptoNative_SslSetClientCertCallback) DllImportEntry(CryptoNative_SslSetConnectState) DllImportEntry(CryptoNative_SslSetData) DllImportEntry(CryptoNative_SslSetQuietShutdown) DllImportEntry(CryptoNative_SslSetTlsExtHostName) DllImportEntry(CryptoNative_SslSetVerifyPeer) DllImportEntry(CryptoNative_SslShutdown) + DllImportEntry(CryptoNative_SslUseCertificate) + DllImportEntry(CryptoNative_SslUsePrivateKey) DllImportEntry(CryptoNative_SslV2_3Method) DllImportEntry(CryptoNative_SslWrite) DllImportEntry(CryptoNative_Tls13Supported) diff --git a/src/native/libs/System.Security.Cryptography.Native/opensslshim.h b/src/native/libs/System.Security.Cryptography.Native/opensslshim.h index daaa49da2869e..a64aac0c676e9 100644 --- a/src/native/libs/System.Security.Cryptography.Native/opensslshim.h +++ b/src/native/libs/System.Security.Cryptography.Native/opensslshim.h @@ -270,6 +270,7 @@ const EVP_CIPHER* EVP_chacha20_poly1305(void); LEGACY_FUNCTION(ERR_load_crypto_strings) \ LIGHTUP_FUNCTION(ERR_new) \ REQUIRED_FUNCTION(ERR_peek_error) \ + REQUIRED_FUNCTION(ERR_peek_error_line) \ REQUIRED_FUNCTION(ERR_peek_last_error) \ FALLBACK_FUNCTION(ERR_put_error) \ REQUIRED_FUNCTION(ERR_reason_error_string) \ @@ -503,6 +504,7 @@ const EVP_CIPHER* EVP_chacha20_poly1305(void); FALLBACK_FUNCTION(SSL_session_reused) \ REQUIRED_FUNCTION(SSL_set_accept_state) \ REQUIRED_FUNCTION(SSL_set_bio) \ + REQUIRED_FUNCTION(SSL_set_cert_cb) \ REQUIRED_FUNCTION(SSL_set_cipher_list) \ LIGHTUP_FUNCTION(SSL_set_ciphersuites) \ REQUIRED_FUNCTION(SSL_set_connect_state) \ @@ -514,6 +516,8 @@ const EVP_CIPHER* EVP_chacha20_poly1305(void); LEGACY_FUNCTION(SSLeay) \ RENAMED_FUNCTION(TLS_method, SSLv23_method) \ REQUIRED_FUNCTION(SSL_write) \ + REQUIRED_FUNCTION(SSL_use_certificate) \ + REQUIRED_FUNCTION(SSL_use_PrivateKey) \ FALLBACK_FUNCTION(X509_check_host) \ REQUIRED_FUNCTION(X509_check_purpose) \ REQUIRED_FUNCTION(X509_cmp_current_time) \ @@ -725,6 +729,7 @@ FOR_ALL_OPENSSL_FUNCTIONS #define ERR_load_crypto_strings ERR_load_crypto_strings_ptr #define ERR_new ERR_new_ptr #define ERR_peek_error ERR_peek_error_ptr +#define ERR_peek_error_line ERR_peek_error_line_ptr #define ERR_peek_last_error ERR_peek_last_error_ptr #define ERR_put_error ERR_put_error_ptr #define ERR_reason_error_string ERR_reason_error_string_ptr @@ -961,6 +966,7 @@ FOR_ALL_OPENSSL_FUNCTIONS #define SSL_session_reused SSL_session_reused_ptr #define SSL_set_accept_state SSL_set_accept_state_ptr #define SSL_set_bio SSL_set_bio_ptr +#define SSL_set_cert_cb SSL_set_cert_cb_ptr #define SSL_set_cipher_list SSL_set_cipher_list_ptr #define SSL_set_ciphersuites SSL_set_ciphersuites_ptr #define SSL_set_connect_state SSL_set_connect_state_ptr @@ -971,6 +977,8 @@ FOR_ALL_OPENSSL_FUNCTIONS #define SSL_state SSL_state_ptr #define SSLeay SSLeay_ptr #define SSL_write SSL_write_ptr +#define SSL_use_certificate SSL_use_certificate_ptr +#define SSL_use_PrivateKey SSL_use_PrivateKey_ptr #define TLS_method TLS_method_ptr #define X509_check_host X509_check_host_ptr #define X509_check_purpose X509_check_purpose_ptr diff --git a/src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.c b/src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.c index 6839d4c2fe04e..79de386f09721 100644 --- a/src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.c +++ b/src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.c @@ -152,20 +152,59 @@ EVP_PKEY* CryptoNative_DecodePkcs8PrivateKey(const uint8_t* buf, int32_t len, in return key; } -int32_t CryptoNative_GetPkcs8PrivateKeySize(EVP_PKEY* pkey) +int32_t CryptoNative_GetPkcs8PrivateKeySize(EVP_PKEY* pkey, int32_t* p8size) { assert(pkey != NULL); + assert(p8size != NULL); + + *p8size = 0; + ERR_clear_error(); PKCS8_PRIV_KEY_INFO* p8 = EVP_PKEY2PKCS8(pkey); if (p8 == NULL) { + // OpenSSL 1.1 and 3 have a behavioral change with EVP_PKEY2PKCS8 + // with regard to handling EVP_PKEYs that do not contain a private key. + // + // In OpenSSL 1.1, it would always succeed, but the private parameters + // would be missing (thus making an invalid PKCS8 structure). + // Over in the managed side, we detect these invalid PKCS8 blobs and + // convert that to a "no private key" error. + // + // In OpenSSL 3, this now correctly errors, with the error + // ASN1_R_ILLEGAL_ZERO_CONTENT. We want to preserve allocation failures + // as OutOfMemoryException. So we peek at the error. If it's a malloc + // failure, -1 is returned to indcate "throw what is on the error queue". + // If the error is not a malloc failure, return -2 to mean "no private key". + // If OpenSSL ever changes the error to something more to explicitly mean + // "no private key" then we should test for that explicitly. Until then, + // we treat all errors, except a malloc error, to mean "no private key". + + const char* file = NULL; + int line = 0; + unsigned long error = ERR_peek_error_line(&file, &line); + + // If it's not a malloc failure, assume it's because the private key is + // missing. + if (ERR_GET_REASON(error) != ERR_R_MALLOC_FAILURE) + { + ERR_clear_error(); + return -2; + } + + // It is a malloc failure. Clear the error queue and set the error + // as a malloc error so it's the only error in the queue. + ERR_clear_error(); + ERR_put_error(ERR_GET_LIB(error), 0, ERR_R_MALLOC_FAILURE, file, line); + return -1; } - int ret = i2d_PKCS8_PRIV_KEY_INFO(p8, NULL); + *p8size = i2d_PKCS8_PRIV_KEY_INFO(p8, NULL); PKCS8_PRIV_KEY_INFO_free(p8); - return ret; + + return *p8size < 0 ? -1 : 1; } int32_t CryptoNative_EncodePkcs8PrivateKey(EVP_PKEY* pkey, uint8_t* buf) diff --git a/src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.h b/src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.h index 012ac98e03db2..fac7ee32b5bbc 100644 --- a/src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.h +++ b/src/native/libs/System.Security.Cryptography.Native/pal_evp_pkey.h @@ -58,9 +58,13 @@ Requres a non-null buf, and len > 0. PALEXPORT EVP_PKEY* CryptoNative_DecodePkcs8PrivateKey(const uint8_t* buf, int32_t len, int32_t algId); /* -Reports the number of bytes rqeuired to encode an EVP_PKEY* as a Pkcs8PrivateKeyInfo, or a negative value on error. +Gets the number of bytes rqeuired to encode an EVP_PKEY* as a Pkcs8PrivateKeyInfo. + +On success, 1 is returned and p8size contains the size of the Pkcs8PrivateKeyInfo. +On failure, -1 is used to indicate the openssl error queue contains the error. +On failure, -2 is used to indcate that the supplied EVP_PKEY* is possibly missing a private key. */ -PALEXPORT int32_t CryptoNative_GetPkcs8PrivateKeySize(EVP_PKEY* pkey); +PALEXPORT int32_t CryptoNative_GetPkcs8PrivateKeySize(EVP_PKEY* pkey, int32_t* p8size); /* Encodes the EVP_PKEY* as a Pkcs8PrivateKeyInfo, writing the encoded value to buf. diff --git a/src/native/libs/System.Security.Cryptography.Native/pal_ssl.c b/src/native/libs/System.Security.Cryptography.Native/pal_ssl.c index d6797af5654a6..b49ca41b1895d 100644 --- a/src/native/libs/System.Security.Cryptography.Native/pal_ssl.c +++ b/src/native/libs/System.Security.Cryptography.Native/pal_ssl.c @@ -433,6 +433,16 @@ X509Stack* CryptoNative_SslGetPeerCertChain(SSL* ssl) return SSL_get_peer_cert_chain(ssl); } +int32_t CryptoNative_SslUseCertificate(SSL* ssl, X509* x) +{ + return SSL_use_certificate(ssl, x); +} + +int32_t CryptoNative_SslUsePrivateKey(SSL* ssl, EVP_PKEY* pkey) +{ + return SSL_use_PrivateKey(ssl, pkey); +} + int32_t CryptoNative_SslCtxUseCertificate(SSL_CTX* ctx, X509* x) { return SSL_CTX_use_certificate(ctx, x); @@ -633,6 +643,21 @@ int32_t CryptoNative_SslCtxAddExtraChainCert(SSL_CTX* ctx, X509* x509) return 0; } +int32_t CryptoNative_SslAddExtraChainCert(SSL* ssl, X509* x509) +{ + if (!x509 || !ssl) + { + return 0; + } + + if (SSL_ctrl(ssl, SSL_CTRL_CHAIN_CERT, 1,(void*)x509) == 1) + { + return 1; + } + + return 0; +} + void CryptoNative_SslCtxSetAlpnSelectCb(SSL_CTX* ctx, SslCtxSetAlpnCallback cb, void* arg) { #if HAVE_OPENSSL_ALPN @@ -648,6 +673,19 @@ void CryptoNative_SslCtxSetAlpnSelectCb(SSL_CTX* ctx, SslCtxSetAlpnCallback cb, #endif } +static int client_certificate_cb(SSL *ssl, void* state) +{ + (void*)ssl; + (void*)state; + // if we return negative number handshake will pause with SSL_ERROR_WANT_X509_LOOKUP + return -1; +} + +void CryptoNative_SslSetClientCertCallback(SSL* ssl, int set) +{ + SSL_set_cert_cb(ssl, set ? client_certificate_cb : NULL, NULL); +} + int32_t CryptoNative_SslSetData(SSL* ssl, void *ptr) { return SSL_set_ex_data(ssl, 0, ptr); @@ -655,7 +693,6 @@ int32_t CryptoNative_SslSetData(SSL* ssl, void *ptr) void* CryptoNative_SslGetData(SSL* ssl) { -// void* data = SSL_get_ex_data(ssl, 0, ptr); return SSL_get_ex_data(ssl, 0); } diff --git a/src/native/libs/System.Security.Cryptography.Native/pal_ssl.h b/src/native/libs/System.Security.Cryptography.Native/pal_ssl.h index 02a8ce973cf30..faf96988b1b50 100644 --- a/src/native/libs/System.Security.Cryptography.Native/pal_ssl.h +++ b/src/native/libs/System.Security.Cryptography.Native/pal_ssl.h @@ -142,6 +142,12 @@ Sets the specified protocols in the SSL_CTX options. PALEXPORT void CryptoNative_SslCtxSetProtocolOptions(SSL_CTX* ctx, SslProtocols protocols); /* +Sets internal callback for client certificate selection is set is positive. +It will unset callback if set is zero. +*/ +PALEXPORT void CryptoNative_SslSetClientCertCallback(SSL* ssl, int set); + +/*======= Sets session caching. 0 is disabled. */ PALEXPORT void CryptoNative_SslCtxSetCaching(SSL_CTX* ctx, int mode); @@ -276,6 +282,22 @@ Returns the certificate chain presented by the peer. */ PALEXPORT X509Stack* CryptoNative_SslGetPeerCertChain(SSL* ssl); +/* +Shims the SSL_use_certificate method. + +Returns 1 upon success, otherwise 0. +*/ +PALEXPORT int32_t CryptoNative_SslUseCertificate(SSL* ssl, X509* x); + +/* +Shims the SSL_use_PrivateKey method. + +Returns 1 upon success, otherwise 0. +*/ +PALEXPORT int32_t CryptoNative_SslUsePrivateKey(SSL* ssl, EVP_PKEY* pkey); + + + /* Shims the SSL_CTX_use_certificate method. @@ -363,13 +385,21 @@ Shims the SSL_session_reused macro. PALEXPORT int32_t CryptoNative_SslSessionReused(SSL* ssl); /* -adds the given certificate to the extra chain certificates associated with ctx. +Adds the given certificate to the extra chain certificates associated with ctx. libssl frees the x509 object. Returns 1 if success and 0 in case of failure */ PALEXPORT int32_t CryptoNative_SslCtxAddExtraChainCert(SSL_CTX* ctx, X509* x509); +/* +Adds the given certificate to the extra chain certificates associated with ssl state. + +libssl frees the x509 object. +Returns 1 if success and 0 in case of failure +*/ +PALEXPORT int32_t CryptoNative_SslAddExtraChainCert(SSL* ssl, X509* x509); + /* Shims the ssl_ctx_set_alpn_select_cb method. */ diff --git a/src/native/libs/build-native.sh b/src/native/libs/build-native.sh index d40399da0e12d..04e5ab7d62cd9 100755 --- a/src/native/libs/build-native.sh +++ b/src/native/libs/build-native.sh @@ -70,14 +70,7 @@ else fi fi -if [[ "$__TargetOS" == OSX ]]; then - # set default OSX deployment target - if [[ "$__BuildArch" == x64 ]]; then - __CMakeArgs="-DCMAKE_OSX_DEPLOYMENT_TARGET=10.13 $__CMakeArgs" - else - __CMakeArgs="-DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 $__CMakeArgs" - fi -elif [[ "$__TargetOS" == Android && -z "$ROOTFS_DIR" ]]; then +if [[ "$__TargetOS" == Android && -z "$ROOTFS_DIR" ]]; then # Android SDK defaults to c++_static; we only need C support __CMakeArgs="-DANDROID_STL=none $__CMakeArgs" elif [[ "$__TargetOS" == iOSSimulator ]]; then diff --git a/src/native/libs/configure.cmake b/src/native/libs/configure.cmake index 7b92afa7b0ae2..74f6910012a05 100644 --- a/src/native/libs/configure.cmake +++ b/src/native/libs/configure.cmake @@ -7,6 +7,7 @@ include(CheckStructHasMember) include(CheckSymbolExists) include(CheckTypeSize) include(CheckLibraryExists) +include(CheckFunctionExists) # CMP0075 Include file check macros honor CMAKE_REQUIRED_LIBRARIES. if(POLICY CMP0075) @@ -144,6 +145,18 @@ check_c_source_compiles( " HAVE_FLOCK64) +check_c_source_compiles( + " + #include + #include + int main(void) + { + struct ifaddrs ia; + return 0; + } + " + HAVE_IFADDRS) + check_symbol_exists( O_CLOEXEC fcntl.h @@ -159,9 +172,8 @@ check_symbol_exists( fcntl.h HAVE_F_FULLFSYNC) -check_symbol_exists( +check_function_exists( getifaddrs - ifaddrs.h HAVE_GETIFADDRS) check_symbol_exists( diff --git a/src/tasks/AndroidAppBuilder/ApkBuilder.cs b/src/tasks/AndroidAppBuilder/ApkBuilder.cs index 84d3490668098..d11c8da8b7971 100644 --- a/src/tasks/AndroidAppBuilder/ApkBuilder.cs +++ b/src/tasks/AndroidAppBuilder/ApkBuilder.cs @@ -503,7 +503,7 @@ public void ReplaceFileInApk(string file) string aapt = Path.Combine(buildToolsFolder, "aapt"); string apksigner = Path.Combine(buildToolsFolder, "apksigner"); - string apkPath = ""; + string apkPath; if (string.IsNullOrEmpty(ProjectName)) apkPath = Directory.GetFiles(Path.Combine(OutputDir, "bin"), "*.apk").First(); else diff --git a/src/tasks/Crossgen2Tasks/ResolveReadyToRunCompilers.cs b/src/tasks/Crossgen2Tasks/ResolveReadyToRunCompilers.cs index 8c3e602ae7725..ddc44ccb782fa 100644 --- a/src/tasks/Crossgen2Tasks/ResolveReadyToRunCompilers.cs +++ b/src/tasks/Crossgen2Tasks/ResolveReadyToRunCompilers.cs @@ -112,7 +112,7 @@ private bool ValidateCrossgenSupport() } if (!ExtractTargetPlatformAndArchitecture(_targetRuntimeIdentifier, out _targetPlatform, out _targetArchitecture) || - !ExtractTargetPlatformAndArchitecture(_hostRuntimeIdentifier, out string hostPlatform, out Architecture hostArchitecture) || + !ExtractTargetPlatformAndArchitecture(_hostRuntimeIdentifier, out string hostPlatform, out _) || _targetPlatform != hostPlatform || !GetCrossgenComponentsPaths()) { diff --git a/src/tasks/WasmAppBuilder/IcallTableGenerator.cs b/src/tasks/WasmAppBuilder/IcallTableGenerator.cs index 08a560aa37bf3..fd8eb70839f4d 100644 --- a/src/tasks/WasmAppBuilder/IcallTableGenerator.cs +++ b/src/tasks/WasmAppBuilder/IcallTableGenerator.cs @@ -274,7 +274,6 @@ private static string GenIcallDecl (Icall icall) var method = icall.Method!; sb.Append (MapType (method.ReturnType)); sb.Append ($" {icall.Func} ("); - int pindex = 0; int aindex = 0; if (!method.IsStatic) { @@ -286,7 +285,6 @@ private static string GenIcallDecl (Icall icall) if (aindex > 0) sb.Append (','); sb.Append (MapType (p.ParameterType)); - pindex++; aindex++; } if (icall.Handles) @@ -294,7 +292,6 @@ private static string GenIcallDecl (Icall icall) if (aindex > 0) sb.Append (','); sb.Append ("int"); - pindex++; } sb.Append (");"); return sb.ToString (); diff --git a/src/tasks/installer.tasks/GenerateRunScript.cs b/src/tasks/installer.tasks/GenerateRunScript.cs index 142ac7c996fbd..e363810fe1de3 100644 --- a/src/tasks/installer.tasks/GenerateRunScript.cs +++ b/src/tasks/installer.tasks/GenerateRunScript.cs @@ -121,8 +121,6 @@ private static string SanitizeEcho(string command, bool isUnix){ // Escape backtick and question mark characters to avoid running commands instead of echo'ing them. string sanitizedRunCommand = command.Replace("`", "\\`") .Replace("?", "\\") - .Replace("$", "") - .Replace("%", "") .Replace("\r","") .Replace("\n"," ") .Replace("&", "^&") @@ -138,4 +136,4 @@ private static string SanitizeEcho(string command, bool isUnix){ return sanitizedRunCommand; } } -} \ No newline at end of file +} diff --git a/src/tests/Common/XUnitWrapperGenerator/ITestInfo.cs b/src/tests/Common/XUnitWrapperGenerator/ITestInfo.cs index 0e9a1822c737d..b8aa63cba15fe 100644 --- a/src/tests/Common/XUnitWrapperGenerator/ITestInfo.cs +++ b/src/tests/Common/XUnitWrapperGenerator/ITestInfo.cs @@ -314,13 +314,15 @@ sealed class NoTestReporting : ITestReporterWrapper sealed class WrapperLibraryTestSummaryReporting : ITestReporterWrapper { - private string _summaryLocalIdentifier; + private readonly string _summaryLocalIdentifier; private readonly string _filterLocalIdentifier; + private readonly string _outputRecorderIdentifier; - public WrapperLibraryTestSummaryReporting(string summaryLocalIdentifier, string filterLocalIdentifier) + public WrapperLibraryTestSummaryReporting(string summaryLocalIdentifier, string filterLocalIdentifier, string outputRecorderIdentifier) { _summaryLocalIdentifier = summaryLocalIdentifier; _filterLocalIdentifier = filterLocalIdentifier; + _outputRecorderIdentifier = outputRecorderIdentifier; } public string WrapTestExecutionWithReporting(string testExecutionExpression, ITestInfo test) @@ -332,12 +334,13 @@ public string WrapTestExecutionWithReporting(string testExecutionExpression, ITe builder.AppendLine($"System.TimeSpan testStart = stopwatch.Elapsed;"); builder.AppendLine("try {"); builder.AppendLine($"System.Console.WriteLine(\"Running test: {{0}}\", {test.TestNameExpression});"); + builder.AppendLine($"{_outputRecorderIdentifier}.ResetTestOutput();"); builder.AppendLine(testExecutionExpression); - builder.AppendLine($"{_summaryLocalIdentifier}.ReportPassedTest({test.TestNameExpression}, \"{test.ContainingType}\", @\"{test.Method}\", stopwatch.Elapsed - testStart);"); + builder.AppendLine($"{_summaryLocalIdentifier}.ReportPassedTest({test.TestNameExpression}, \"{test.ContainingType}\", @\"{test.Method}\", stopwatch.Elapsed - testStart, {_outputRecorderIdentifier}.GetTestOutput());"); builder.AppendLine($"System.Console.WriteLine(\"Passed test: {{0}}\", {test.TestNameExpression});"); builder.AppendLine("}"); builder.AppendLine("catch (System.Exception ex) {"); - builder.AppendLine($"{_summaryLocalIdentifier}.ReportFailedTest({test.TestNameExpression}, \"{test.ContainingType}\", @\"{test.Method}\", stopwatch.Elapsed - testStart, ex);"); + builder.AppendLine($"{_summaryLocalIdentifier}.ReportFailedTest({test.TestNameExpression}, \"{test.ContainingType}\", @\"{test.Method}\", stopwatch.Elapsed - testStart, ex, {_outputRecorderIdentifier}.GetTestOutput());"); builder.AppendLine($"System.Console.WriteLine(\"Failed test: {{0}}\", {test.TestNameExpression});"); builder.AppendLine("}"); diff --git a/src/tests/Common/XUnitWrapperGenerator/TestPlatforms.cs b/src/tests/Common/XUnitWrapperGenerator/TestPlatforms.cs index b84e9f250045e..a4f11204e48ba 100644 --- a/src/tests/Common/XUnitWrapperGenerator/TestPlatforms.cs +++ b/src/tests/Common/XUnitWrapperGenerator/TestPlatforms.cs @@ -20,7 +20,7 @@ public enum TestPlatforms Android = 512, Browser = 1024, MacCatalyst = 2048, - AnyUnix = FreeBSD | Linux | NetBSD | OSX | illumos | Solaris | iOS | tvOS | MacCatalyst | Android | Browser, + AnyUnix = FreeBSD | Linux | NetBSD | OSX | illumos | Solaris | iOS | tvOS | MacCatalyst | Android | Browser, Any = ~0 } } diff --git a/src/tests/Common/XUnitWrapperGenerator/XUnitWrapperGenerator.cs b/src/tests/Common/XUnitWrapperGenerator/XUnitWrapperGenerator.cs index 22bd59ab82952..eb4295c06cc33 100644 --- a/src/tests/Common/XUnitWrapperGenerator/XUnitWrapperGenerator.cs +++ b/src/tests/Common/XUnitWrapperGenerator/XUnitWrapperGenerator.cs @@ -151,12 +151,15 @@ private static string GenerateFullTestRunner(ImmutableArray testInfos { // For simplicity, we'll use top-level statements for the generated Main method. StringBuilder builder = new(); - ITestReporterWrapper reporter = new WrapperLibraryTestSummaryReporting("summary", "filter"); builder.AppendLine(string.Join("\n", aliasMap.Values.Where(alias => alias != "global").Select(alias => $"extern alias {alias};"))); builder.AppendLine("XUnitWrapperLibrary.TestFilter filter = args.Length != 0 ? new XUnitWrapperLibrary.TestFilter(args[0]) : null;"); builder.AppendLine("XUnitWrapperLibrary.TestSummary summary = new();"); builder.AppendLine("System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew();"); + builder.AppendLine("XUnitWrapperLibrary.TestOutputRecorder outputRecorder = new(System.Console.Out);"); + builder.AppendLine("System.Console.SetOut(outputRecorder);"); + + ITestReporterWrapper reporter = new WrapperLibraryTestSummaryReporting("summary", "filter", "outputRecorder"); foreach (ITestInfo test in testInfos) { @@ -175,7 +178,7 @@ private static string GenerateXHarnessTestRunner(ImmutableArray testI StringBuilder builder = new(); builder.AppendLine(string.Join("\n", aliasMap.Values.Where(alias => alias != "global").Select(alias => $"extern alias {alias};"))); - + builder.AppendLine("try {"); builder.AppendLine($@"return await XHarnessRunnerLibrary.RunnerEntryPoint.RunTests(RunTests, ""{assemblyName}"", args.Length != 0 ? args[0] : null);"); builder.AppendLine("} catch(System.Exception ex) { System.Console.WriteLine(ex.ToString()); return 101; }"); @@ -183,8 +186,11 @@ private static string GenerateXHarnessTestRunner(ImmutableArray testI builder.AppendLine("static XUnitWrapperLibrary.TestSummary RunTests(XUnitWrapperLibrary.TestFilter filter)"); builder.AppendLine("{"); builder.AppendLine("XUnitWrapperLibrary.TestSummary summary = new();"); - ITestReporterWrapper reporter = new WrapperLibraryTestSummaryReporting("summary", "filter"); builder.AppendLine("System.Diagnostics.Stopwatch stopwatch = new();"); + builder.AppendLine("XUnitWrapperLibrary.TestOutputRecorder outputRecorder = new(System.Console.Out);"); + builder.AppendLine("System.Console.SetOut(outputRecorder);"); + + ITestReporterWrapper reporter = new WrapperLibraryTestSummaryReporting("summary", "filter", "outputRecorder"); foreach (ITestInfo test in testInfos) { diff --git a/src/tests/Common/XUnitWrapperLibrary/TestOutputRecorder.cs b/src/tests/Common/XUnitWrapperLibrary/TestOutputRecorder.cs new file mode 100644 index 0000000000000..13b4c3d4ae52f --- /dev/null +++ b/src/tests/Common/XUnitWrapperLibrary/TestOutputRecorder.cs @@ -0,0 +1,34 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; + +namespace XUnitWrapperLibrary; + +public sealed class TestOutputRecorder : TextWriter +{ + private TextWriter _inner; + private ThreadLocal _testOutput = new(() => new StringBuilder()); + + public TestOutputRecorder(TextWriter inner) + { + _inner = inner; + } + + public override void Write(char value) + { + _inner.Write(value); + _testOutput.Value!.Append(value); + } + + public override Encoding Encoding => _inner.Encoding; + + public void ResetTestOutput() => _testOutput.Value!.Clear(); + + public string GetTestOutput() => _testOutput.Value!.ToString(); +} diff --git a/src/tests/Common/XUnitWrapperLibrary/TestSummary.cs b/src/tests/Common/XUnitWrapperLibrary/TestSummary.cs index 5c1180fe30be0..a2f23bad9bbf8 100644 --- a/src/tests/Common/XUnitWrapperLibrary/TestSummary.cs +++ b/src/tests/Common/XUnitWrapperLibrary/TestSummary.cs @@ -9,7 +9,7 @@ namespace XUnitWrapperLibrary; public class TestSummary { - readonly record struct TestResult(string Name, string ContainingTypeName, string MethodName, TimeSpan Duration, Exception? Exception, string? SkipReason); + readonly record struct TestResult(string Name, string ContainingTypeName, string MethodName, TimeSpan Duration, Exception? Exception, string? SkipReason, string? Output); public int PassedTests { get; private set; } = 0; public int FailedTests { get; private set; } = 0; @@ -19,22 +19,22 @@ public class TestSummary private DateTime _testRunStart = DateTime.Now; - public void ReportPassedTest(string name, string containingTypeName, string methodName, TimeSpan duration) + public void ReportPassedTest(string name, string containingTypeName, string methodName, TimeSpan duration, string output) { PassedTests++; - _testResults.Add(new TestResult(name, containingTypeName, methodName, duration, null, null)); + _testResults.Add(new TestResult(name, containingTypeName, methodName, duration, null, null, output)); } - public void ReportFailedTest(string name, string containingTypeName, string methodName, TimeSpan duration, Exception ex) + public void ReportFailedTest(string name, string containingTypeName, string methodName, TimeSpan duration, Exception ex, string output) { FailedTests++; - _testResults.Add(new TestResult(name, containingTypeName, methodName, duration, ex, null)); + _testResults.Add(new TestResult(name, containingTypeName, methodName, duration, ex, null, output)); } public void ReportSkippedTest(string name, string containingTypeName, string methodName, TimeSpan duration, string reason) { SkippedTests++; - _testResults.Add(new TestResult(name, containingTypeName, methodName, duration, null, reason)); + _testResults.Add(new TestResult(name, containingTypeName, methodName, duration, null, reason, null)); } public string GetTestResultOutput(string assemblyName) @@ -72,7 +72,7 @@ public string GetTestResultOutput(string assemblyName) resultsFile.Append($@""); + resultsFile.AppendLine($@"result=""Fail"">"); } else if (test.SkipReason is not null) { @@ -80,7 +80,7 @@ public string GetTestResultOutput(string assemblyName) } else { - resultsFile.AppendLine(@" result=""Pass"" />"); + resultsFile.AppendLine($@" result=""Pass"">"); } } diff --git a/src/tests/Common/testenvironment.proj b/src/tests/Common/testenvironment.proj index c8d6e0d31e59e..aae081a187126 100644 --- a/src/tests/Common/testenvironment.proj +++ b/src/tests/Common/testenvironment.proj @@ -62,6 +62,7 @@ COMPlus_JitEdgeProfiling; COMPlus_JitRandomGuardedDevirtualization; COMPlus_JitRandomEdgeCounts; + COMPlus_JitRandomOnStackReplacement; RunningIlasmRoundTrip @@ -187,6 +188,7 @@ + diff --git a/src/tests/GC/API/Frozen/Frozen.cs b/src/tests/GC/API/Frozen/Frozen.cs new file mode 100644 index 0000000000000..3a9ad49175064 --- /dev/null +++ b/src/tests/GC/API/Frozen/Frozen.cs @@ -0,0 +1,188 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace HelloFrozenSegment +{ + using System; + using System.Reflection; + using System.Runtime.InteropServices; + using System.Runtime.CompilerServices; + + struct FrozenSegment + { + IntPtr underlyingSegment; + IntPtr underlyingBuffer; + + public FrozenSegment(IntPtr underlyingSegment, IntPtr underlyingBuffer) + { + this.underlyingSegment = underlyingSegment; + this.underlyingBuffer = underlyingBuffer; + } + + public void Release() + { + GCHelpers.UnregisterFrozenSegment(this.underlyingSegment); + Marshal.FreeHGlobal(this.underlyingBuffer); + } + } + + internal static class GCHelpers + { + private static MethodInfo s_registerFrozenSegmentMethod; + private static MethodInfo s_unregisterFrozenSegmentMethod; + + private static MethodInfo RegisterFrozenSegmentMethod + { + get + { + if (s_registerFrozenSegmentMethod == null) + { + s_registerFrozenSegmentMethod = typeof(GC).GetMethod("_RegisterFrozenSegment", BindingFlags.NonPublic|BindingFlags.Static); + } + + return s_registerFrozenSegmentMethod; + } + } + + private static MethodInfo UnregisterFrozenSegmentMethod + { + get + { + if (s_unregisterFrozenSegmentMethod == null) + { + s_unregisterFrozenSegmentMethod = typeof(GC).GetMethod("_UnregisterFrozenSegment", BindingFlags.NonPublic|BindingFlags.Static); + } + + return s_unregisterFrozenSegmentMethod; + } + } + + public static IntPtr RegisterFrozenSegment(IntPtr buffer, nint size) + { + return (IntPtr)RegisterFrozenSegmentMethod.Invoke(null, new object[]{buffer, size}); + + } + + public static void UnregisterFrozenSegment(IntPtr segment) + { + UnregisterFrozenSegmentMethod.Invoke(null, new object[]{segment}); + } + } + + internal unsafe class FrozenSegmentBuilder + { + private IntPtr _buffer; + private IntPtr _allocated; + private IntPtr _limit; + + // This only work for BaseSize (i.e. not arrays) + private static unsafe short GetObjectSize(IntPtr methodTable) + { + IntPtr pointerToSize = methodTable + 4; + return *((short*)pointerToSize); + } + + public FrozenSegmentBuilder(int capacity) + { + _buffer = Marshal.AllocHGlobal(capacity); + for (int i = 0; i < capacity; i++) + { + *((byte*)(_buffer + i)) = 0; + } + _allocated = _buffer + IntPtr.Size; + _limit = _buffer + capacity; + } + + public IntPtr Allocate(IntPtr methodTable) + { + if (_allocated == IntPtr.Zero) + { + throw new Exception("Segment already built"); + } + int objectSize = GetObjectSize(methodTable); + if ((_allocated + objectSize).CompareTo(_limit) > 0) + { + throw new Exception("OutOfCapacity"); + } + + IntPtr* pMethodTable = (IntPtr*)_allocated; + *pMethodTable = methodTable; + IntPtr result = _allocated; + _allocated = _allocated + objectSize; + return result; + } + + public FrozenSegment GetSegment() + { + if (_allocated == IntPtr.Zero) + { + throw new Exception("Segment already built"); + } + + nint size = (nint)(_allocated.ToInt64() - _buffer.ToInt64()); + _allocated = IntPtr.Zero; + IntPtr segment = GCHelpers.RegisterFrozenSegment(_buffer, size); + return new FrozenSegment(segment, _buffer); + } + } + + internal class Node + { + public Node next; + public int number; + } + + internal static class Program + { + private static unsafe IntPtr GetMethodTablePointer(object obj) + { + GCHandle gch = GCHandle.Alloc(obj); + IntPtr pointerToPointerToObject = GCHandle.ToIntPtr(gch); + IntPtr pointerToObject = *((IntPtr*)pointerToPointerToObject); + IntPtr methodTable = *((IntPtr*)pointerToObject); + gch.Free(); + return methodTable; + } + + private static unsafe int Main(string[] args) + { + Node template = new Node(); + IntPtr methodTable = GetMethodTablePointer(template); + + FrozenSegmentBuilder frozenSegmentBuilder = new FrozenSegmentBuilder(1000); + IntPtr node1Ptr = frozenSegmentBuilder.Allocate(methodTable); + IntPtr node2Ptr = frozenSegmentBuilder.Allocate(methodTable); + + FrozenSegment frozenSegment = frozenSegmentBuilder.GetSegment(); + Node root = new Node(); + Node node1 = Unsafe.AsRef((void*)&node1Ptr); + Node node2 = Unsafe.AsRef((void*)&node2Ptr); + // It is okay for any object to reference a frozen object. + root.next = node1; + + // It is not okay for a frozen object to reference another frozen object + // This is because the WriteBarrier code may (depending on the pointer + // value returned by AllocHGlobal) determine node2 to be an ephemeral object + // when it isn't. + // node1.next = node2; + + // It is not okay for a frozen object to reference another object that is not frozen + // This is because we may miss the marking of the new Node or miss the relocation + // of the new Node. + // node2.next = new Node(); + + // Making changes to non-GC references is fine + node1.number = 10086; + node2.number = 12580; + + GC.Collect(); + node1 = null; + GC.Collect(); + node2 = null; + GC.Collect(); + Console.WriteLine(root.next.next != null); + frozenSegment.Release(); + return 100; + } + } +} diff --git a/src/tests/GC/API/Frozen/Frozen.csproj b/src/tests/GC/API/Frozen/Frozen.csproj new file mode 100644 index 0000000000000..365f9ae36ae06 --- /dev/null +++ b/src/tests/GC/API/Frozen/Frozen.csproj @@ -0,0 +1,16 @@ + + + Exe + true + 1 + true + true + + + + PdbOnly + + + + + diff --git a/src/tests/Interop/COM/NativeClients/windows_version_helpers.h b/src/tests/Interop/COM/NativeClients/windows_version_helpers.h index b51c2f7f84efe..97d1e946e84bb 100644 --- a/src/tests/Interop/COM/NativeClients/windows_version_helpers.h +++ b/src/tests/Interop/COM/NativeClients/windows_version_helpers.h @@ -23,7 +23,7 @@ inline HRESULT is_windows_nano() osVersionInfo.wServicePackMinor, &productKind)) { - return HRESULT_FROM_WIN32(GetLastError()); + return E_FAIL; } if (productKind == PRODUCT_IOTUAP) @@ -31,33 +31,40 @@ inline HRESULT is_windows_nano() return S_FALSE; } + LSTATUS err; DWORD dataSize; DWORD type; - if (!RegGetValueW(HKEY_LOCAL_MACHINE, + err = RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"InstallationType", RRF_RT_REG_SZ, &type, nullptr, - &dataSize) - || type != REG_SZ) + &dataSize); + if (err != ERROR_SUCCESS) { - return HRESULT_FROM_WIN32(GetLastError()); + return HRESULT_FROM_WIN32(err); + } + if (type != REG_SZ) + { + return S_FALSE; } LPWSTR installationType = new WCHAR[dataSize + 1]; - - if (!RegGetValueW(HKEY_LOCAL_MACHINE, + err = RegGetValueW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"InstallationType", RRF_RT_REG_SZ, &type, installationType, - &dataSize) - || type != REG_SZ) + &dataSize); + if (err != ERROR_SUCCESS || type != REG_SZ) { delete[] installationType; - return HRESULT_FROM_WIN32(GetLastError()); + if (err == ERROR_SUCCESS) + return S_FALSE; + + return HRESULT_FROM_WIN32(err); } bool isNano = _wcsnicmp(L"Nano Server", installationType, dataSize + 1) == 0; diff --git a/src/tests/Interop/PInvoke/BestFitMapping/Test.cs b/src/tests/Interop/PInvoke/BestFitMapping/Test.cs index 936ebecd45d3e..4c507185744b3 100644 --- a/src/tests/Interop/PInvoke/BestFitMapping/Test.cs +++ b/src/tests/Interop/PInvoke/BestFitMapping/Test.cs @@ -38,13 +38,13 @@ public static void Validate(bool bestFitMapping, bool throwOnUnmappableCha T invalid = data.Invalid; if (shouldThrowOnInvalid) { - Assert.Throws(() => funcs.In(invalid)); + Assert.Throws(() => funcs.In(invalid)); invalid = data.Invalid; - Assert.Throws(() => funcs.InByRef(ref invalid)); + Assert.Throws(() => funcs.InByRef(ref invalid)); invalid = data.Invalid; - Assert.Throws(() => funcs.InOutByRef(ref invalid)); + Assert.Throws(() => funcs.InOutByRef(ref invalid)); } else { diff --git a/src/tests/Interop/UnmanagedCallersOnly/InvalidCallbacks.il b/src/tests/Interop/UnmanagedCallersOnly/InvalidCallbacks.il index f1afc64eb7ac9..4c7826650dcb8 100644 --- a/src/tests/Interop/UnmanagedCallersOnly/InvalidCallbacks.il +++ b/src/tests/Interop/UnmanagedCallersOnly/InvalidCallbacks.il @@ -15,59 +15,59 @@ .class public auto ansi beforefieldinit InvalidCSharp.GenericClass`1 extends [System.Runtime]System.Object { - .method public hidebysig static + .method public hidebysig static int32 CallbackMethod ( int32 n - ) cil managed preservesig + ) cil managed preservesig { .custom instance void [System.Runtime.InteropServices]System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 - IL_0000: ldstr "Functions with attribute UnmanagedCallersOnlyAttribute within a generic type are invalid" - IL_0005: newobj instance void [System.Runtime]System.Exception::.ctor(string) - IL_000a: throw + ldstr "Functions with attribute UnmanagedCallersOnlyAttribute within a generic type are invalid" + newobj instance void [System.Runtime]System.Exception::.ctor(string) + throw } - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { .maxstack 8 - IL_0000: ldarg.0 - IL_0001: call instance void [System.Runtime]System.Object::.ctor() - IL_0006: ret + ldarg.0 + call instance void [System.Runtime]System.Object::.ctor() + ret } } .class public auto ansi beforefieldinit InvalidCSharp.Callbacks extends [System.Runtime]System.Object { - .method public hidebysig static + .method public hidebysig static int32 CallbackMethodGeneric ( !!T arg - ) cil managed preservesig + ) cil managed preservesig { .custom instance void [System.Runtime.InteropServices]System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 - IL_0000: ldstr "Functions with attribute UnmanagedCallersOnlyAttribute cannot have generic arguments" - IL_0005: newobj instance void [System.Runtime]System.Exception::.ctor(string) - IL_000a: throw + ldstr "Functions with attribute UnmanagedCallersOnlyAttribute cannot have generic arguments" + newobj instance void [System.Runtime]System.Exception::.ctor(string) + throw } - .method public hidebysig + .method public hidebysig instance int32 CallbackNonStatic ( int32 val - ) cil managed preservesig + ) cil managed preservesig { .custom instance void [System.Runtime.InteropServices]System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 8 - IL_0000: ldstr "Instance functions with attribute UnmanagedCallersOnlyAttribute are invalid" - IL_0005: newobj instance void [System.Runtime]System.Exception::.ctor(string) - IL_000a: throw + ldstr "Instance functions with attribute UnmanagedCallersOnlyAttribute are invalid" + newobj instance void [System.Runtime]System.Exception::.ctor(string) + throw } .method public hidebysig static @@ -79,87 +79,73 @@ ret } - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { .maxstack 8 - IL_0000: ldarg.0 - IL_0001: call instance void [System.Runtime]System.Object::.ctor() - IL_0006: ret + ldarg.0 + call instance void [System.Runtime]System.Object::.ctor() + ret } } .class public auto ansi beforefieldinit InvalidCSharp.CallingUnmanagedCallersOnlyDirectly extends [System.Runtime]System.Object { - .method public hidebysig specialname rtspecialname - instance void .ctor () cil managed + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed { .maxstack 8 - IL_0000: ldarg.0 - IL_0001: call instance void [System.Runtime]System.Object::.ctor() - IL_0006: ret + ldarg.0 + call instance void [System.Runtime]System.Object::.ctor() + ret } - - .method public hidebysig static - int32 ManagedDoubleCallback ( - int32 n - ) cil managed + + .method public hidebysig static + int32 ManagedDoubleCallback ( + int32 n + ) cil managed { .custom instance void [System.Runtime.InteropServices]System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 1 - .locals init ( - [0] int32 - ) - - IL_0000: nop - IL_0001: ldarg.0 - IL_0002: call int32 InvalidCSharp.CallingUnmanagedCallersOnlyDirectly::DoubleImpl(int32) - IL_0007: stloc.0 - IL_0008: br.s IL_000a - IL_000a: ldloc.0 - IL_000b: ret + nop + ldarg.0 + call int32 InvalidCSharp.CallingUnmanagedCallersOnlyDirectly::DoubleImpl(int32) + ret } - - .method private hidebysig static + + .method private hidebysig static int32 DoubleImpl ( int32 n - ) cil managed + ) cil managed { .maxstack 2 - .locals init ( - [0] int32 - ) - - IL_0000: nop - IL_0001: ldc.i4.2 - IL_0002: ldarg.0 - IL_0003: mul - IL_0004: stloc.0 - IL_0005: br.s IL_0007 - IL_0007: ldloc.0 - IL_0008: ret + nop + ldc.i4.2 + ldarg.0 + mul + ret } - .method public hidebysig static - class [System.Runtime]System.Func`2 GetDoubleDelegate () cil managed + .method public hidebysig static + class [System.Runtime]System.Func`2 GetDoubleDelegate () cil managed { .maxstack 8 - IL_0000: ldnull - IL_0001: ldftn int32 InvalidCSharp.CallingUnmanagedCallersOnlyDirectly::ManagedDoubleCallback(int32) - IL_0007: newobj instance void class [System.Runtime]System.Func`2::.ctor(object, native int) - IL_000c: ret + ldnull + ldftn int32 InvalidCSharp.CallingUnmanagedCallersOnlyDirectly::ManagedDoubleCallback(int32) + newobj instance void class [System.Runtime]System.Func`2::.ctor(object, native int) + ret } - .method public hidebysig static pinvokeimpl("UnmanagedCallersOnlyDll" as "DoesntExist" winapi) - int32 PInvokeMarkedWithUnmanagedCallersOnly ( - int32 n - ) cil managed preservesig + .method public hidebysig static pinvokeimpl("UnmanagedCallersOnlyDll" as "DoesntExist" winapi) + int32 PInvokeMarkedWithUnmanagedCallersOnly ( + int32 n + ) cil managed preservesig { .custom instance void [System.Runtime.InteropServices]System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 @@ -177,4 +163,81 @@ call int32 InvalidCSharp.CallingUnmanagedCallersOnlyDirectly::PInvokeMarkedWithUnmanagedCallersOnly(int32) ret } +} + +.class public auto ansi beforefieldinit InvalidCSharp.UnmanagedCallersOnlyWithByRefs + extends [System.Runtime]System.Object +{ + .method private hidebysig static + int32 WithByRef ( + int32& val + ) cil managed + { + .custom instance void [System.Runtime.InteropServices]System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( + 01 00 00 00 + ) + .maxstack 8 + ldstr "Functions with by-ref and attribute UnmanagedCallersOnlyAttribute are invalid" + newobj instance void [System.Runtime]System.Exception::.ctor(string) + throw + } + .method public hidebysig static + native int GetWithByRefFunctionPointer ( + ) cil managed preservesig + { + .maxstack 8 + ldftn int32 InvalidCSharp.UnmanagedCallersOnlyWithByRefs::WithByRef(int32&) + ret + } + .method private hidebysig static + int32 WithByRefIn ( + [in] int32& val + ) cil managed + { + .custom instance void [System.Runtime.InteropServices]System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( + 01 00 00 00 + ) + .maxstack 8 + ldstr "Functions with 'in' by-ref and attribute UnmanagedCallersOnlyAttribute are invalid" + newobj instance void [System.Runtime]System.Exception::.ctor(string) + throw + } + .method public hidebysig static + native int GetWithByRefInFunctionPointer ( + ) cil managed preservesig + { + .maxstack 8 + ldftn int32 InvalidCSharp.UnmanagedCallersOnlyWithByRefs::WithByRefIn([in] int32&) + ret + } + .method private hidebysig static + int32 WithByRefOut ( + [out] int32& val + ) cil managed + { + .custom instance void [System.Runtime.InteropServices]System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( + 01 00 00 00 + ) + .maxstack 8 + ldstr "Functions with 'out' by-ref and attribute UnmanagedCallersOnlyAttribute are invalid" + newobj instance void [System.Runtime]System.Exception::.ctor(string) + throw + } + .method public hidebysig static + native int GetWithByRefOutFunctionPointer ( + ) cil managed preservesig + { + .maxstack 8 + ldftn int32 InvalidCSharp.UnmanagedCallersOnlyWithByRefs::WithByRefOut([out] int32&) + ret + } + + .method public hidebysig specialname rtspecialname + instance void .ctor () cil managed + { + .maxstack 8 + ldarg.0 + call instance void [System.Runtime]System.Object::.ctor() + ret + } } \ No newline at end of file diff --git a/src/tests/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest.cs b/src/tests/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest.cs index 5911af405e3f7..f67c8b67270ed 100644 --- a/src/tests/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest.cs +++ b/src/tests/Interop/UnmanagedCallersOnly/UnmanagedCallersOnlyTest.cs @@ -205,6 +205,9 @@ public static void NegativeTest_NonBlittable() int n = 12345; // Try invoking method Assert.Throws(() => { UnmanagedCallersOnlyDll.CallManagedProc((IntPtr)(delegate* unmanaged)&CallbackMethodNonBlittable, n); }); + Assert.Throws(() => { UnmanagedCallersOnlyDll.CallManagedProc(UnmanagedCallersOnlyWithByRefs.GetWithByRefFunctionPointer(), n); }); + Assert.Throws(() => { UnmanagedCallersOnlyDll.CallManagedProc(UnmanagedCallersOnlyWithByRefs.GetWithByRefInFunctionPointer(), n); }); + Assert.Throws(() => { UnmanagedCallersOnlyDll.CallManagedProc(UnmanagedCallersOnlyWithByRefs.GetWithByRefOutFunctionPointer(), n); }); } public static void NegativeTest_InstantiatedGenericArguments() diff --git a/src/tests/JIT/Methodical/Coverage/b433189.cs b/src/tests/JIT/Methodical/Coverage/b433189.cs index daac252cacbe3..233372e7a3b1a 100644 --- a/src/tests/JIT/Methodical/Coverage/b433189.cs +++ b/src/tests/JIT/Methodical/Coverage/b433189.cs @@ -45,7 +45,7 @@ public static void foo() { } - public static int Main(String[] args) + public static int Main() { try { diff --git a/src/tests/JIT/Methodical/Invoke/hfa_params/hfa_params.cs b/src/tests/JIT/Methodical/Invoke/hfa_params/hfa_params.cs index 4900ab2ead964..a84f46d4d4241 100644 --- a/src/tests/JIT/Methodical/Invoke/hfa_params/hfa_params.cs +++ b/src/tests/JIT/Methodical/Invoke/hfa_params/hfa_params.cs @@ -40,7 +40,7 @@ static bool foo(doublesStruct d1, doublesStruct d2, doublesStruct d3) return success; } - public static int Main(string[] args) + public static int Main() { // Test that a function with HFA args gets the expected contents of the structs. diff --git a/src/tests/JIT/Methodical/NaN/arithm32_cs_r.csproj b/src/tests/JIT/Methodical/NaN/arithm32_cs_r.csproj deleted file mode 100644 index 1d4bb8124b153..0000000000000 --- a/src/tests/JIT/Methodical/NaN/arithm32_cs_r.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - Exe - 1 - - - None - False - - - - - diff --git a/src/tests/JIT/Methodical/NaN/arithm32_r.csproj b/src/tests/JIT/Methodical/NaN/arithm32_r.csproj index ae6d54b865e5f..1d4bb8124b153 100644 --- a/src/tests/JIT/Methodical/NaN/arithm32_r.csproj +++ b/src/tests/JIT/Methodical/NaN/arithm32_r.csproj @@ -4,8 +4,8 @@ 1 - - + None + False diff --git a/src/tests/JIT/Methodical/NaN/arithm32_ro.csproj b/src/tests/JIT/Methodical/NaN/arithm32_ro.csproj index 78b3910bd48ff..0e464aed7200c 100644 --- a/src/tests/JIT/Methodical/NaN/arithm32_ro.csproj +++ b/src/tests/JIT/Methodical/NaN/arithm32_ro.csproj @@ -4,7 +4,7 @@ 1 - + None True diff --git a/src/tests/JIT/Methodical/NaN/arithm64_r.csproj b/src/tests/JIT/Methodical/NaN/arithm64_r.csproj index 4ee65bf654f4d..0a1a264667756 100644 --- a/src/tests/JIT/Methodical/NaN/arithm64_r.csproj +++ b/src/tests/JIT/Methodical/NaN/arithm64_r.csproj @@ -1,11 +1,10 @@ Exe - 1 - - + None + False diff --git a/src/tests/JIT/Methodical/NaN/arithm64_ro.csproj b/src/tests/JIT/Methodical/NaN/arithm64_ro.csproj index a4f4b382fde45..5baf4cd370ba4 100644 --- a/src/tests/JIT/Methodical/NaN/arithm64_ro.csproj +++ b/src/tests/JIT/Methodical/NaN/arithm64_ro.csproj @@ -1,7 +1,6 @@ Exe - 1 diff --git a/src/tests/JIT/Methodical/Overflow/FloatInfinitiesToInt.cs b/src/tests/JIT/Methodical/Overflow/FloatInfinitiesToInt.cs index dc1cac51bb257..032e4280559ef 100644 --- a/src/tests/JIT/Methodical/Overflow/FloatInfinitiesToInt.cs +++ b/src/tests/JIT/Methodical/Overflow/FloatInfinitiesToInt.cs @@ -300,32 +300,10 @@ public static int TestValues() return res; } - public static void Usage() + public static int Main() { - Console.WriteLine("FloatOvfToInt [print|test]"); - } - - public static int Main(String[] args) - { - if (args.Length != 1) - { - int res = TestValues(); - Console.WriteLine("Test " + (res == 100 ? "passed" : "failed")); - return res; - } - switch (args[0]) - { - case "print": - PrintValues(); - break; - case "test": - int res = TestValues(); - Console.WriteLine("Test " + (res == 100 ? "passed" : "failed")); - return res; - default: - Usage(); - break; - } - return 0; + int res = TestValues(); + Console.WriteLine("Test " + (res == 100 ? "passed" : "failed")); + return res; } } diff --git a/src/tests/JIT/Methodical/Overflow/FloatOvfToInt2.cs b/src/tests/JIT/Methodical/Overflow/FloatOvfToInt2.cs index acff1809714c4..061d6de67753d 100644 --- a/src/tests/JIT/Methodical/Overflow/FloatOvfToInt2.cs +++ b/src/tests/JIT/Methodical/Overflow/FloatOvfToInt2.cs @@ -887,32 +887,10 @@ public static int TestValues() return res; } - public static void Usage() - { - Console.WriteLine("FloatOvfToInt [print|test]"); - } - - public static int Main(String[] args) - { - if (args.Length != 1) - { - int res = TestValues(); - Console.WriteLine("Test " + (res == 100 ? "passed" : "failed")); - return res; - } - switch (args[0]) - { - case "print": - PrintValues(); - break; - case "test": - int res = TestValues(); - Console.WriteLine("Test " + (res == 100 ? "passed" : "failed")); - return res; - default: - Usage(); - break; - } - return 0; + public static int Main() + { + int res = TestValues(); + Console.WriteLine("Test " + (res == 100 ? "passed" : "failed")); + return res; } } diff --git a/src/tests/JIT/Methodical/eh/basics/emptyfinally.il b/src/tests/JIT/Methodical/eh/basics/emptyfinally.il index 2571109f7f657..0ad150dd5b198 100644 --- a/src/tests/JIT/Methodical/eh/basics/emptyfinally.il +++ b/src/tests/JIT/Methodical/eh/basics/emptyfinally.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly 'emptyfinally' {} .assembly extern xunit.core {} @@ -18,7 +18,7 @@ .class private auto ansi beforefieldinit Class1 extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -32,8 +32,8 @@ ldstr "Done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog hello.Class1::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog ret } @@ -56,8 +56,8 @@ .entrypoint .maxstack 1 - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -71,11 +71,11 @@ ldstr "Done" call void [System.Console]System.Console::WriteLine(string) - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/emptyfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/emptyfinally_il_d.ilproj index 14b5c4f79545a..a5f22331d15f4 100644 --- a/src/tests/JIT/Methodical/eh/basics/emptyfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/emptyfinally_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/emptyfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/emptyfinally_il_r.ilproj index 0e6c752f6f733..b89f79a19ffb3 100644 --- a/src/tests/JIT/Methodical/eh/basics/emptyfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/emptyfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/multihandler.cs b/src/tests/JIT/Methodical/eh/basics/multihandler.cs index b11fa133fb241..48a3eba1c9b39 100644 --- a/src/tests/JIT/Methodical/eh/basics/multihandler.cs +++ b/src/tests/JIT/Methodical/eh/basics/multihandler.cs @@ -24,7 +24,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/multihandler_d.csproj b/src/tests/JIT/Methodical/eh/basics/multihandler_d.csproj index 45605789c42ca..ea117ddfc2d34 100644 --- a/src/tests/JIT/Methodical/eh/basics/multihandler_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/multihandler_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/multihandler_do.csproj b/src/tests/JIT/Methodical/eh/basics/multihandler_do.csproj index 2dd47a56ea55f..9b0912aca9f3d 100644 --- a/src/tests/JIT/Methodical/eh/basics/multihandler_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/multihandler_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/multihandler_r.csproj b/src/tests/JIT/Methodical/eh/basics/multihandler_r.csproj index 2bb952cf10da5..9d4fbf256fadf 100644 --- a/src/tests/JIT/Methodical/eh/basics/multihandler_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/multihandler_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/multihandler_ro.csproj b/src/tests/JIT/Methodical/eh/basics/multihandler_ro.csproj index 5d23a0b5eea4a..207f9745da473 100644 --- a/src/tests/JIT/Methodical/eh/basics/multihandler_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/multihandler_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwincatch.cs b/src/tests/JIT/Methodical/eh/basics/throwincatch.cs index e36684a2a0852..9fdcbf8af9abd 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwincatch.cs +++ b/src/tests/JIT/Methodical/eh/basics/throwincatch.cs @@ -27,7 +27,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/throwincatch_d.csproj b/src/tests/JIT/Methodical/eh/basics/throwincatch_d.csproj index 3c9f2a4c509e5..1084dbd56a142 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwincatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwincatch_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwincatch_do.csproj b/src/tests/JIT/Methodical/eh/basics/throwincatch_do.csproj index 97223b5980c52..b49e317d15181 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwincatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwincatch_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwincatch_r.csproj b/src/tests/JIT/Methodical/eh/basics/throwincatch_r.csproj index 3e016e2864ecc..b7ed81d575090 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwincatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwincatch_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwincatch_ro.csproj b/src/tests/JIT/Methodical/eh/basics/throwincatch_ro.csproj index 26e10071c9810..01623ae8e604b 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwincatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwincatch_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_d.csproj b/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_d.csproj index 2e534c35ef14c..03ea036b040f1 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_do.csproj b/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_do.csproj index fe7c40ee6e4de..1844f95550243 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_r.csproj b/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_r.csproj index 6eb5610c270c3..bd9826a842d0c 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_ro.csproj b/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_ro.csproj index fd3afd042df51..b6515036cba43 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinclassconstructor_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinexcept.il b/src/tests/JIT/Methodical/eh/basics/throwinexcept.il index 885011d292f63..f75b47664650b 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinexcept.il +++ b/src/tests/JIT/Methodical/eh/basics/throwinexcept.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -39,11 +39,11 @@ ldstr "Done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { try_start: @@ -78,10 +78,10 @@ done2: call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/throwinexcept_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinexcept_il_d.ilproj index 37e4709a1e3ff..63ed90bac7412 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinexcept_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinexcept_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinexcept_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinexcept_il_r.ilproj index 6f96f942c4b47..487783f8ca2be 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinexcept_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinexcept_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfault.il b/src/tests/JIT/Methodical/eh/basics/throwinfault.il index c1c9907d8b660..e4adb4eda7e38 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfault.il +++ b/src/tests/JIT/Methodical/eh/basics/throwinfault.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -36,11 +36,11 @@ ldstr "In catch" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { ldstr "In try - catch" @@ -72,10 +72,10 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfault_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfault_il_d.ilproj index e2515afa6a31f..79225bdb8b7a5 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfault_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfault_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfault_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfault_il_r.ilproj index 18f195c567a84..f6f05bf5a1538 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfault_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfault_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfilter.il b/src/tests/JIT/Methodical/eh/basics/throwinfilter.il index 291e49a3ea857..d074b3626393d 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfilter.il +++ b/src/tests/JIT/Methodical/eh/basics/throwinfilter.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -36,11 +36,11 @@ ldstr "Done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { try_start: @@ -75,10 +75,10 @@ done2: call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfilter_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfilter_il_d.ilproj index 20914e47c79bb..c7baa28426aaf 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfilter_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfilter_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfilter_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfilter_il_r.ilproj index 5cca32de105b1..7d464d3b2d4e2 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfilter_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfilter_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinally.cs b/src/tests/JIT/Methodical/eh/basics/throwinfinally.cs index cec3faccfd9f4..506699c33d527 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinally.cs +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinally.cs @@ -38,7 +38,7 @@ public static void MiddleMethod() } } - public static int Main(string[] args) + public static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinally_d.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinally_d.csproj index a4cf02fde822d..7661f7246bc0a 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinally_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinally_do.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinally_do.csproj index 920ad8f83d8c3..385d5ea51c9c3 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinally_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinally_r.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinally_r.csproj index 8b0c953108556..f3d180376e04d 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinally_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinally_ro.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinally_ro.csproj index 780db521bc583..bd292cf3e716c 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinally_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath.cs b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath.cs index 9724d19e1247d..6fb587e0efd2e 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath.cs +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath.cs @@ -44,7 +44,7 @@ static public void inFinally() { Console.WriteLine("in Finally"); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_d.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_d.csproj index e38076313fc5c..6a3b01f88b689 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_do.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_do.csproj index b786953fdd756..87c7955c7d195 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_r.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_r.csproj index 9e53dafcad139..f0fbb0b7f27e3 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_ro.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_ro.csproj index ce1257177357a..9c6e3d115e423 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpath_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn.cs b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn.cs index 25611cd0bdd05..2246dc8d0fa89 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn.cs +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn.cs @@ -39,7 +39,7 @@ public static void MiddleMethod() Console.WriteLine("Unreached..."); } - public static int Main(string[] args) + public static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_d.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_d.csproj index 443c1629e3eed..eb534bd095d86 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_do.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_do.csproj index 09c599f2f5a6b..79f6912f59ba2 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_r.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_r.csproj index 6f6a0dadc3708..4717f7aa5f734 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_ro.csproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_ro.csproj index 2c47ad6ef85d2..f25971135c9e4 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyerrpathfn_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1.il b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1.il index 0413083851e26..89978e47e6456 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1.il +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -48,11 +48,11 @@ ldstr "caught an exception!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -71,10 +71,10 @@ DONE: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1_il_d.ilproj index ebc29f3d34e09..e3ffa0b97ab41 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1_il_r.ilproj index 746bbf9e376ed..0f6c8c2900603 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter1_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2.il b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2.il index 9245d8dc5ae75..7aecdc0049094 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2.il +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -48,11 +48,11 @@ ldstr "caught an exception!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -71,10 +71,10 @@ DONE: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2_il_d.ilproj index 140d1a9cabd9e..c5e39c6f4e1af 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2_il_r.ilproj index e94439217b989..dc3336aba36cb 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter2_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3.il b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3.il index 4f12bbb419ae3..10244b655d4ef 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3.il +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -57,11 +57,11 @@ ldstr "caught an exception!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -80,10 +80,10 @@ DONE: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3_il_d.ilproj index 48c2c68745a63..e543ef4d5b18a 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3_il_r.ilproj index dc27136cb1161..ee0c84b52cb63 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwinfinallyintryfilter3_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction.il b/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction.il index a4d63564e9c3d..73b5286071113 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction.il +++ b/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction.il @@ -9,14 +9,14 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly 'throwisfirstinstruction' {} .assembly extern xunit.core {} .class private auto ansi beforefieldinit test extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -32,8 +32,8 @@ ldstr "after try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog test::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog test::testLog ret } @@ -44,8 +44,8 @@ ) .entrypoint - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -64,11 +64,11 @@ ldstr "after try" call void [System.Console]System.Console::WriteLine(string) - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction_il_d.ilproj index 1e090b043e667..5c2f98aad6841 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction_il_r.ilproj index 6e40f7631ec6a..56c39c6188258 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/throwisfirstinstruction_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwoutside.cs b/src/tests/JIT/Methodical/eh/basics/throwoutside.cs index 5898a15eb720e..b1a0b162e91a5 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwoutside.cs +++ b/src/tests/JIT/Methodical/eh/basics/throwoutside.cs @@ -29,7 +29,7 @@ public static void MiddleMethod() throw new Exception(); } - public static int Main(string[] args) + public static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/throwoutside_d.csproj b/src/tests/JIT/Methodical/eh/basics/throwoutside_d.csproj index 860eef80df3c8..d9a24b6cab994 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwoutside_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwoutside_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwoutside_do.csproj b/src/tests/JIT/Methodical/eh/basics/throwoutside_do.csproj index 7ae5b9ef65984..ffc0b4c2b86ae 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwoutside_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwoutside_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwoutside_r.csproj b/src/tests/JIT/Methodical/eh/basics/throwoutside_r.csproj index 46d7c6677a9a6..42d7d744e8977 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwoutside_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwoutside_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/throwoutside_ro.csproj b/src/tests/JIT/Methodical/eh/basics/throwoutside_ro.csproj index f51a3016e71f7..5d0a3ce5df26e 100644 --- a/src/tests/JIT/Methodical/eh/basics/throwoutside_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/throwoutside_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trycatch.cs b/src/tests/JIT/Methodical/eh/basics/trycatch.cs index e3c59c9f13af0..3f139cba53f5e 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatch.cs +++ b/src/tests/JIT/Methodical/eh/basics/trycatch.cs @@ -34,7 +34,7 @@ static public void inCatch() static public void inFinally() { } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/trycatch_d.csproj b/src/tests/JIT/Methodical/eh/basics/trycatch_d.csproj index cbb4f9fa814e8..8e08e2572284a 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trycatch_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trycatch_do.csproj b/src/tests/JIT/Methodical/eh/basics/trycatch_do.csproj index e9a3f9171db3f..de3f1ab3eb99a 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trycatch_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trycatch_r.csproj b/src/tests/JIT/Methodical/eh/basics/trycatch_r.csproj index 14bf6b13404f4..ab453cfcea5ba 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trycatch_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trycatch_ro.csproj b/src/tests/JIT/Methodical/eh/basics/trycatch_ro.csproj index 9e5d50fb7bfbd..2c592e74eccb8 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trycatch_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch.cs b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch.cs index 8087d1bae67d3..af59a53644ffe 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch.cs +++ b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch.cs @@ -37,7 +37,7 @@ static public void inFinally() Console.WriteLine("In finally"); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_d.csproj b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_d.csproj index af8cf018f31d9..efe77cea1f99f 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_do.csproj b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_do.csproj index 1752281343a55..4db328c45f8e9 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_r.csproj b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_r.csproj index c96bd5e7c411d..dba339f1076d7 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_ro.csproj b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_ro.csproj index 6823f79d398eb..44c799b1c900f 100644 --- a/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trycatchtrycatch_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryexcept.il b/src/tests/JIT/Methodical/eh/basics/tryexcept.il index 028f83baf188d..fe357ac542d8a 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryexcept.il +++ b/src/tests/JIT/Methodical/eh/basics/tryexcept.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -30,11 +30,11 @@ ldstr "Done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() try_start: ldstr "In try" call void [System.Console]System.Console::WriteLine(string) @@ -56,10 +56,10 @@ handler_begin: pop call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret .try try_start to filter_begin filter filter_begin handler handler_begin to done diff --git a/src/tests/JIT/Methodical/eh/basics/tryexcept_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/tryexcept_il_d.ilproj index 015af404597c2..97c8301299faa 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryexcept_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryexcept_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryexcept_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/tryexcept_il_r.ilproj index fdd2d2196409a..eb4c88ada4bae 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryexcept_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryexcept_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfault.il b/src/tests/JIT/Methodical/eh/basics/tryfault.il index ee9e817306121..dc09833fb5d20 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfault.il +++ b/src/tests/JIT/Methodical/eh/basics/tryfault.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -27,11 +27,11 @@ ldstr "In try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -50,10 +50,10 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/tryfault_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfault_il_d.ilproj index 43ccb93a02c4a..e1188c0bfc7c7 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfault_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfault_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfault_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfault_il_r.ilproj index d710e5b31f27a..d1e77be846feb 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfault_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfault_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch.il b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch.il index ffb39123b97f1..c70b4e281823f 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch.il +++ b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -36,11 +36,11 @@ ldstr "In catch" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { ldstr "In try - catch" @@ -70,10 +70,10 @@ } done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch_il_d.ilproj index c90bf7273ffb5..a9bffb8fcae95 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch_il_r.ilproj index 7eaa069de21c6..184701327224b 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatch_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn.il b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn.il index 51fe932c712c5..85372b3ebe462 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn.il +++ b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -43,7 +43,7 @@ done: .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -61,11 +61,11 @@ done: ldstr "In catch" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { ldstr "In try - catch" @@ -82,10 +82,10 @@ done: } done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn_il_d.ilproj index ffda5941c6060..1f92b86c47846 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn_il_r.ilproj index 1619854826cb3..91d6012304525 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfaulttrycatchfn_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinally.cs b/src/tests/JIT/Methodical/eh/basics/tryfinally.cs index ac3fd22e41883..875be52dbf163 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinally.cs +++ b/src/tests/JIT/Methodical/eh/basics/tryfinally.cs @@ -34,7 +34,7 @@ static public void inFinally() Console.WriteLine("in Finally"); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinally_d.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinally_d.csproj index c3d80bae7c3a7..d7273e9983123 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinally_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinally_do.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinally_do.csproj index deb3015843bab..115ef6726676e 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinally_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinally_r.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinally_r.csproj index 997729f99eeb3..9f8691bd62b81 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinally_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinally_ro.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinally_ro.csproj index f12cb3cfb5020..e51f805693733 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinally_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch.cs b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch.cs index cd4b1b1788a8f..f559764fcd1df 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch.cs +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch.cs @@ -44,7 +44,7 @@ static public void inFinally() Console.WriteLine("in Finally"); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_d.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_d.csproj index 7d144464faadb..50033f113e225 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_do.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_do.csproj index c8efd800d670c..445251dddc6fb 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_r.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_r.csproj index 4e3df1ba7894d..d01390c61837b 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_ro.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_ro.csproj index ea34eb23ef3d8..d957431a85916 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytrycatch_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally.cs b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally.cs index 8d9275557f901..8573beb9c96df 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally.cs +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally.cs @@ -24,7 +24,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_d.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_d.csproj index bb5c66ade0117..0cb9b20dac799 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_do.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_do.csproj index ae629a35feffe..c43a915ccda36 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_r.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_r.csproj index 3330fef842229..7590c57b87d67 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_ro.csproj b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_ro.csproj index 1c5b4deb88e2b..664eca9cdf5ac 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallytryfinally_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally.il b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally.il index ed8ac02b555a2..10f663b48244f 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally.il +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly 'tryfinallywith2endfinally' {} .assembly extern xunit.core {} @@ -18,7 +18,7 @@ .class private auto ansi beforefieldinit Class1 extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -32,8 +32,8 @@ ldstr "in finally" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog hello.Class1::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog ret } @@ -46,8 +46,8 @@ .entrypoint .maxstack 1 - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -67,11 +67,11 @@ } IL_0017: - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally_il_d.ilproj index 7b53a5f541538..3fbe1add1fba9 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally_il_r.ilproj index 2d159610953e3..a501993664ac0 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2endfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally.il b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally.il index 06846e0fd929f..f92dc8acf5cbe 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally.il +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly 'tryfinallywith2reachableendfinally' {} .assembly extern xunit.core {} @@ -18,7 +18,7 @@ .class private auto ansi beforefieldinit Class1 extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -38,8 +38,8 @@ ldstr "in second finally" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog hello.Class1::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog ret } @@ -53,8 +53,8 @@ .maxstack 1 .locals init (int32 V_0) - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4.0 stloc.0 @@ -88,11 +88,11 @@ again: br.s again done: - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally_il_d.ilproj index 0e173898c9142..4ced3967cc4fa 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally_il_r.ilproj index 5b76db6e8e228..dab4847b04964 100644 --- a/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/tryfinallywith2reachableendfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatch.cs b/src/tests/JIT/Methodical/eh/basics/trythrowcatch.cs index d23607734d6f1..48944bb182e7b 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatch.cs +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatch.cs @@ -35,7 +35,7 @@ static public void inCatch() } static public void inFinally() { } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatch_d.csproj b/src/tests/JIT/Methodical/eh/basics/trythrowcatch_d.csproj index e71dc68212515..99b2e7f732996 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatch_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatch_do.csproj b/src/tests/JIT/Methodical/eh/basics/trythrowcatch_do.csproj index f0ae4a8d8a747..c3bed6623aa7c 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatch_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatch_r.csproj b/src/tests/JIT/Methodical/eh/basics/trythrowcatch_r.csproj index e60f5ebef8737..ef3031a296068 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatch_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatch_ro.csproj b/src/tests/JIT/Methodical/eh/basics/trythrowcatch_ro.csproj index b9bc9b3489c22..d9cce920c8670 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatch_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_d.csproj b/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_d.csproj index ef3d7525fc411..11e86db2b6415 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_do.csproj b/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_do.csproj index 84b8b5c143e40..f1c2edb048d00 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_r.csproj b/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_r.csproj index 5931ab4a7a57e..60b00fb2b1cbd 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_ro.csproj b/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_ro.csproj index 6d42d11fa98de..2201119cdea9d 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowcatchfinally_ro.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowexcept.il b/src/tests/JIT/Methodical/eh/basics/trythrowexcept.il index c13e04e5bc014..8365a8178b24e 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowexcept.il +++ b/src/tests/JIT/Methodical/eh/basics/trythrowexcept.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module test.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -42,11 +42,11 @@ ldstr "Done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() try_start: ldstr "In try" @@ -72,10 +72,10 @@ handler_begin: pop call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret .try try_start to filter_begin filter filter_begin handler handler_begin to done diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowexcept_il_d.ilproj b/src/tests/JIT/Methodical/eh/basics/trythrowexcept_il_d.ilproj index 8ed4c3fad67e3..f90ba0ef73a21 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowexcept_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowexcept_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/basics/trythrowexcept_il_r.ilproj b/src/tests/JIT/Methodical/eh/basics/trythrowexcept_il_r.ilproj index 7756242f0ad80..aec113f782586 100644 --- a/src/tests/JIT/Methodical/eh/basics/trythrowexcept_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/basics/trythrowexcept_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/common/common.csproj b/src/tests/JIT/Methodical/eh/common/common.csproj deleted file mode 100644 index 0346931092f81..0000000000000 --- a/src/tests/JIT/Methodical/eh/common/common.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - Library - BuildOnly - false - BuildOnly - false - - - - - - - - diff --git a/src/tests/JIT/Methodical/eh/cs/unsafe.cs b/src/tests/JIT/Methodical/eh/cs/unsafe.cs index e7dcf476a54fe..0c1bee75c5127 100644 --- a/src/tests/JIT/Methodical/eh/cs/unsafe.cs +++ b/src/tests/JIT/Methodical/eh/cs/unsafe.cs @@ -50,7 +50,7 @@ unsafe static void WriteLocations(byte[] arr) } } - static int Main(String[] args) + static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/cs/unsafe_d.csproj b/src/tests/JIT/Methodical/eh/cs/unsafe_d.csproj index 6eea0f0299aa8..a0548c96b74aa 100644 --- a/src/tests/JIT/Methodical/eh/cs/unsafe_d.csproj +++ b/src/tests/JIT/Methodical/eh/cs/unsafe_d.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/cs/unsafe_do.csproj b/src/tests/JIT/Methodical/eh/cs/unsafe_do.csproj index c798265cf3295..17b5ab70b2f50 100644 --- a/src/tests/JIT/Methodical/eh/cs/unsafe_do.csproj +++ b/src/tests/JIT/Methodical/eh/cs/unsafe_do.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/cs/unsafe_r.csproj b/src/tests/JIT/Methodical/eh/cs/unsafe_r.csproj index e269ef7745dfa..995b81dee5413 100644 --- a/src/tests/JIT/Methodical/eh/cs/unsafe_r.csproj +++ b/src/tests/JIT/Methodical/eh/cs/unsafe_r.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/cs/unsafe_ro.csproj b/src/tests/JIT/Methodical/eh/cs/unsafe_ro.csproj index 78cfbb8fdaaa7..560e05ae72ef3 100644 --- a/src/tests/JIT/Methodical/eh/cs/unsafe_ro.csproj +++ b/src/tests/JIT/Methodical/eh/cs/unsafe_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch.il b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch.il index 944aef16c0889..91cde8bcfb22f 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch.il +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch.il @@ -10,7 +10,7 @@ .assembly extern mscorlib{ .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'badcodeaftercatch' { .ver 0:0:0:0 @@ -61,7 +61,7 @@ .entrypoint .locals init (object V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -70,20 +70,20 @@ ldstr "pass" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call object Test_badcodeaftercatch::GetObj() call void [System.Console]System.Console::WriteLine(object) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch_il_d.ilproj index e4f843a20949c..bedb336015c71 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch_il_r.ilproj index 150f7a94668b7..5b6ca0d1ab413 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftercatch_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault.il b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault.il index b672281092348..633ff8bd18387 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault.il +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault.il @@ -10,7 +10,7 @@ .assembly extern mscorlib{ .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'badcodeafterfault' { .ver 0:0:0:0 @@ -57,7 +57,7 @@ .entrypoint .locals init (object V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -66,20 +66,20 @@ ldstr "pass" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call object Test_badcodeafterfault::GetObj() call void [System.Console]System.Console::WriteLine(object) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault_il_d.ilproj index e73e61b256e58..7257e1bae6300 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault_il_r.ilproj index f81f1768f93c4..8e23cb2c0fbce 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfault_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter.il b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter.il index 1bad495c4595c..62bb00f05c237 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter.il +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter.il @@ -10,7 +10,7 @@ .assembly extern mscorlib{ .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'badcodeafterfilter' { .ver 0:0:0:0 @@ -60,7 +60,7 @@ .entrypoint .locals init (object V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -69,20 +69,20 @@ ldstr "pass" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call object Test_badcodeafterfilter::GetObj() call void [System.Console]System.Console::WriteLine(object) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter_il_d.ilproj index c0ab6b81e1cb2..8c5c869c1f20f 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter_il_r.ilproj index 1fa706f9c4298..08b0cb8adb726 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfilter_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally.il b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally.il index 96dcf6d25b671..e5aa5dac7835b 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally.il +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally.il @@ -10,7 +10,7 @@ .assembly extern mscorlib{ .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'badcodeafterfinally' { .ver 0:0:0:0 @@ -66,7 +66,7 @@ .entrypoint .locals init (object V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -75,20 +75,20 @@ ldstr "pass" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call object Test_badcodeafterfinally::GetObj() call void [System.Console]System.Console::WriteLine(object) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally_il_d.ilproj index c6a1f6dc89315..98c03d9ecebbf 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally_il_d.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally_il_r.ilproj index adc8757c26173..2a17af6b48382 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeafterfinally_il_r.ilproj @@ -13,6 +13,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry.il b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry.il index 90c519ec6ebcb..3c25b4c507734 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry.il +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry.il @@ -10,7 +10,7 @@ .assembly extern mscorlib{ .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'badcodeaftertry' { .ver 0:0:0:0 @@ -57,7 +57,7 @@ .entrypoint .locals init (object V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -66,20 +66,20 @@ ldstr "pass" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call object Test_badcodeaftertry::GetObj() call void [System.Console]System.Console::WriteLine(object) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry_il_d.ilproj index ffa231c486870..7c48a7a054ef6 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry_il_r.ilproj index 2e8cb26e9c4d9..6f92f0fe02ad3 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeaftertry_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally.il b/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally.il index 3c923c39d92b6..b84e198c56be4 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally.il +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally.il @@ -10,7 +10,7 @@ .assembly extern mscorlib{ .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'badcodeinsidefinally' { .ver 0:0:0:0 @@ -73,7 +73,7 @@ .entrypoint .locals init (object V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -82,20 +82,20 @@ ldstr "pass" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call object Test_badcodeinsidefinally::GetObj() call void [System.Console]System.Console::WriteLine(object) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally_il_d.ilproj index 25e64f451b5fe..32eab59e3cace 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally_il_r.ilproj index 7ace56ef9e729..53bb7408fcd61 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/badcodeinsidefinally_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally.il b/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally.il index 175ccb41359d7..a83fb59395a65 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally.il +++ b/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally.il @@ -7,14 +7,14 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly 'branchoverendfinally' {} .assembly extern xunit.core {} .class private auto ansi beforefieldinit foo extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -36,8 +36,8 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog foo::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog foo::testLog ret } @@ -49,8 +49,8 @@ .entrypoint .maxstack 1 - ldsfld class [common]TestUtil.TestLog foo::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog foo::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -79,11 +79,11 @@ IL_0036: call void [System.Console]System.Console::WriteLine(string) IL_0039: - ldsfld class [common]TestUtil.TestLog foo::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog foo::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog foo::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog foo::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() IL_003b: ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally_il_d.ilproj index cd4430ea8aae1..7df28f3888d63 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally_il_r.ilproj index b340b1d8ef3bf..96f2cb11bc942 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/branchoverendfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB.il b/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB.il index 6eb3dc21d301d..03b35c753ea65 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common {} +.assembly extern eh_common {} .assembly 'deadEHregionacrossBB' { .hash algorithm 0x00008004 @@ -26,12 +26,12 @@ .class private auto ansi beforefieldinit test extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 - newobj instance void [common]TestUtil.TestLog::.ctor() - stsfld class [common]TestUtil.TestLog test::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor() + stsfld class [eh_common]TestUtil.TestLog test::testLog ret } // end of method test::.cctor } // end of class test @@ -55,8 +55,8 @@ .entrypoint .maxstack 1 .locals init (int32 V_0) - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() L: br IL_0019 @@ -84,11 +84,11 @@ } // end handler IL_0019: - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() IL_0022: ret } // end of method test::Main diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB_il_d.ilproj index 94b204e48a529..1f7815f4f3cf9 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB_il_d.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB_il_r.ilproj index e4849a1c81def..af2d3123184c3 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadEHregionacrossBB_il_r.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch.il b/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch.il index cff7b6ad4c1ad..d0fad14bb4304 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch.il @@ -9,7 +9,7 @@ .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) .ver 4:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly 'deadcodeincatch' { // --- The following custom attribute is added automatically, do not uncomment ------- @@ -33,7 +33,7 @@ .class private auto ansi beforefieldinit Class1 extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 3 @@ -56,8 +56,8 @@ ldstr "Pass" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog hello.Class1::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog ret } // end of method Class1::.cctor @@ -137,8 +137,8 @@ starttest: // Start recording - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldarg.0 stloc.0 .try @@ -189,12 +189,12 @@ call void [System.Console]System.Console::WriteLine(string) // stop recoding - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() // verify output - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() stloc.3 done: ldloc.3 diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch_il_d.ilproj index 7855b4bbf48b4..85131cbe439bf 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch_il_d.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch_il_r.ilproj index b0bb0e925e6e7..94bade77e29fc 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadcodeincatch_il_r.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit.il b/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit.il index 87afce8ed023a..6d828d68e5774 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog) + class [eh_common]TestUtil.TestLog testLog) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -42,11 +42,11 @@ ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -85,8 +85,8 @@ ldstr "Done!" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit_il_d.ilproj index ef6fe9ed2d6ff..9240a8cf3b61b 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit_il_r.ilproj index 7a4b9d548e24a..6e1fcbdb0b972 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadnonlocalexit_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadoponerror.il b/src/tests/JIT/Methodical/eh/deadcode/deadoponerror.il index 0a57462e346c3..d027c0ccd92b5 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadoponerror.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadoponerror.il @@ -4,7 +4,7 @@ .assembly extern mscorlib { } -.assembly extern common {} +.assembly extern eh_common {} .assembly 'deadoponerror' { } .assembly extern xunit.core {} @@ -18,13 +18,13 @@ .entrypoint .maxstack 8 .locals init ( - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) - newobj instance void [common]TestUtil.TestLog::.ctor() + newobj instance void [eh_common]TestUtil.TestLog::.ctor() stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { ldc.i4 1 leave endtry2 @@ -45,10 +45,10 @@ endtry1: endtry2: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } // end of method 'Test::Main' diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadoponerror_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadoponerror_il_d.ilproj index e63a943fbfa66..40ecb2f553efe 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadoponerror_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadoponerror_il_d.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadoponerror_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadoponerror_il_r.ilproj index 3737eea677878..ecf0935b78582 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadoponerror_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadoponerror_il_r.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet.il b/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet.il index 59e629384c520..a16deba23f93d 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet.il @@ -11,7 +11,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'deadoponerrorinfunclet' { .hash algorithm 0x00008004 @@ -27,7 +27,7 @@ .class private auto ansi beforefieldinit Class1 extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -44,8 +44,8 @@ ldstr "1234" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog hello.Class1::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog ret } } @@ -77,8 +77,8 @@ string V_1, int32 V_2) - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() IL_0000: ldc.i4 1234 IL_0002: stloc.0 IL_0003: ldloc.0 @@ -154,11 +154,11 @@ IL_006a: ldloc.2 call void [System.Console]System.Console::WriteLine(int32) - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() IL_006b: ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d.ilproj index f49b00668dd19..68ec24f2a5d6b 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r.ilproj index 901ffa45b961f..b0ef594900714 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadoponerrorinfunclet_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet.il b/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet.il index 1be0fbaadf6dd..9b2d35aa28477 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly test { .ver 0:0:0:0 @@ -29,7 +29,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -40,11 +40,11 @@ ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -115,9 +115,9 @@ L5: ldstr "Done!" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet_il_d.ilproj index a175faa92e4ed..9c2edef5c6602 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet_il_r.ilproj index 1f5adb4ce0f9f..9bb1dd736f412 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadrgninfunclet_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch.il b/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch.il index 6f2b4ae7539f8..949b08ef2f0e8 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -40,11 +40,11 @@ ldstr "Done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { ldstr "In try" @@ -76,9 +76,9 @@ ldstr "Done" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch_il_d.ilproj index a891a470d323a..95abd20cc2b7c 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch_il_r.ilproj index 55c802d86d4d7..13aec1c4fc432 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtrycatch_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally.il b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally.il index 670dbb0cabc57..c119f4c4f0292 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -37,11 +37,11 @@ ldstr "In try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { ldstr "In try" @@ -71,9 +71,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally_il_d.ilproj index 56cd016abe218..31ff1e8d4ee40 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally_il_r.ilproj index be582a7f536b3..ac1aa9164563e 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow.il b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow.il index dfa8026b5162a..f435b0a0b4eb6 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow.il +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -40,11 +40,11 @@ ldstr "In catch" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { ldstr "In try" call void [System.Console]System.Console::WriteLine(string) @@ -74,9 +74,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow_il_d.ilproj index 9926838555c4c..51815d328d9c8 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow_il_r.ilproj index 78d6ad1ab376e..3323806e8648c 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/deadtryfinallythrow_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop.il b/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop.il index 7caf328300b43..a53985c7214ab 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop.il +++ b/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop.il @@ -13,7 +13,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'endfinallyinloop' { @@ -39,7 +39,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -54,11 +54,11 @@ ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { IL_0000: ldstr "In try..." @@ -85,10 +85,10 @@ IL_0030: ldstr "Done!" IL_0035: call void [System.Console]System.Console::WriteLine(string) IL_0039: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() IL_003a: ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop_il_d.ilproj index c6b2e052c1469..352cdcc9bd0c6 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop_il_r.ilproj index 36adc73653ce1..d34a9558132a0 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/endfinallyinloop_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto.cs b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto.cs index edfb46ac88335..a8adb75237355 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto.cs +++ b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto.cs @@ -25,7 +25,7 @@ static Class1() s_testLog = new TestUtil.TestLog(expectedOut); } - private static int Main(string[] args) + private static int Main() { string[] s = { "one", "two", "three", "four", "five", "six" }; s_testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_d.csproj b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_d.csproj index bf56081b5aa48..7b3727b2bab9b 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_d.csproj +++ b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_do.csproj b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_do.csproj index 66ea96d71f2f9..8f003ce4b3651 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_do.csproj +++ b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_r.csproj b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_r.csproj index 2d1d42fc5dba8..d90da26ae87ea 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_r.csproj +++ b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_ro.csproj b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_ro.csproj index 057a432902ce3..f9362a5e62465 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_ro.csproj +++ b/src/tests/JIT/Methodical/eh/deadcode/loopstrswitchgoto_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions.il b/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions.il index 5f2eb80d4e97e..2ea3724d8e6ac 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions.il +++ b/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly test { @@ -30,7 +30,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -42,11 +42,11 @@ ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -172,9 +172,9 @@ skip: ldstr "Done!" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions_il_d.ilproj index d897f7819eb42..7d916c5a9e549 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions_il_r.ilproj index 66c6091a9e4eb..2285ae52bf12b 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/severaldeadehregions_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions.il b/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions.il index 15a80075731cb..7aaa1e57ebde6 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions.il +++ b/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly test { .ver 0:0:0:0 @@ -29,7 +29,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -40,11 +40,11 @@ ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -171,9 +171,9 @@ skip: ldstr "Done!" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions_il_d.ilproj index ff8da9061cb7a..55e9a847518cd 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions_il_r.ilproj index 0e06ae33dc0c4..a6350564c5616 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/severalnesteddeadehregions_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion.il b/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion.il index ca4968a72bef7..c4e6421d013c8 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion.il +++ b/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly test { .ver 0:0:0:0 @@ -29,7 +29,7 @@ .locals init ( int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -41,11 +41,11 @@ ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -78,9 +78,9 @@ done: ldstr "Done!" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion_il_d.ilproj b/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion_il_d.ilproj index 8294ae04aaa6c..21d0e9f51cf84 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion_il_r.ilproj b/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion_il_r.ilproj index e273a80f2e0b1..71989e6995240 100644 --- a/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/deadcode/simpledeadehregion_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/backwardleave.il b/src/tests/JIT/Methodical/eh/disconnected/backwardleave.il index 781ef2b38c522..7156403fc2d85 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/backwardleave.il +++ b/src/tests/JIT/Methodical/eh/disconnected/backwardleave.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -46,11 +46,11 @@ ldstr "In the middle" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -84,8 +84,8 @@ } done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/backwardleave_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/backwardleave_il_d.ilproj index 243fcdc7c80de..4020b5b27504a 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/backwardleave_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/backwardleave_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/backwardleave_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/backwardleave_il_r.ilproj index 82f0ee8b89ff8..401efd49bc621 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/backwardleave_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/backwardleave_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody.il b/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody.il index f0d0a420ed520..ad500f16dea8b 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody.il +++ b/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly test { .ver 0:0:0:0 @@ -29,7 +29,7 @@ .locals init ( int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -41,11 +41,11 @@ ldstr "In handler 0" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -69,9 +69,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody_il_d.ilproj index 7d7f71b2ffaf6..1dbf2b81ffadb 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody_il_r.ilproj index 154fab7ffafad..d5315ce1ea3aa 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/catchbeforetrybody_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally.il b/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally.il index 6d420b2c8bc10..f9c72946664c3 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally.il +++ b/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -29,7 +29,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -46,11 +46,11 @@ ldstr "In finally" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() IL_0000: ldc.i4 0xffff63c0 IL_0005: stloc.0 @@ -81,9 +81,9 @@ } IL_0031: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally_il_d.ilproj index dae6e1b78e0cd..dd36cb0bb8934 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally_il_r.ilproj index e6b1102926808..998bdc0372fdd 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/catchtryintryfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody.il b/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody.il index 87d57ceed316c..f50a5d519313f 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody.il +++ b/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -36,11 +36,11 @@ ldstr "In try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 br start_try1 @@ -62,9 +62,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_d.ilproj index 961260d211fab..a11fe456f089e 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_r.ilproj index 407610f19e37b..b4a222fcac425 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/faultbeforetrybody_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody.il b/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody.il index abadfc6cccd51..ae83cfb461d6b 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody.il +++ b/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -40,11 +40,11 @@ ldstr "In finally" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -67,9 +67,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody_il_d.ilproj index 66e7b6bccdb16..370a34e86ef83 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody_il_r.ilproj index 01e1e3f1f6153..53fd06b491934 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/finallybeforetrybody_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally.il b/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally.il index 6410ba8dc23a5..94dc2f34b7407 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally.il +++ b/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .locals init ( int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -46,11 +46,11 @@ ldstr "In finally 2" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -81,9 +81,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally_il_d.ilproj index 05a7e6c554135..410c21fb630ae 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally_il_r.ilproj index 6519202742f06..d5a16de3006b2 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/finallytryintryfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers.il b/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers.il index 1b608f188a935..3201300295376 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers.il +++ b/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .locals init ( int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -40,11 +40,11 @@ ldstr "In handler 2 (correct)" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -95,9 +95,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers_il_d.ilproj index 55132ea98842f..c53265408ae90 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers_il_r.ilproj index dc321b51ca13f..d742ea981edfb 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/reversedhandlers_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock.il b/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock.il index 7b235446a3be3..2b25d44528ce0 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock.il +++ b/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -45,11 +45,11 @@ ldstr "In handler 2" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -89,9 +89,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock_il_d.ilproj index 52f4c84858651..5051d360ae02e 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock_il_r.ilproj index 5a96c6a3dbe99..7dec86e8a47fd 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/reversedtryblock_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry.il b/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry.il index 2f7670b2a374d..9b88eb464c75f 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry.il +++ b/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -27,7 +27,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -39,11 +39,11 @@ ldstr "Done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() br.s try_start filter_begin: @@ -71,10 +71,10 @@ done: ldstr "Done" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret .try try_start to try_end filter filter_begin handler handler_begin to handler_end diff --git a/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry_il_d.ilproj index a18013e738b26..76c21c5a7ce84 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry_il_r.ilproj index 9767d6203abf2..a782ce986fcbd 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/sehhandlerbeforetry_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/testeit.il b/src/tests/JIT/Methodical/eh/disconnected/testeit.il index 5b0b814728807..939a9ac6497ca 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/testeit.il +++ b/src/tests/JIT/Methodical/eh/disconnected/testeit.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -29,7 +29,7 @@ .locals init (int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -43,11 +43,11 @@ ldstr "In handler 0" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -107,9 +107,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/testeit_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/testeit_il_d.ilproj index ff042b645979f..c3d2d0dcab29a 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/testeit_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/testeit_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/testeit_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/testeit_il_r.ilproj index 0e7bebc59ae86..b989a8fe13230 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/testeit_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/testeit_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers.il b/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers.il index 0bb018bfff34a..4a7aca0c871c9 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers.il +++ b/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers.il @@ -12,7 +12,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -29,7 +29,7 @@ .locals init ( int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -53,11 +53,11 @@ ldstr "Done!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -167,9 +167,9 @@ ldstr "Done!" call void [System.Console]System.Console::WriteLine(class [mscorlib]System.String) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers_il_d.ilproj index 75ada998a275e..e627c25f5faa7 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers_il_r.ilproj index 45f60c35b63ef..9c1135149f3f9 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/trybodyinbetweencatchhandlers_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry.il b/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry.il index 1148f9c7f1612..24eb60775ab0a 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry.il +++ b/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry.il @@ -11,7 +11,7 @@ { .ver 0:0:0:0 } -.assembly extern common {} +.assembly extern eh_common {} .assembly test { .ver 0:0:0:0 @@ -28,7 +28,7 @@ .locals init ( int32 V_0, int32 V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -52,11 +52,11 @@ ldstr "In outer finally" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0xffff63c0 stloc.0 @@ -97,9 +97,9 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry_il_d.ilproj b/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry_il_d.ilproj index 9d555c2c77e58..a5a5400574214 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry_il_r.ilproj b/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry_il_r.ilproj index dab413d8b3d37..07d37ff63e143 100644 --- a/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/disconnected/tryfinallyincatchtry_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry.cs b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry.cs index 37be221adc65e..45c9acc9b9258 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry.cs @@ -28,7 +28,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static int Main(string[] args) + static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry.il b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry.il index b9d6fd17ef0e7..045eb725be549 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry.il +++ b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry.il @@ -11,7 +11,7 @@ .assembly extern mscorlib { } - .assembly extern common{} + .assembly extern eh_common{} .assembly catchrettoinnertry { .hash algorithm 0x00008004 @@ -44,7 +44,7 @@ .class private auto ansi beforefieldinit Class1 extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -61,8 +61,8 @@ ldstr "In outer finally" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog strswitch.Class1::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog strswitch.Class1::testLog ret } .method private hidebysig static int32 @@ -74,8 +74,8 @@ .entrypoint .maxstack 2 - ldsfld class [common]TestUtil.TestLog strswitch.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog strswitch.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .locals init (int32 V_0, class [mscorlib]System.Exception V_1, @@ -124,11 +124,11 @@ endfinally } branch_003a: - ldsfld class [common]TestUtil.TestLog strswitch.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog strswitch.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog strswitch.Class1::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog strswitch.Class1::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_d.csproj index 98f953ca71bd2..37128b28596e7 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_do.csproj index 307079a31b21f..7c9e6b04e3cf4 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_r.csproj index 1106f4769dc50..28d3017ad6554 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_ro.csproj index 336089af811c8..6dc8e5384f325 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_cs_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_il_d.ilproj b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_il_d.ilproj index 03f6e9755b6e6..6d4bce51c373e 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_il_r.ilproj b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_il_r.ilproj index 6d97496642c4d..e754c6e68fce1 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/catchrettoinnertry_il_r.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_d.csproj index f8320e70af15c..d6811aff2fcbe 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_do.csproj index b644a3088974c..0c01a9a908d51 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_r.csproj index e6ef85d9e5146..9fbc2d3fd36e9 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_ro.csproj index 7c01aac36435d..ee3b164bac89a 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/localgotoinahandler_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally.cs b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally.cs index 9ff0fe44925c6..a57183df8a3db 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally.cs @@ -23,7 +23,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static int Main(string[] args) + static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_d.csproj index 45924247fcb1c..276ccb0f2aea7 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_do.csproj index e33e943099fc4..cd3823bdc5708 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_r.csproj index 69583bfec25a8..cd0ca51829370 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_ro.csproj index cfb862abb2de9..1ff99cf5e9f60 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/loopinfinally_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall.il b/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall.il index f6e7de6141de2..898b08a21efea 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall.il +++ b/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall.il @@ -9,12 +9,12 @@ } .assembly extern mscorlib {} .assembly extern System {} -.assembly extern common{} +.assembly extern eh_common{} .assembly 'nestedfinallycall' {} .assembly extern xunit.core {} .class public EHTest { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -40,8 +40,8 @@ ldstr "PASSED" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog EHTest::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog EHTest::testLog ret } @@ -131,8 +131,8 @@ ) .entrypoint - ldsfld class [common]TestUtil.TestLog EHTest::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog EHTest::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -146,11 +146,11 @@ RET: ldstr "PASSED" call void [System.Console]System.Console::WriteLine(string) - ldsfld class [common]TestUtil.TestLog EHTest::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog EHTest::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog EHTest::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog EHTest::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } } diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall_il_d.ilproj b/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall_il_d.ilproj index 05c1b055f9992..f4da491f7bee1 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall_il_r.ilproj b/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall_il_r.ilproj index 146f563ab04db..c0a99a1a96a2f 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nestedfinallycall_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry.cs b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry.cs index f7fb6942d9061..01d3b631a5337 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry.cs @@ -27,7 +27,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); @@ -39,11 +39,8 @@ static public int Main(string[] args) if (i > 0) goto done; try { - if (args.Length == 0) - { - i++; - goto begintry1; - } + i++; + goto begintry1; } finally { diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_d.csproj index 427f1fcfdd9d1..3c70ea279407f 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_do.csproj index 5e826b295c0d9..558ae56be06b2 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_r.csproj index bccef84a04d42..6bac894fe1b7e 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_ro.csproj index c5c3c2523cdf4..ec8527451c222 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittobeginningoftry_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling.il b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling.il index 473a42f63394b..c3fd5fd153494 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling.il +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} - .assembly extern common{} + .assembly extern eh_common{} .assembly 'nonlocalexittonestedsibling' {} .assembly extern xunit.core {} @@ -19,7 +19,7 @@ .class private auto ansi beforefieldinit Class1 extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 4 @@ -50,8 +50,8 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog hello.Class1::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog ret } @@ -69,8 +69,8 @@ class [mscorlib]System.ArithmeticException V_3, string V_4, int32 V_5) - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0x4d2 stloc.0 @@ -192,11 +192,11 @@ branch_00ce: - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog hello.Class1::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog hello.Class1::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling_il_d.ilproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling_il_d.ilproj index 05e49a94ac9ed..1667e95e3f4af 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling_il_r.ilproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling_il_r.ilproj index d07d1f0f4e01b..dc056bd26bddb 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalexittonestedsibling_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_d.csproj index 70482bcd91589..373edaa867608 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_do.csproj index 6b47d3fb54a65..cd08ecc409ff2 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_r.csproj index 4dea5e9ceebb6..8165794d53342 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_ro.csproj index 96fb6616625d1..860ab117fe4bf 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/nonlocalgotoinatryblockinahandler_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit.cs b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit.cs index eb982bfccf47c..76e0747a2359e 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit.cs @@ -23,14 +23,14 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); try { - if (args.Length == 0) goto done; + goto done; Console.WriteLine("in try"); } finally diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_d.csproj index 10d07f4371e1b..3460e93d3c7d7 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_do.csproj index 1cbb3645d4885..fc6f1501d0d43 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_r.csproj index 49bbdbf2f30ff..d705a59ba45b2 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_ro.csproj index 9ef959f49010a..a9a52d25985a5 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexit_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch.cs b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch.cs index 007767e6265f4..e29140426b36e 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch.cs @@ -22,7 +22,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); @@ -30,7 +30,7 @@ static public int Main(string[] args) { try { - if (args.Length == 0) goto done; + goto done; Console.WriteLine("in try"); } finally diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_d.csproj index 97d6dac6e80a3..f2adc6361d747 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_do.csproj index 840c310696197..c4f3e524a13e1 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_r.csproj index 47d4c467f7f14..64a5a98d38259 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_ro.csproj index 2c4939909793d..8197cf0f84c7a 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/simplenonlocalexitnestedintrycatch_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch.cs b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch.cs index d877f016aa328..ef63bac33f6ae 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch.cs @@ -40,7 +40,7 @@ static Class1() /// /// The main entry point for the application. /// - static int Main(string[] args) + static int Main() { string[] s = { "one", "two", "three", "four", "five", "six" }; //Start recording diff --git a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_d.csproj index 34b930119109d..97a2bde07f7df 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_do.csproj index 765c150f785e4..9d03e7f27961e 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_r.csproj index 5acfbcdae5868..f2b9084ae3307 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_ro.csproj index fd862a8fd3c61..1f5a01c8a2185 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/switchincatch_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1.cs b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1.cs index 240eaad720cb4..d46a617d6881d 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1.cs @@ -43,7 +43,7 @@ static public void Middle1(int i) Console.WriteLine("middle1 L1"); } - static public int Main(string[] args) + static public int Main() { // start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_d.csproj index a28d1afb6b572..48eb77fa370ee 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_do.csproj index 937573ef90ea4..b6002d36bcc2d 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_r.csproj index 542befeb26458..ffb340f1245d3 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_ro.csproj index d43f3e6f9f0c8..c8f6b707db3aa 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit1_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2.cs b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2.cs index 8f298039f9cf8..93d2d48d39a17 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2.cs @@ -68,7 +68,7 @@ static public void Middle2(int i) Console.WriteLine("middle2 L2"); } - static public int Main(string[] args) + static public int Main() { // start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_d.csproj index 079726db720ca..5ea02ce470d38 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_do.csproj index f21b7dc72a9ab..aad9e95ab2e42 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_r.csproj index 832c828c7fb9e..14696db66e265 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_ro.csproj index d192f3f42aaac..6c5c4643e8143 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit2_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3.cs b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3.cs index 96e7db9036aa9..5ef9a2e00a70d 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3.cs @@ -84,7 +84,7 @@ static public void Middle2(int i) Console.WriteLine(" in middle2 L2B"); } - static public int Main(string[] args) + static public int Main() { // start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_d.csproj index 05a645d414047..c0b923bb12cdb 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_do.csproj index 52f463b15c55e..a86946974a847 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_r.csproj index 5254c13e6e2d6..de41134201400 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_ro.csproj index cf79779182ec7..c9ed59aa8cdc7 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit3_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4.cs b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4.cs index 2b3d7be778c91..6b7b2f5f14cdd 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4.cs @@ -60,7 +60,7 @@ static public void foo(int i) } - static public int Main(string[] args) + static public int Main() { // start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_d.csproj index 939aec395c202..dffec8e6288c4 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_do.csproj index c32b1144fc0e7..157253a86ef16 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_r.csproj index a38fbcf882b66..b90cd2085c6b2 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_ro.csproj index 8ff7434d77c40..0cdeb3ed205b9 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryCatchFinallyThrow_nonlocalexit4_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit.cs b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit.cs index 9e13611f04aa2..3e26c2428ecab 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit.cs +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit.cs @@ -53,14 +53,14 @@ static public void Middle(int i) } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); try { Console.WriteLine("In main's try"); - Middle(args.Length); + Middle(0); } catch { diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_d.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_d.csproj index 53472aa94ec81..b3fed6c4ce20a 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_d.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_do.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_do.csproj index ab2a8dc484b29..98be0b378e0da 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_do.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_r.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_r.csproj index 800696aa5ef5a..077db4c280c48 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_r.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_ro.csproj b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_ro.csproj index 4c205955930b3..8c87dde4db4ad 100644 --- a/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_ro.csproj +++ b/src/tests/JIT/Methodical/eh/finallyexec/tryfinallythrow_nonlocalexit_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/throwincatch_d.csproj b/src/tests/JIT/Methodical/eh/generics/throwincatch_d.csproj index c11c6235757b4..8b69adfc97a48 100644 --- a/src/tests/JIT/Methodical/eh/generics/throwincatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/generics/throwincatch_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/throwincatch_do.csproj b/src/tests/JIT/Methodical/eh/generics/throwincatch_do.csproj index 56695d85328ae..faf0d00b1742b 100644 --- a/src/tests/JIT/Methodical/eh/generics/throwincatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/generics/throwincatch_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/throwincatch_r.csproj b/src/tests/JIT/Methodical/eh/generics/throwincatch_r.csproj index 536be78a3c842..7adfebc17a673 100644 --- a/src/tests/JIT/Methodical/eh/generics/throwincatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/generics/throwincatch_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/throwincatch_ro.csproj b/src/tests/JIT/Methodical/eh/generics/throwincatch_ro.csproj index b1df0b6434342..4e9ccaade291e 100644 --- a/src/tests/JIT/Methodical/eh/generics/throwincatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/generics/throwincatch_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_d.csproj b/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_d.csproj index 9d68eddf63e6c..c38fe96a3d155 100644 --- a/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_d.csproj +++ b/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_do.csproj b/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_do.csproj index 6697effb5f757..ad254f3632ac2 100644 --- a/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_do.csproj +++ b/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_r.csproj b/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_r.csproj index e67ba575c4358..da91f8f4cf846 100644 --- a/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_r.csproj +++ b/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_ro.csproj b/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_ro.csproj index b002c67234532..6791d30ce250d 100644 --- a/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_ro.csproj +++ b/src/tests/JIT/Methodical/eh/generics/trycatchnestedtype_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_d.csproj b/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_d.csproj index 07a93a14091ab..4cb75702da026 100644 --- a/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_d.csproj +++ b/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_do.csproj b/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_do.csproj index 0a748d0fbc8a6..70c9a023e90c2 100644 --- a/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_do.csproj +++ b/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_r.csproj b/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_r.csproj index 6ba78fdadb1f4..e4a96aaace2c7 100644 --- a/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_r.csproj +++ b/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_ro.csproj b/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_ro.csproj index 4320be94acfcd..4febc6189f67f 100644 --- a/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_ro.csproj +++ b/src/tests/JIT/Methodical/eh/generics/trycatchsimpletype_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/gcincatch.cs b/src/tests/JIT/Methodical/eh/interactions/gcincatch.cs index dce8fad356330..152bfe23dfdd1 100644 --- a/src/tests/JIT/Methodical/eh/interactions/gcincatch.cs +++ b/src/tests/JIT/Methodical/eh/interactions/gcincatch.cs @@ -40,7 +40,7 @@ static Class1() /// /// The main entry point for the application. /// - public static int Main(String[] args) + public static int Main() { int[] ar = new int[] { 1, 2, 3, 4, 5 }; @@ -49,13 +49,6 @@ public static int Main(String[] args) try { - if (args.Length > 0) - { - for (int i = 0; i < ar.Length; i++) - { - Console.WriteLine("ar[" + i + "]=" + ar[i]); - } - } Console.WriteLine("In try"); GC.Collect(); GC.WaitForPendingFinalizers(); diff --git a/src/tests/JIT/Methodical/eh/interactions/gcincatch_d.csproj b/src/tests/JIT/Methodical/eh/interactions/gcincatch_d.csproj index b87052a25fabf..69f6f4f21ceec 100644 --- a/src/tests/JIT/Methodical/eh/interactions/gcincatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/gcincatch_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/gcincatch_do.csproj b/src/tests/JIT/Methodical/eh/interactions/gcincatch_do.csproj index 6c84f4fe219a3..50f9580550fb9 100644 --- a/src/tests/JIT/Methodical/eh/interactions/gcincatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/gcincatch_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/gcincatch_r.csproj b/src/tests/JIT/Methodical/eh/interactions/gcincatch_r.csproj index 3a3508b2218b5..7dccaecc1f78d 100644 --- a/src/tests/JIT/Methodical/eh/interactions/gcincatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/gcincatch_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/gcincatch_ro.csproj b/src/tests/JIT/Methodical/eh/interactions/gcincatch_ro.csproj index b2ce882e1cd28..fd75a0e92b13a 100644 --- a/src/tests/JIT/Methodical/eh/interactions/gcincatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/gcincatch_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally.cs b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally.cs index cf446a37ae68b..7e8be151ff474 100644 --- a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally.cs +++ b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally.cs @@ -22,7 +22,7 @@ static Class1() // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { int[] a; //Start recording diff --git a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_d.csproj b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_d.csproj index e86f1a6954f1f..fb65118a0a897 100644 --- a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_do.csproj b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_do.csproj index 6d3016e45870f..419ed339ea550 100644 --- a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_r.csproj b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_r.csproj index b68a8a3039113..cb20910703c69 100644 --- a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_ro.csproj b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_ro.csproj index f5b92f1ec6e04..4fa95a8abb3c1 100644 --- a/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/rangecheckinfinally_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal.cs b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal.cs index d8925257a6b33..e8f7027493446 100644 --- a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal.cs +++ b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal.cs @@ -54,7 +54,7 @@ static Class1() s_testLog = new TestUtil.TestLog(expectedOut); } - private static int Main(string[] args) + private static int Main() { string[] s = { "one", "two", "three", "four", "five", "six" }; s_testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_d.csproj b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_d.csproj index 861379bcfadb5..09faff138877e 100644 --- a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_d.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_d.csproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_do.csproj b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_do.csproj index 813e47519160e..6a020c1519bc0 100644 --- a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_do.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_do.csproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_r.csproj b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_r.csproj index cd9efb86f934a..00aa580cabfb1 100644 --- a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_r.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_r.csproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_ro.csproj b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_ro.csproj index dd0f3a136f1ff..a4b05658e5ec3 100644 --- a/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_ro.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/strswitchfinal_ro.csproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/switchinfinally.cs b/src/tests/JIT/Methodical/eh/interactions/switchinfinally.cs index b00747fad113c..33a551c68d162 100644 --- a/src/tests/JIT/Methodical/eh/interactions/switchinfinally.cs +++ b/src/tests/JIT/Methodical/eh/interactions/switchinfinally.cs @@ -85,12 +85,12 @@ static Class1() /// /// The main entry point for the application. /// - static int Main(string[] args) + static int Main() { //Start recording testLog.StartRecording(); MyClass x = new MyClass(1234); - x.testit(args.Length); + x.testit(0); Console.WriteLine(x.val); // stop recoding diff --git a/src/tests/JIT/Methodical/eh/interactions/switchinfinally_d.csproj b/src/tests/JIT/Methodical/eh/interactions/switchinfinally_d.csproj index 3f9d578fc338c..9495fe4601cd5 100644 --- a/src/tests/JIT/Methodical/eh/interactions/switchinfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/switchinfinally_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/switchinfinally_do.csproj b/src/tests/JIT/Methodical/eh/interactions/switchinfinally_do.csproj index eed67513f93f0..f22a1ab0544c6 100644 --- a/src/tests/JIT/Methodical/eh/interactions/switchinfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/switchinfinally_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/switchinfinally_r.csproj b/src/tests/JIT/Methodical/eh/interactions/switchinfinally_r.csproj index c76f8e51ea3c7..cff3b88e13b7a 100644 --- a/src/tests/JIT/Methodical/eh/interactions/switchinfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/switchinfinally_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/switchinfinally_ro.csproj b/src/tests/JIT/Methodical/eh/interactions/switchinfinally_ro.csproj index 78df18f2dce4e..70ee8c9e3bb01 100644 --- a/src/tests/JIT/Methodical/eh/interactions/switchinfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/interactions/switchinfinally_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/throw1dimarray.il b/src/tests/JIT/Methodical/eh/interactions/throw1dimarray.il index b5c906d2e7748..a23066d7d4e61 100644 --- a/src/tests/JIT/Methodical/eh/interactions/throw1dimarray.il +++ b/src/tests/JIT/Methodical/eh/interactions/throw1dimarray.il @@ -17,7 +17,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'throw1dimarray' { @@ -57,7 +57,7 @@ [7] int32[] V_7, [8] object o, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -115,11 +115,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldnull @@ -266,9 +266,9 @@ IL_00f7: br IL_003d IL_00fc: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() IL_00fd: ret diff --git a/src/tests/JIT/Methodical/eh/interactions/throw1dimarray_il_d.ilproj b/src/tests/JIT/Methodical/eh/interactions/throw1dimarray_il_d.ilproj index 42a8e79548274..74353312cd448 100644 --- a/src/tests/JIT/Methodical/eh/interactions/throw1dimarray_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/interactions/throw1dimarray_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/throw1dimarray_il_r.ilproj b/src/tests/JIT/Methodical/eh/interactions/throw1dimarray_il_r.ilproj index 81418e1ec8a34..ee6a87566fcbd 100644 --- a/src/tests/JIT/Methodical/eh/interactions/throw1dimarray_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/interactions/throw1dimarray_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/throw2dimarray.il b/src/tests/JIT/Methodical/eh/interactions/throw2dimarray.il index 3484f4cde28d9..580cfe6f6565e 100644 --- a/src/tests/JIT/Methodical/eh/interactions/throw2dimarray.il +++ b/src/tests/JIT/Methodical/eh/interactions/throw2dimarray.il @@ -13,7 +13,7 @@ { .ver 0:0:0:0 } -.assembly extern common{} +.assembly extern eh_common{} .assembly extern System.Windows.Forms { .ver 0:0:0:0 @@ -52,7 +52,7 @@ int32[,] V_4, object V_5, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -128,11 +128,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() IL_0000: ldnull @@ -373,10 +373,10 @@ } IL_00a3: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() IL_00a4: ret } diff --git a/src/tests/JIT/Methodical/eh/interactions/throw2dimarray_il_d.ilproj b/src/tests/JIT/Methodical/eh/interactions/throw2dimarray_il_d.ilproj index 8e57e3ed44b8b..f6497cf229b02 100644 --- a/src/tests/JIT/Methodical/eh/interactions/throw2dimarray_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/interactions/throw2dimarray_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/throw2dimarray_il_r.ilproj b/src/tests/JIT/Methodical/eh/interactions/throw2dimarray_il_r.ilproj index 4303af4ae5473..9c0c939ed05e5 100644 --- a/src/tests/JIT/Methodical/eh/interactions/throw2dimarray_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/interactions/throw2dimarray_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/interactions/volatileFromFinally.cs b/src/tests/JIT/Methodical/eh/interactions/volatileFromFinally.cs index 5a22e947c19fb..b20a51f7151c6 100644 --- a/src/tests/JIT/Methodical/eh/interactions/volatileFromFinally.cs +++ b/src/tests/JIT/Methodical/eh/interactions/volatileFromFinally.cs @@ -37,7 +37,7 @@ private static void Crash() } } - private static int Main(string[] args) + private static int Main() { //Console.WriteLine("64 bit = {0}", Environment.Is64BitProcess); diff --git a/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry.il b/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry.il index af525a8301d38..fe173773ddcb5 100644 --- a/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry.il +++ b/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly '2branchesoutoftry'{ .hash algorithm 0x00008004 @@ -47,7 +47,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -62,11 +62,11 @@ ldstr "After try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -89,10 +89,10 @@ label2: ldstr "After try" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry_il_d.ilproj index 786511538fd56..ef70c4396c2fd 100644 --- a/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry_il_r.ilproj index 04840887e182e..c63878f8754e6 100644 --- a/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/2branchesoutoftry_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch.il b/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch.il index 38addcab9bf2c..7622150ab520d 100644 --- a/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch.il +++ b/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'backwardleaveincatch' { .hash algorithm 0x00008004 @@ -84,7 +84,7 @@ .maxstack 2 .locals init (int32 V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -110,11 +110,11 @@ ldstr "done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4.0 stloc.0 @@ -154,10 +154,10 @@ ldstr "done" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch_il_d.ilproj index eeb1711f5159f..94a31dd389711 100644 --- a/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch_il_r.ilproj index 15874afa5cb2a..0b82dccda87e1 100644 --- a/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/backwardleaveincatch_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch.il b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch.il index d81ffc6495749..59dc610160c67 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch.il +++ b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'branchbackwardswithcatch' { .hash algorithm 0x00008004 @@ -83,7 +83,7 @@ .maxstack 2 .locals init (int32 V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -103,11 +103,11 @@ ldstr "done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4.0 stloc.0 @@ -145,10 +145,10 @@ before: ldstr "done" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch_il_d.ilproj index 0e51862357ae5..ec9bf1d9f72bf 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch_il_r.ilproj index 0a3ad6611a1b7..7fd4f6c1c45c0 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithcatch_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally.il b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally.il index d77d0c195170f..f1c07aba492b0 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally.il +++ b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly branchbackwardswithfinally { .hash algorithm 0x00008004 @@ -83,7 +83,7 @@ .maxstack 2 .locals init (int32 V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -109,11 +109,11 @@ ldstr "done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4.0 stloc.0 @@ -151,10 +151,10 @@ ldstr "done" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally_il_d.ilproj index ca83044262728..ba3d5313739f2 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally_il_r.ilproj index 82644af3dd4ff..ce61adc283cac 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/branchbackwardswithfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally.il b/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally.il index cc584d81d46f1..b17ba77507675 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally.il +++ b/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'branchoutofnestedtryfinally' { .hash algorithm 0x00008004 @@ -92,7 +92,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -113,11 +113,11 @@ ldstr "After try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { ldstr "In try 0" @@ -153,10 +153,10 @@ ldstr "After try" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally_il_d.ilproj index bb3b2c7bb21d8..ed552517852de 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally_il_r.ilproj index db43d3847dec6..639e66748b428 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/branchoutofnestedtryfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally.il b/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally.il index 8aa943becb92e..34a79462a7c04 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally.il +++ b/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally.il @@ -13,7 +13,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'branchoutoftryfinally' { .hash algorithm 0x00008004 @@ -48,7 +48,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -62,11 +62,11 @@ ldstr "After try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -87,10 +87,10 @@ ldstr "After try" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally_il_d.ilproj index fc04292b38fda..0dba22bfa42be 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally_il_r.ilproj index 745614046d243..e4bc7ff30e5d6 100644 --- a/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/branchoutoftryfinally_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet.cs b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet.cs index cb2ac623d9caa..a443c0719a41a 100644 --- a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet.cs +++ b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet.cs @@ -25,7 +25,7 @@ static Class1() // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_d.csproj b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_d.csproj index e1970c6a0c70f..6dcdb18328662 100644 --- a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_d.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_do.csproj b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_do.csproj index 36b14db1986f3..356c25ec31d7e 100644 --- a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_do.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_r.csproj b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_r.csproj index cd430966ebb03..5893c7ffaf190 100644 --- a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_r.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_ro.csproj b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_ro.csproj index 1a5625bbc07df..b11e6d253fbb9 100644 --- a/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_ro.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/catchretnonlocalexitinfunclet_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch.il b/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch.il index fb62104c565fb..831f8227f79d9 100644 --- a/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch.il +++ b/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'forwardleaveincatch' { .hash algorithm 0x00008004 @@ -83,7 +83,7 @@ .maxstack 2 .locals init (int32 V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -106,11 +106,11 @@ ldstr "after try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4.0 stloc.0 @@ -153,9 +153,9 @@ ldstr "after try" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch_il_d.ilproj index 01f2552e2670a..31cf654efefcf 100644 --- a/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch_il_r.ilproj index 250a47466b818..03d1dd0d49da7 100644 --- a/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/forwardleaveincatch_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally.il b/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally.il index ea059a878a18a..317e13f0fe94c 100644 --- a/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally.il +++ b/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally.il @@ -11,7 +11,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'labelbeforefinally' { .hash algorithm 0x00008004 @@ -46,7 +46,7 @@ .maxstack 2 .locals init (bool V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -61,11 +61,11 @@ ldstr "after try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4.0 stloc.0 .try @@ -87,9 +87,9 @@ labelafter: ldstr "after try" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally_il_d.ilproj index 7979259358b21..ddb436a23072f 100644 --- a/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally_il_r.ilproj index e8b1e6f72c692..ef50aa1c9b3cc 100644 --- a/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/labelbeforefinally_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally.il b/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally.il index d65d52edf3ad7..781f8517fb80c 100644 --- a/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally.il +++ b/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'labelbeginningfinally' { .hash algorithm 0x00008004 @@ -47,7 +47,7 @@ .maxstack 2 .locals init (bool V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -65,11 +65,11 @@ ldstr "done" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4.0 stloc.0 .try @@ -94,9 +94,9 @@ ldstr "done" call void [System.Console]System.Console::WriteLine(string) ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally_il_d.ilproj index 1e490b5af9353..4757fee213fb1 100644 --- a/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally_il_r.ilproj index 7663fa1dfab68..7ce6a2a1a67c7 100644 --- a/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/labelbeginningfinally_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion.il b/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion.il index 1a18f4047fd24..677873d6cc29c 100644 --- a/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion.il +++ b/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'leaveinsameregion' { .hash algorithm 0x00008004 @@ -72,7 +72,7 @@ .maxstack 2 .locals init (class [mscorlib]System.Exception V_0, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -83,11 +83,11 @@ ldstr "in Catch\n" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -108,10 +108,10 @@ } IL_0015: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion_il_d.ilproj index d8cf0cbdc15da..86bd872fe0dd5 100644 --- a/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion_il_r.ilproj index b56f5997fb2e1..0a47ccaf78ae5 100644 --- a/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/leaveinsameregion_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody.il b/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody.il index bb95d59b3831a..56f4feee5d43c 100644 --- a/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody.il +++ b/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody.il @@ -12,7 +12,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'leaveintotrybody' { .hash algorithm 0x00008004 @@ -65,7 +65,7 @@ .locals init (int32 V_0, class [mscorlib]System.Exception V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -102,11 +102,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() IL_0000: ldc.i4.0 IL_0001: stloc.0 .try @@ -159,10 +159,10 @@ } IL_001b: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody_il_d.ilproj index b3f2f43548ec4..c9d0ed390acaa 100644 --- a/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody_il_r.ilproj index 1bb35167b2ae4..0fadf0e1ebccb 100644 --- a/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/leaveintotrybody_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_d.csproj b/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_d.csproj index 4b01c12c8c328..dc89065297c00 100644 --- a/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_do.csproj b/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_do.csproj index 95edc96dadff3..a8bff543c56a4 100644 --- a/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_r.csproj b/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_r.csproj index bc2dc41ecfaa9..89947df6657df 100644 --- a/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_ro.csproj b/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_ro.csproj index 1699a3fbec98e..438a81153a00c 100644 --- a/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/nonlocalexitfromnestedcatch_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/oponerror.cs b/src/tests/JIT/Methodical/eh/leaves/oponerror.cs index e7186a47d1e00..a960800e2aace 100644 --- a/src/tests/JIT/Methodical/eh/leaves/oponerror.cs +++ b/src/tests/JIT/Methodical/eh/leaves/oponerror.cs @@ -27,7 +27,7 @@ static Class1() // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/leaves/oponerror_d.csproj b/src/tests/JIT/Methodical/eh/leaves/oponerror_d.csproj index 77067e854922f..ea1b0fd583e1e 100644 --- a/src/tests/JIT/Methodical/eh/leaves/oponerror_d.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/oponerror_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/oponerror_do.csproj b/src/tests/JIT/Methodical/eh/leaves/oponerror_do.csproj index d52523a30d437..0205d2938aa03 100644 --- a/src/tests/JIT/Methodical/eh/leaves/oponerror_do.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/oponerror_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/oponerror_r.csproj b/src/tests/JIT/Methodical/eh/leaves/oponerror_r.csproj index 3cd54e45b6106..78f095c9bb3af 100644 --- a/src/tests/JIT/Methodical/eh/leaves/oponerror_r.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/oponerror_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/oponerror_ro.csproj b/src/tests/JIT/Methodical/eh/leaves/oponerror_ro.csproj index 7b3973e9489bb..2290f5a520905 100644 --- a/src/tests/JIT/Methodical/eh/leaves/oponerror_ro.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/oponerror_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry.il b/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry.il index 40ce213f38723..8ee803a7a8f21 100644 --- a/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry.il +++ b/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry.il @@ -13,7 +13,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'tryfinallyintrycatchwithleaveintotry' { .hash algorithm 0x00008004 @@ -66,7 +66,7 @@ .locals init (int32 V_0, class [mscorlib]System.Exception V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -109,11 +109,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() IL_0000: ldc.i4.0 IL_0001: stloc.0 .try @@ -175,10 +175,10 @@ } IL_001b: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry_il_d.ilproj b/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry_il_d.ilproj index 001f5d7a70588..7ee14c9865875 100644 --- a/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry_il_r.ilproj b/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry_il_r.ilproj index 4ff434fcb635b..cdda447565cae 100644 --- a/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/leaves/tryfinallyintrycatchwithleaveintotry_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop.cs b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop.cs index 609d32b5a8b6f..d2a572fb45e47 100644 --- a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop.cs +++ b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop.cs @@ -41,7 +41,7 @@ static public void inFinally() { Console.WriteLine("in Finally\n"); } - static public int Main(string[] args) + static public int Main() { int i = 0; //Start recording diff --git a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_d.csproj b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_d.csproj index 2e4550f67a237..9da9bf19d1a10 100644 --- a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_d.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_do.csproj b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_do.csproj index fb066153189c4..1d92d52698f9e 100644 --- a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_do.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_r.csproj b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_r.csproj index 3e4b7f299ef2f..bfa18d68da6f8 100644 --- a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_r.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_ro.csproj b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_ro.csproj index ecaaecd81f61b..e0371bdf0648e 100644 --- a/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_ro.csproj +++ b/src/tests/JIT/Methodical/eh/leaves/tryfinallyloop_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch.il b/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch.il index ada2a761ee276..29dd18a373382 100644 --- a/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch.il +++ b/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch.il @@ -15,7 +15,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'catchfiltercatch' { .hash algorithm 0x00008004 @@ -64,7 +64,7 @@ .locals init (class [mscorlib]System.DivideByZeroException V_0, class [mscorlib]System.ArithmeticException V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -78,11 +78,11 @@ ldstr "In handler" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() start_try: ldstr "In try" call void [System.Console]System.Console::WriteLine(string) @@ -132,10 +132,10 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch_il_d.ilproj index 6b94beee26ab6..1992d47a7167e 100644 --- a/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch_il_r.ilproj index 79c7ca4441874..114d614083632 100644 --- a/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/mixedhandler/catchfiltercatch_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch.il b/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch.il index e362a58111b63..4f64c5669c2ac 100644 --- a/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch.il +++ b/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch.il @@ -15,7 +15,7 @@ .assembly extern mscorlib { } -.assembly extern common{} +.assembly extern eh_common{} .assembly 'filterfiltercatchcatch' { .hash algorithm 0x00008004 @@ -64,7 +64,7 @@ .locals init (class [mscorlib]System.DivideByZeroException V_0, class [mscorlib]System.ArithmeticException V_1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() stloc.s expectedOut @@ -81,11 +81,11 @@ ldstr "In handler2" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() start_try: ldstr "In try" call void [System.Console]System.Console::WriteLine(string) @@ -150,10 +150,10 @@ done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch_il_d.ilproj index 03c8f77b9678d..7a91443a09c9a 100644 --- a/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch_il_r.ilproj index 491bcadaaf7ee..ece73fa9d319f 100644 --- a/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/mixedhandler/filterfiltercatchcatch_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch.il b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch.il index e8bffa7b01207..668d73cfc64ed 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch.il +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module cascadedcatch.exe @@ -20,7 +20,7 @@ int32 V_0, int32 V1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -41,11 +41,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0 stloc.0 @@ -1490,10 +1490,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch_il_d.ilproj index 31f4346e1c5af..3bf22a0e44ba9 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch_il_r.ilproj index a6f422191c48f..40f2e9529fa35 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedcatch_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept.il b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept.il index 4a3110d78cd41..a402afd45e3a5 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept.il +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module cascadedexcept.exe @@ -19,7 +19,7 @@ int32 V_0, int32 V1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -40,11 +40,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0 stloc.0 @@ -1832,10 +1832,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept_il_d.ilproj index a0a3682528dca..b52e5767cb4a6 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept_il_r.ilproj index fa3a08d3a03e0..55d368e7c5512 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/cascadedexcept_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch.il b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch.il index 00a0066375f8d..7f2f6392fdd60 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch.il +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module cascadedcatch.exe @@ -20,7 +20,7 @@ int32 V_0, int32 V1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -334,11 +334,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0 stloc.0 @@ -1670,10 +1670,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch_il_d.ilproj index 723602640f6b8..ee42e405fbd10 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch_il_r.ilproj index 41ba32ba3e139..43452007cc1d2 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatch_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin.il b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin.il index 914b92c850468..00c8ce18837ce 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin.il +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module throwincascadedcatchnofin.exe @@ -19,7 +19,7 @@ int32 V_0, int32 V1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -333,11 +333,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0 stloc.0 @@ -1849,10 +1849,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin_il_d.ilproj index 65b0bcc8d8102..a88fe386557ad 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin_il_r.ilproj index 468fd5ff46753..8b767273b70f7 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedcatchnofin_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept.il b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept.il index dfee82c1605d3..5eaf4dc420665 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept.il +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module throwincascadedexcept.exe @@ -20,7 +20,7 @@ int32 V_0, int32 V1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -454,11 +454,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0 stloc.0 @@ -2070,10 +2070,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept_il_d.ilproj index 1d4c421006b13..c50dd45e2f557 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept_il_r.ilproj index 10c35acce8f60..f8589442682f1 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexcept_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin.il b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin.il index 1b2db08e20f62..0602fc15437d8 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin.il +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module throwincascadedexceptnofin.exe @@ -20,7 +20,7 @@ int32 V_0, int32 V1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -484,11 +484,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0 stloc.0 @@ -2350,10 +2350,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin_il_d.ilproj index 44876f592d2d6..22d338d00ed5f 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin_il_r.ilproj index 693093f4cc844..2f967450b448d 100644 --- a/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/cascadedcatchret/throwincascadedexceptnofin_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch.cs b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch.cs index 941d24164bcee..212a9c920c007 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch.cs +++ b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch.cs @@ -57,8 +57,10 @@ static public void inFinally() Console.WriteLine("in Finally"); } - static public int Main(string[] args) + static public int Main() { + string[] args = new string[] {}; + //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_d.csproj b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_d.csproj index d669b17596257..da2113e6decd9 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_do.csproj b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_do.csproj index a9e46825c9e11..822905bb900a1 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_r.csproj b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_r.csproj index 0f23f5c2f820c..9c56660218e34 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_ro.csproj b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_ro.csproj index 2382a2433e2bb..708bf4355e347 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/cascadedcatch_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/localvarincatch.il b/src/tests/JIT/Methodical/eh/nested/general/localvarincatch.il index 1f751fde67841..a5c25e0aae552 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/localvarincatch.il +++ b/src/tests/JIT/Methodical/eh/nested/general/localvarincatch.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module localvarincatch.exe @@ -21,7 +21,7 @@ int32 V_0, int32 V1, class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -59,11 +59,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() ldc.i4 0 stloc.0 @@ -195,10 +195,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/general/localvarincatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/general/localvarincatch_il_d.ilproj index 0c4a37de47ac1..b814e762e0069 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/localvarincatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/general/localvarincatch_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/localvarincatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/general/localvarincatch_il_r.ilproj index 162a34865ccac..6a796e17b79ba 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/localvarincatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/general/localvarincatch_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally.cs b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally.cs index c940dda71f4de..1f0cbdc2e3873 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally.cs +++ b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally.cs @@ -32,7 +32,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_d.csproj b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_d.csproj index b2fbec8cef4b9..73ee291e01c72 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_do.csproj b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_do.csproj index 32022702b3443..7831838cbcd8b 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_r.csproj b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_r.csproj index 857425af76c33..ad80318b605b9 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_ro.csproj b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_ro.csproj index f481be46eaec7..28a28fe59e11e 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/methodthrowsinfinally_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally.cs b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally.cs index d1d35f1d43b5e..68621a1ec25de 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally.cs +++ b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally.cs @@ -36,7 +36,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_d.csproj b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_d.csproj index 3fe430cc537dc..87ac22c592cd7 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_do.csproj b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_do.csproj index 424d85bacd062..22dcc35478e6b 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_r.csproj b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_r.csproj index 06f7e60505638..31b9e6c254b28 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_ro.csproj b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_ro.csproj index cadeec4008e77..699100171874c 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/rethrowincatchnestedinfinally_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally.cs b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally.cs index 7d5ae5b718347..2fba0e34f9273 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally.cs +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally.cs @@ -48,7 +48,7 @@ public static void MiddleMethod() Console.WriteLine("Unreached..."); } - public static int Main(string[] args) + public static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_d.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_d.csproj index e52d7b2f5a834..c7b7f3cbefe04 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_do.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_do.csproj index ace93493384af..eaa6abf24631c 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_r.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_r.csproj index 655e65c6938f5..10a28f6bde670 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_ro.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_ro.csproj index 622bf62d6bfbb..89d5be98a8a47 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinally_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry.cs b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry.cs index 1de3e89cfd1d2..7a2595b4313bd 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry.cs +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry.cs @@ -58,7 +58,7 @@ public static void MiddleMethod() Console.WriteLine("Unreached..."); } - public static int Main(string[] args) + public static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_d.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_d.csproj index 719030f049bd8..81396a07347f9 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_do.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_do.csproj index aa50aed3a8eb2..5f310d4a78749 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_r.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_r.csproj index e38fef8e53567..523cafca8212a 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_ro.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_ro.csproj index b6fafb8697667..a559457aeb0d0 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinfinallynestedintry_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch.il b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch.il index f05d900d6f0a5..3902833523506 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch.il +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch.il @@ -9,14 +9,14 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly 'throwinnestedcatch' {} .assembly extern xunit.core {} .class private auto ansi beforefieldinit test extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -38,8 +38,8 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog test::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog test::testLog ret } @@ -50,8 +50,8 @@ ) .entrypoint - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -90,11 +90,11 @@ leave IL_END } IL_END: - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch_il_d.ilproj index ee3bb9eaaabdb..e515cc4560f67 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch_il_r.ilproj index 8a80f2d57a8ae..04aa3becd972a 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedcatch_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally.cs b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally.cs index d688519c4bf65..ce3e55cb459fa 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally.cs +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally.cs @@ -58,7 +58,7 @@ public static void MiddleMethod() Console.WriteLine("Unreached..."); } - public static int Main(string[] args) + public static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_d.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_d.csproj index 7aecd1ad5538c..188620457be0f 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_do.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_do.csproj index de7ce260940de..5a8607104b5cc 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_r.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_r.csproj index 871c49e67f344..8d33d96719a95 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_ro.csproj b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_ro.csproj index d2ab85401c04a..58c64045ef074 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/throwinnestedfinally_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally.cs b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally.cs index 54d201613ad05..dafeddd16171a 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally.cs +++ b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally.cs @@ -48,7 +48,7 @@ public static void MiddleMethod() Console.WriteLine("Done."); } - public static int Main(string[] args) + public static int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_d.csproj b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_d.csproj index 08c579c695068..033776e9935da 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_do.csproj b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_do.csproj index f8d6b6ca912f0..ad3e344d2db65 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_r.csproj b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_r.csproj index 9d7c1c55d9034..dc6bb15446495 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_ro.csproj b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_ro.csproj index 9125896c7c75c..08a32bb340a9e 100644 --- a/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/general/trycatchintryfinally_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch.il b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch.il index 8add131d3c6ce..2f8f1c742e7b0 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch.il +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nestedtrycatch.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -179,11 +179,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() begin: .try { @@ -642,10 +642,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch_il_d.ilproj index 24e6982280b0a..092458e188a12 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch_il_r.ilproj index c5a94fc0019b5..b86bf019c45ea 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtrycatch_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept.il b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept.il index 58af7df97cbee..9cf8c25aaf1cd 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept.il +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nestedtryexcept.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -179,11 +179,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() begin: .try { @@ -992,10 +992,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept_il_d.ilproj index 2c047046fee5f..543be74411224 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept_il_r.ilproj index 06206e85515e0..3af1a81c101ec 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryexcept_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault.il b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault.il index f3253ee650080..dead1524514b9 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault.il +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nestedtryfault.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -179,11 +179,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() begin: .try { @@ -592,10 +592,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault_il_d.ilproj index a6eaa709ff0ba..879fdac64ff2e 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault_il_r.ilproj index 6cd27efc8d411..15c97509e2a63 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfault_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally.il b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally.il index 0c8572f239789..2a196a54c8732 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally.il +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nestedtryfinally.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -329,11 +329,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() begin: .try { @@ -742,10 +742,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally_il_d.ilproj index 15b42810ab8ee..ccde14e3c5e0c 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally_il_r.ilproj index 56a30ce88b0c1..fd5769c4efc19 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/nestedtryfinally_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch.il b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch.il index 515522c906ca5..599ed7436ee8b 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch.il +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module throwinnestedtrycatch.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -182,11 +182,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() begin: .try { @@ -646,10 +646,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch_il_d.ilproj index 180d1624efd05..2d70095397b8a 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch_il_r.ilproj index 9d6ddf201f7bd..6dc7b6d86088f 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtrycatch_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept.il b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept.il index 0dddf75127871..d6058ff3e2b6e 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept.il +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module throwinnestedtryexcept.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -332,11 +332,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() begin: .try { @@ -1146,10 +1146,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept_il_d.ilproj index 8485506ae913a..37bc5031fd893 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept_il_r.ilproj index 006baa9ec3d23..6c9b51deb8a99 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryexcept_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault.il b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault.il index 6e6606fd378cf..94ac64ddd8e4f 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault.il +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module throwinnestedtryfault.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -329,11 +329,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() begin: .try { @@ -744,10 +744,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault_il_d.ilproj index 7cdc7b6e9128a..7fc6417667db2 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault_il_r.ilproj index 933b0b89fde00..8c78e449537c7 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfault_il_r.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally.il b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally.il index 8c8aecc99648a..08da5fd61dace 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally.il +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module throwinnestedtryfinally.exe @@ -18,7 +18,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) newobj instance void [mscorlib]System.IO.StringWriter::.ctor() @@ -329,11 +329,11 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() begin: .try { @@ -744,10 +744,10 @@ begin: done: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally_il_d.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally_il_d.ilproj index 7485d67901581..5877d8fc40945 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally_il_d.ilproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally_il_r.ilproj b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally_il_r.ilproj index da548247add13..c5e6fb55352d9 100644 --- a/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/nested/nestedtry/throwinnestedtryfinally_il_r.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50.cs b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50.cs index ca26914e76408..e0fac50cf8a05 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50.cs +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50.cs @@ -829,7 +829,7 @@ static public void foo(int i) } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_d.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_d.csproj index fc451d3c6de72..1a645df98599b 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_do.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_do.csproj index 9f05aaf9e410c..f9b08eec5959d 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_r.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_r.csproj index 7ee7d28f99302..a37ce0aa8e587 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_ro.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_ro.csproj index 6f9a084811926..4413a92debe81 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinally_50_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30.cs b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30.cs index 3b44d5481d439..c43352061d10e 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30.cs +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30.cs @@ -1401,7 +1401,7 @@ static public void foo(int i) } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_d.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_d.csproj index 551223db0b26f..37afc59e86f97 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_do.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_do.csproj index 2f26d9553569b..bbbab575c9273 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_r.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_r.csproj index f9f1a885486c1..bc4b50a83cf89 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_ro.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_ro.csproj index d0b03c903af95..739efe1dfdd66 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallynestedintry_30_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20.cs b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20.cs index 509a1193a2706..389f5e3cb5cd5 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20.cs +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20.cs @@ -1631,7 +1631,7 @@ static public void foo(int i) } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_d.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_d.csproj index 6ac54aeccab82..e6d506c7ec9f2 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_d.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_do.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_do.csproj index b375b38998122..1feb65fe447a3 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_do.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_r.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_r.csproj index c83100604e4a5..0c2937f832c1d 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_r.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_ro.csproj b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_ro.csproj index bb753bf046028..6135cd6ed8cb9 100644 --- a/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_ro.csproj +++ b/src/tests/JIT/Methodical/eh/nested/nonlocalexit/throwinfinallyrecursive_20_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/122239/outermostFinally.cs b/src/tests/JIT/Methodical/eh/regress/asurt/122239/outermostFinally.cs index 3b9b416a1009d..02c3b91d90aac 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/122239/outermostFinally.cs +++ b/src/tests/JIT/Methodical/eh/regress/asurt/122239/outermostFinally.cs @@ -26,7 +26,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static int Main(string[] args) + static int Main() { int[] array = { 1, 2, 3, 4, 5, 6 }; diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/122239/outermostFinally.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/122239/outermostFinally.csproj index d2c49963ae4f0..c7096bd5bfe84 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/122239/outermostFinally.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/122239/outermostFinally.csproj @@ -9,6 +9,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally.cs b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally.cs index c3ca67c86c988..13aac3c34a87a 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally.cs +++ b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally.cs @@ -29,7 +29,7 @@ static Class1() // Create and initialize test log object testLog = new TestUtil.TestLog(expectedOut); } - static int Main(string[] args) + static int Main() { int x = 7, y = 0, z; //Start recording diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_d.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_d.csproj index 6d8d39a677f14..866898afecfd1 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_d.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_do.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_do.csproj index d786aab5d3e9d..8a4f87c6bc825 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_do.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_r.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_r.csproj index 608a154f70f7d..7ad67f2ef6df3 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_r.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_ro.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_ro.csproj index 82f8e3b3f91fe..4709184f08b16 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_ro.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/140713/innerFinally_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_d.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_d.csproj index 3fc6753634f8f..53fb4734aae19 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_d.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_do.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_do.csproj index d8c5476b8e96c..474a329e88c52 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_do.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_r.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_r.csproj index ffc7332fa6fef..61a3aa55104f7 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_r.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_ro.csproj b/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_ro.csproj index 8f12201fc36d5..27d83dfeb3181 100644 --- a/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_ro.csproj +++ b/src/tests/JIT/Methodical/eh/regress/asurt/141358/uncaughtException_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/vswhidbey/148190/baduwinfo.csproj b/src/tests/JIT/Methodical/eh/regress/vswhidbey/148190/baduwinfo.csproj index 2e7bef65762fc..af65afdc74de1 100644 --- a/src/tests/JIT/Methodical/eh/regress/vswhidbey/148190/baduwinfo.csproj +++ b/src/tests/JIT/Methodical/eh/regress/vswhidbey/148190/baduwinfo.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/regress/vswhidbey/148190/baduwinfo1.csproj b/src/tests/JIT/Methodical/eh/regress/vswhidbey/148190/baduwinfo1.csproj index 56dcae7faf99f..9f83ef71330cc 100644 --- a/src/tests/JIT/Methodical/eh/regress/vswhidbey/148190/baduwinfo1.csproj +++ b/src/tests/JIT/Methodical/eh/regress/vswhidbey/148190/baduwinfo1.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch.cs b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch.cs index a41667d9ab2d7..94d098d2ce7de 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch.cs +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch.cs @@ -36,7 +36,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_d.csproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_d.csproj index 7aa346d9c3e9f..01858451d4904 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_d.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_do.csproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_do.csproj index 298bb09ba6dd0..745b5ebc04b6c 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_do.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_r.csproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_r.csproj index d6ddaddf1d087..b6e2c07d66fc0 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_r.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_ro.csproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_ro.csproj index 990f481cf8799..eadf876558032 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_ro.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyaftercatch_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch.il b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch.il index a16c1c351db26..cbc8f49a802c3 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch.il +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch.il @@ -7,7 +7,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly 'rethrowinfinallyinsidecatch' {} .assembly extern xunit.core {} @@ -17,7 +17,7 @@ .class private auto ansi beforefieldinit Class1 extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -48,8 +48,8 @@ callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog Test.Class1::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog Test.Class1::testLog ret } @@ -66,8 +66,8 @@ class [mscorlib]System.Exception e, int32 V_3) - ldsfld class [common]TestUtil.TestLog Test.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog Test.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -142,11 +142,11 @@ } L3: - ldsfld class [common]TestUtil.TestLog Test.Class1::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog Test.Class1::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog Test.Class1::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog Test.Class1::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch_il_d.ilproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch_il_d.ilproj index cbfe470109a19..1c3bcfb087a62 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch_il_d.ilproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch_il_d.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch_il_r.ilproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch_il_r.ilproj index 292c48d2e1e7a..7b170ed6437cd 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch_il_r.ilproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowinfinallyinsidecatch_il_r.ilproj @@ -1,16 +1,16 @@ - - - Exe - 1 - - - PdbOnly - False - - - - - - - - + + + Exe + 1 + + + PdbOnly + False + + + + + + + + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase.cs b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase.cs index 1585d10baaea2..0851b29cec52f 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase.cs +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase.cs @@ -55,7 +55,7 @@ static public void f1() } } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_d.csproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_d.csproj index a8fcf51a406a2..a70e1303588c5 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_d.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_do.csproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_do.csproj index 972eb6f3dcac3..97a3f1b613ae0 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_do.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_r.csproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_r.csproj index 1b2c3f70914d4..611f61a5cf3bb 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_r.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_ro.csproj b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_ro.csproj index 67c105208c657..5a9b99c2af3a0 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_ro.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/rethrowwithhandlerscatchingbase_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice.cs b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice.cs index 63ee47c2f881f..195be061360a7 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice.cs +++ b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice.cs @@ -68,7 +68,7 @@ static public void f1() } } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_d.csproj b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_d.csproj index 91d178c1713e2..0eaa0ee81e6a3 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_d.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_do.csproj b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_do.csproj index 950cff29109ad..ac7164570eda8 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_do.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_r.csproj b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_r.csproj index 6f1ffd19521e4..14a4c7e65f95f 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_r.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_ro.csproj b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_ro.csproj index 750ee5ef041b5..87d117d0af9fe 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_ro.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/samerethrowtwice_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice.cs b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice.cs index 86ecd1b6396ca..d7263040debdd 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice.cs +++ b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice.cs @@ -67,7 +67,7 @@ static public void f1() } } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_d.csproj b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_d.csproj index 03655c1586814..5261b784fe77b 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_d.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_d.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_do.csproj b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_do.csproj index 4d2577489fe2e..c1d394e1b023c 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_do.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_r.csproj b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_r.csproj index 3fba7dc3d9bae..4a0b8db8a2fd8 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_r.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_r.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_ro.csproj b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_ro.csproj index f9a1c3f122574..808437daf52f6 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_ro.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/samethrowtwice_ro.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow.cs b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow.cs index daa5d48dbbd64..48ee6357a8258 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow.cs +++ b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow.cs @@ -26,7 +26,7 @@ static Class1() testLog = new TestUtil.TestLog(expectedOut); } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_d.csproj b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_d.csproj index 7c6a078578c61..a3627f1d3af3a 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_d.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_do.csproj b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_do.csproj index b932a1548f3c0..02ac6a3f988f5 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_do.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_do.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_r.csproj b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_r.csproj index 5f0c32bc23f68..825982b2c9aae 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_r.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_ro.csproj b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_ro.csproj index 031fda448ca42..0d74d0bf04818 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_ro.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/simplerethrow_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase.cs b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase.cs index 32a212d1a4294..3ebfe08c752e1 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase.cs +++ b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase.cs @@ -55,7 +55,7 @@ static public void f1() } } - static public int Main(string[] args) + static public int Main() { //Start recording testLog.StartRecording(); diff --git a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_d.csproj b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_d.csproj index 9fa44535e72e2..e495a0ae80f82 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_d.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_d.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_do.csproj b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_do.csproj index 1455ba086d6e0..3e9da1b05bd7d 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_do.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_do.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_r.csproj b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_r.csproj index 8285b08c3e8e6..18709fa130cd9 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_r.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_r.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_ro.csproj b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_ro.csproj index c69b006ee7e4d..2846b1edb2a42 100644 --- a/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_ro.csproj +++ b/src/tests/JIT/Methodical/eh/rethrow/throwwithhandlerscatchingbase_ro.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Methodical/flowgraph/bug614098/intToByte.cs b/src/tests/JIT/Methodical/flowgraph/bug614098/intToByte.cs index 2b415c16d491f..a1271faf1520b 100644 --- a/src/tests/JIT/Methodical/flowgraph/bug614098/intToByte.cs +++ b/src/tests/JIT/Methodical/flowgraph/bug614098/intToByte.cs @@ -31,7 +31,7 @@ public MyStruct(ushort value) static private MyStruct[] s_myObjects = { new MyStruct(0x0100) }; - private static int Main(string[] args) + private static int Main() { MyStruct obj = s_myObjects[0]; ushort value = obj.value; diff --git a/src/tests/JIT/Methodical/flowgraph/bug619534/finallyclone.cs b/src/tests/JIT/Methodical/flowgraph/bug619534/finallyclone.cs index bfa7d3b9db7e5..d81493f9274b1 100644 --- a/src/tests/JIT/Methodical/flowgraph/bug619534/finallyclone.cs +++ b/src/tests/JIT/Methodical/flowgraph/bug619534/finallyclone.cs @@ -16,7 +16,7 @@ class ApplicationException : Exception { } public class TestClass { - public static int Main(string[] args) + public static int Main() { //this should return true; return Test() ? 100 : 101; diff --git a/src/tests/JIT/Methodical/flowgraph/bug619534/twoEndFinallys.cs b/src/tests/JIT/Methodical/flowgraph/bug619534/twoEndFinallys.cs index 8d21f89daf234..c5061549bfab2 100644 --- a/src/tests/JIT/Methodical/flowgraph/bug619534/twoEndFinallys.cs +++ b/src/tests/JIT/Methodical/flowgraph/bug619534/twoEndFinallys.cs @@ -28,9 +28,9 @@ private Test() _temp = 101; } - private static int Main(string[] args) + private static int Main() { - Test t = TwoEndFinallys(args); + Test t = TwoEndFinallys(new string[] {}); if (t._temp == 101) return 100; else return 101; diff --git a/src/tests/JIT/Methodical/flowgraph/dev10_bug675304/osrAddovershot.cs b/src/tests/JIT/Methodical/flowgraph/dev10_bug675304/osrAddovershot.cs index 96972c7e57e81..7c5445dc3f93e 100644 --- a/src/tests/JIT/Methodical/flowgraph/dev10_bug675304/osrAddovershot.cs +++ b/src/tests/JIT/Methodical/flowgraph/dev10_bug675304/osrAddovershot.cs @@ -59,7 +59,7 @@ private static MyStruct[] InitMS(int length) return ms; } - private static int Main(string[] args) + private static int Main() { MyStruct[] ms = InitMS(5); //InitMS(args.Length > 0 ? int.Parse(args[0]) : 5); //Do not expect to take in any arguments here for simplicity sake. diff --git a/src/tests/JIT/Methodical/flowgraph/dev10_bug723489/qMarkColon.cs b/src/tests/JIT/Methodical/flowgraph/dev10_bug723489/qMarkColon.cs index 6bad513509d59..be4eb2e960644 100644 --- a/src/tests/JIT/Methodical/flowgraph/dev10_bug723489/qMarkColon.cs +++ b/src/tests/JIT/Methodical/flowgraph/dev10_bug723489/qMarkColon.cs @@ -14,15 +14,10 @@ public static bool MyEquals(object obj1, object obj2) return ((obj1 as Version) == (obj2 as Version)); } - public static int Main(String[] args) + public static int Main() { Version ver0 = null; Version ver1 = null; - if (args.Length >= 2) - { - ver0 = new Version(args[0]); - ver1 = new Version(args[1]); - } bool result = MyEquals(ver0, ver1); if (result) diff --git a/src/tests/JIT/Methodical/fp/apps/BouncingBall.cs b/src/tests/JIT/Methodical/fp/apps/BouncingBall.cs index f7e8bdb21d99e..0d509c897fc57 100644 --- a/src/tests/JIT/Methodical/fp/apps/BouncingBall.cs +++ b/src/tests/JIT/Methodical/fp/apps/BouncingBall.cs @@ -8,7 +8,7 @@ class BouncingBall { - public static int Main(string[] args) + public static int Main() { double coef; double height; @@ -17,16 +17,8 @@ public static int Main(string[] args) string output; bool FirstTime; - if (args.Length >= 2) - { - coef = Convert.ToDouble(args[0]); - height = Convert.ToDouble(args[1]); - } - else - { - coef = 0.8; - height = 80.0; - } + coef = 0.8; + height = 80.0; Console.WriteLine("Coeficient of Restitution: {0}", coef); Console.WriteLine("Balls starting height : {0} m", height); diff --git a/src/tests/JIT/Methodical/inlining/boolean/InlineBool.cs b/src/tests/JIT/Methodical/inlining/boolean/InlineBool.cs index f11a40061e9b6..85bf97afae5b6 100644 --- a/src/tests/JIT/Methodical/inlining/boolean/InlineBool.cs +++ b/src/tests/JIT/Methodical/inlining/boolean/InlineBool.cs @@ -157,7 +157,7 @@ public class Program static bool Id99(bool x) { return Id04(x != false) ? true : false; } [MethodImpl(MethodImplOptions.NoOptimization)] - public static int Main(string[] args) + public static int Main() { bool result = true; diff --git a/src/tests/JIT/Methodical/localloc/call/call01_small.csproj b/src/tests/JIT/Methodical/localloc/call/call01_small.csproj index 692ad1df98a94..38c34800f67dc 100644 --- a/src/tests/JIT/Methodical/localloc/call/call01_small.csproj +++ b/src/tests/JIT/Methodical/localloc/call/call01_small.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/Methodical/nonvirtualcall/classic.cs b/src/tests/JIT/Methodical/nonvirtualcall/classic.cs index 86b14e13ee381..4333df701fe18 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/classic.cs +++ b/src/tests/JIT/Methodical/nonvirtualcall/classic.cs @@ -187,7 +187,7 @@ public static void CallFromInsideGrandChild() child.TestGrandChild(); } - public static int Main(string[] args) + public static int Main() { try { diff --git a/src/tests/JIT/Methodical/nonvirtualcall/classic.il b/src/tests/JIT/Methodical/nonvirtualcall/classic.il index 23b4645f60128..58ad342c484d4 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/classic.il +++ b/src/tests/JIT/Methodical/nonvirtualcall/classic.il @@ -30,8 +30,8 @@ .corflags 0x00000001 // ILONLY - -.class public abstract auto ansi beforefieldinit Test_classic.Base +.namespace Test_classic { +.class public abstract auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual @@ -163,7 +163,7 @@ } // end of class Test.Base -.class public auto ansi beforefieldinit Test_classic.Child +.class public auto ansi beforefieldinit Child extends Test_classic.Base { .method public hidebysig virtual final @@ -372,7 +372,7 @@ } // end of class Test.Child -.class public auto ansi beforefieldinit Test_classic.GrandChild +.class public auto ansi beforefieldinit GrandChild extends Test_classic.Child { .method public hidebysig virtual final @@ -559,7 +559,7 @@ } // end of class Test.GrandChild -.class public auto ansi sealed beforefieldinit Test_classic.SealedGrandChild +.class public auto ansi sealed beforefieldinit SealedGrandChild extends Test_classic.GrandChild { .method public hidebysig specialname rtspecialname @@ -573,7 +573,7 @@ } // end of class Test.SealedGrandChild -.class public abstract auto ansi sealed beforefieldinit Test_classic.Program +.class public abstract auto ansi sealed beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig static void CallSealedGrandChild() cil managed @@ -730,7 +730,7 @@ } // end of class Test.Program -.class public abstract auto ansi sealed beforefieldinit Test_classic.Assert +.class public abstract auto ansi sealed beforefieldinit Assert extends [mscorlib]System.Object { .method public hidebysig static void AreEqual(string left, @@ -790,6 +790,4 @@ } // end of method Assert::AreEqual } // end of class Test.Assert - - - +} diff --git a/src/tests/JIT/Methodical/nonvirtualcall/delegate.cs b/src/tests/JIT/Methodical/nonvirtualcall/delegate.cs index 9c97559bd3a7b..a3b662920ce06 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/delegate.cs +++ b/src/tests/JIT/Methodical/nonvirtualcall/delegate.cs @@ -146,7 +146,7 @@ public static void CallDelegateFromGrandChild() Assert.AreEqual("GrandChild.VirtualOverrideFinal", new TestMethod(child.VirtualOverrideFinal)); } - public static int Main(string[] args) + public static int Main() { try { diff --git a/src/tests/JIT/Methodical/nonvirtualcall/delegate.il b/src/tests/JIT/Methodical/nonvirtualcall/delegate.il index bd5a96ac21278..91b24d2723fad 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/delegate.il +++ b/src/tests/JIT/Methodical/nonvirtualcall/delegate.il @@ -30,8 +30,8 @@ .corflags 0x00000001 // ILONLY - -.class public abstract auto ansi beforefieldinit Test_delegate.Base +.namespace Test_delegate { +.class public abstract auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual @@ -163,7 +163,7 @@ } // end of class Test.Base -.class public auto ansi beforefieldinit Test_delegate.Child +.class public auto ansi beforefieldinit Child extends Test_delegate.Base { .method public hidebysig virtual final @@ -275,7 +275,7 @@ } // end of class Test.Child -.class public auto ansi beforefieldinit Test_delegate.GrandChild +.class public auto ansi beforefieldinit GrandChild extends Test_delegate.Child { .method public hidebysig virtual final @@ -373,7 +373,7 @@ } // end of class Test.GrandChild -.class public auto ansi sealed beforefieldinit Test_delegate.SealedGrandChild +.class public auto ansi sealed beforefieldinit SealedGrandChild extends Test_delegate.GrandChild { .method public hidebysig specialname rtspecialname @@ -387,7 +387,7 @@ } // end of class Test.SealedGrandChild -.class public auto ansi sealed Test_delegate.TestMethod +.class public auto ansi sealed TestMethod extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname @@ -415,7 +415,7 @@ } // end of class Test.TestMethod -.class public abstract auto ansi sealed beforefieldinit Test_delegate.Program +.class public abstract auto ansi sealed beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig static void CallDelegateFromSealedGrandChild() cil managed @@ -613,7 +613,7 @@ } // end of class Test.Program -.class public abstract auto ansi sealed beforefieldinit Test_delegate.Assert +.class public abstract auto ansi sealed beforefieldinit Assert extends [mscorlib]System.Object { .method public hidebysig static void AreEqual(string left, @@ -687,6 +687,4 @@ } // end of method Assert::AreEqual } // end of class Test.Assert - - - +} diff --git a/src/tests/JIT/Methodical/nonvirtualcall/generics.cs b/src/tests/JIT/Methodical/nonvirtualcall/generics.cs index b163666197535..5146f443bbe1a 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/generics.cs +++ b/src/tests/JIT/Methodical/nonvirtualcall/generics.cs @@ -186,7 +186,7 @@ public static void CallFromInsideGrandChild() child.TestGrandChild(); } - public static int Main(string[] args) + public static int Main() { try { diff --git a/src/tests/JIT/Methodical/nonvirtualcall/generics.il b/src/tests/JIT/Methodical/nonvirtualcall/generics.il index 02cacb8a03857..1a23c734a0e14 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/generics.il +++ b/src/tests/JIT/Methodical/nonvirtualcall/generics.il @@ -30,8 +30,8 @@ .corflags 0x00000001 // ILONLY - -.class public abstract auto ansi beforefieldinit Test_generics.Base +.namespace Test_generics { +.class public abstract auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual @@ -163,7 +163,7 @@ } // end of class Test.Base -.class public auto ansi beforefieldinit Test_generics.Child +.class public auto ansi beforefieldinit Child extends Test_generics.Base { .method public hidebysig virtual final @@ -372,7 +372,7 @@ } // end of class Test.Child -.class public auto ansi beforefieldinit Test_generics.GrandChild +.class public auto ansi beforefieldinit GrandChild extends Test_generics.Child { .method public hidebysig virtual final @@ -571,7 +571,7 @@ } // end of class Test.GrandChild -.class public auto ansi sealed beforefieldinit Test_generics.SealedGrandChild +.class public auto ansi sealed beforefieldinit SealedGrandChild extends Test_generics.GrandChild { .method public hidebysig specialname rtspecialname @@ -585,7 +585,7 @@ } // end of class Test.SealedGrandChild -.class public abstract auto ansi sealed beforefieldinit Test_generics.Program +.class public abstract auto ansi sealed beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig static void CallSealedGrandChild() cil managed @@ -742,7 +742,7 @@ } // end of class Test.Program -.class public abstract auto ansi sealed beforefieldinit Test_generics.Assert +.class public abstract auto ansi sealed beforefieldinit Assert extends [mscorlib]System.Object { .method public hidebysig static void AreEqual(string left, @@ -802,6 +802,4 @@ } // end of method Assert::AreEqual } // end of class Test.Assert - - - +} diff --git a/src/tests/JIT/Methodical/nonvirtualcall/generics2.cs b/src/tests/JIT/Methodical/nonvirtualcall/generics2.cs index 4924c1c97817c..d889a55e2b990 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/generics2.cs +++ b/src/tests/JIT/Methodical/nonvirtualcall/generics2.cs @@ -186,7 +186,7 @@ public static void CallFromInsideGrandChild() child.TestGrandChild(); } - public static int Main(string[] args) + public static int Main() { try { diff --git a/src/tests/JIT/Methodical/nonvirtualcall/generics2.il b/src/tests/JIT/Methodical/nonvirtualcall/generics2.il index 6937587cd8d98..59635af68e3bd 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/generics2.il +++ b/src/tests/JIT/Methodical/nonvirtualcall/generics2.il @@ -33,9 +33,10 @@ // Image base: 0x000000001AB30000 +.namespace Test_generics2 { // =============== CLASS MEMBERS DECLARATION =================== -.class public abstract auto ansi beforefieldinit Test_generics2.Base`1 +.class public abstract auto ansi beforefieldinit Base`1 extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual @@ -175,7 +176,7 @@ } // end of class Test.Base`1 -.class public auto ansi beforefieldinit Test_generics2.Child`1 +.class public auto ansi beforefieldinit Child`1 extends class Test_generics2.Base`1 { .method public hidebysig virtual final @@ -394,7 +395,7 @@ } // end of class Test.Child`1 -.class public auto ansi beforefieldinit Test_generics2.GrandChild`1 +.class public auto ansi beforefieldinit GrandChild`1 extends class Test_generics2.Child`1 { .method public hidebysig virtual final @@ -601,7 +602,7 @@ } // end of class Test.GrandChild`1 -.class public auto ansi sealed beforefieldinit Test_generics2.SealedGrandChild`1 +.class public auto ansi sealed beforefieldinit SealedGrandChild`1 extends class Test_generics2.GrandChild`1 { .method public hidebysig specialname rtspecialname @@ -616,7 +617,7 @@ } // end of class Test.SealedGrandChild`1 -.class public abstract auto ansi sealed beforefieldinit Test_generics2.Program +.class public abstract auto ansi sealed beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig static void CallSealedGrandChild() cil managed @@ -777,7 +778,7 @@ } // end of class Test.Program -.class public abstract auto ansi sealed beforefieldinit Test_generics2.Assert +.class public abstract auto ansi sealed beforefieldinit Assert extends [mscorlib]System.Object { .method public hidebysig static void AreEqual(string left, @@ -838,9 +839,4 @@ } // end of method Assert::AreEqual } // end of class Test.Assert - - -// ============================================================= - -// *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file nonvirtualcalls_generics2.res +} diff --git a/src/tests/JIT/Methodical/nonvirtualcall/tailcall.cs b/src/tests/JIT/Methodical/nonvirtualcall/tailcall.cs index 0bb9446a629e2..ee48c5bcf7380 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/tailcall.cs +++ b/src/tests/JIT/Methodical/nonvirtualcall/tailcall.cs @@ -187,7 +187,7 @@ public static void CallFromInsideGrandChild() child.TestGrandChild(); } - public static int Main(string[] args) + public static int Main() { try { diff --git a/src/tests/JIT/Methodical/nonvirtualcall/tailcall.il b/src/tests/JIT/Methodical/nonvirtualcall/tailcall.il index dbd642e8a7e6c..9bbb008aa5de5 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/tailcall.il +++ b/src/tests/JIT/Methodical/nonvirtualcall/tailcall.il @@ -22,9 +22,10 @@ // Image base: 0x000000001AB30000 +.namespace Test_tailcall { // =============== CLASS MEMBERS DECLARATION =================== -.class public abstract auto ansi beforefieldinit Test_tailcall.Base +.class public abstract auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual @@ -164,7 +165,7 @@ } // end of class Test.Base -.class public auto ansi beforefieldinit Test_tailcall.Child +.class public auto ansi beforefieldinit Child extends Test_tailcall.Base { .method public hidebysig virtual final @@ -347,7 +348,7 @@ } // end of class Test.Child -.class public auto ansi beforefieldinit Test_tailcall.GrandChild +.class public auto ansi beforefieldinit GrandChild extends Test_tailcall.Child { .method public hidebysig virtual final @@ -584,7 +585,7 @@ } // end of class Test.GrandChild -.class public abstract auto ansi sealed beforefieldinit Test_tailcall.Program +.class public abstract auto ansi sealed beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig static void CallFromInsideGrandChild() cil managed @@ -646,7 +647,7 @@ } // end of class Test.Program -.class public abstract auto ansi sealed beforefieldinit Test_tailcall.Assert +.class public abstract auto ansi sealed beforefieldinit Assert extends [mscorlib]System.Object { .method public hidebysig static void AreEqual(string left, @@ -707,9 +708,4 @@ } // end of method Assert::AreEqual } // end of class Test.Assert - - -// ============================================================= - -// *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file nonvirtualcalls_tailcall.res +} diff --git a/src/tests/JIT/Methodical/nonvirtualcall/valuetype.cs b/src/tests/JIT/Methodical/nonvirtualcall/valuetype.cs index 7d55d198a69c0..6e1b0c95660c0 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/valuetype.cs +++ b/src/tests/JIT/Methodical/nonvirtualcall/valuetype.cs @@ -31,7 +31,7 @@ public static void CallDummy() Assert.AreEqual("Dummy.Virtual", new TestMethod(dummy.Virtual)); } - public static int Main(string[] args) + public static int Main() { try { diff --git a/src/tests/JIT/Methodical/nonvirtualcall/valuetype.il b/src/tests/JIT/Methodical/nonvirtualcall/valuetype.il index fe74b777ecc02..25897d22e7940 100644 --- a/src/tests/JIT/Methodical/nonvirtualcall/valuetype.il +++ b/src/tests/JIT/Methodical/nonvirtualcall/valuetype.il @@ -32,10 +32,10 @@ .corflags 0x00000001 // ILONLY // Image base: 0x02EC0000 - +.namespace Test_valuetype { // =============== CLASS MEMBERS DECLARATION =================== -.class public sequential ansi sealed beforefieldinit Test_valuetype.Dummy +.class public sequential ansi sealed beforefieldinit Dummy extends [mscorlib]System.ValueType { .pack 0 @@ -57,7 +57,7 @@ } // end of class Test.Dummy -.class public auto ansi sealed Test_valuetype.TestMethod +.class public auto ansi sealed TestMethod extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname @@ -85,7 +85,7 @@ } // end of class Test.TestMethod -.class public abstract auto ansi sealed beforefieldinit Test_valuetype.Program +.class public abstract auto ansi sealed beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig static void CallDummy() cil managed @@ -160,7 +160,7 @@ } // end of class Test.Program -.class public abstract auto ansi sealed beforefieldinit Test_valuetype.Assert +.class public abstract auto ansi sealed beforefieldinit Assert extends [mscorlib]System.Object { .method public hidebysig static void AreEqual(string left, @@ -236,9 +236,4 @@ } // end of method Assert::AreEqual } // end of class Test.Assert - - -// ============================================================= - -// *********** DISASSEMBLY COMPLETE *********************** -// WARNING: Created Win32 resource file valuetype.res +} diff --git a/src/tests/JIT/Methodical/stringintern/test1.cs b/src/tests/JIT/Methodical/stringintern/test1.cs index 63d8fd6d5185d..d64bfce3c16b5 100644 --- a/src/tests/JIT/Methodical/stringintern/test1.cs +++ b/src/tests/JIT/Methodical/stringintern/test1.cs @@ -92,115 +92,9 @@ public static bool TestSameObjRef() return passed; } - public static bool TestDiffObjRef() + public static int Main() { - Console.WriteLine(); - Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); - Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); - Console.WriteLine("When JIT'ed, two strings always have same object reference"); - Console.WriteLine(); - Console.WriteLine("Testing DiffObjRef"); - - bool passed = true; - - if ((object)teststr1 == (object)C.teststr1) - { - Console.WriteLine("(object)teststr1 == (object)C.teststr1 is not expected. FAILED"); - passed = false; - } - - if ((object)teststr2[0] == (object)C.teststr2[0]) - { - Console.WriteLine("(object)teststr2[0] == (object)C.teststr2[0] is not expected. FAILED"); - passed = false; - } - - if (Object.ReferenceEquals((object)teststr3(), (object)C.teststr3())) - { - Console.WriteLine("(object)teststr3() == (object)C.teststr3() is not expected. FAILED"); - passed = false; - } - - // Special case for const literal teststr4 - // two consecutive LDSTR is emitted by C# compiler for the following statement - // as a result, both are interned in the same module and object comparison returns true - if ((object)teststr4 != (object)C.teststr4) - { - Console.WriteLine("(object)teststr4 != (object)C.teststr4 is not expected. FAILED"); - passed = false; - } - - // Special case for String.Empty - // String.Empty is loaded using LDSFLD, rather than LDSTR in any module - // as a result, it is always the same reference to [mscorlib]System.String::Empty, - // and object comparison return true - if ((object)teststr5 != (object)C.teststr5) - { - Console.WriteLine("(object)teststr5 != (object)C.teststr5 is not expected. FAILED"); - passed = false; - } - - if ((object)"GenC static \uC09C\u7B8B field" == (object)GenC.teststr1) - { - Console.WriteLine("(object)\"GenC static \uC09C\u7B8B field\" == (object)GenC.teststr1 is not expected. FAILED"); - passed = false; - } - - if ((object)"GenC \u3F2Aarray element 0" == (object)GenC.teststr2[0]) - { - Console.WriteLine("(object)\"GenC \u3F2Aarray element 0\" == (object)GenC.teststr2[0] is not expected. FAILED"); - passed = false; - } - - if ((object)@"GenC method return\\" == (object)GenC.teststr3()) - { - Console.WriteLine("(object)\"GenC method return\\\" == (object)GenC.teststr3() is not expected. FAILED"); - passed = false; - } - - // Special case for const literal teststr4 - // two consecutive LDSTR is emitted by C# compiler for the following statement - // as a result, both are interned in the same module and object comparison returns true - if (!Object.ReferenceEquals((object)"GenC const string\"", (object)GenC.teststr4)) - { - Console.WriteLine("(object)\"GenC const string\"\" != (object)GenC.teststr4 is not expected. FAILED"); - passed = false; - } - - // Special case for String.Empty - // String.Empty is loaded using LDSFLD, rather than LDSTR in any module - // as a result, it is always the same reference to [mscorlib]System.String::Empty, - // and object comparison return true - if ((object)teststr5 != (object)GenC.teststr5) - { - Console.WriteLine("(object)teststr5 != (object)GenC.teststr5 is not expected. FAILED"); - passed = false; - } - - return passed; - } - - public static int Main(string[] args) - { - bool passed = false; - - if ((args.Length < 1) || (args[0].ToUpper() == "SAMEOBJREF")) - passed = TestSameObjRef(); - else if (args[0].ToUpper() == "DIFFOBJREF") - passed = TestDiffObjRef(); - else - { - Console.WriteLine("Usage: Test1.exe [SameObjRef|DiffObjRef]"); - Console.WriteLine(); - Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); - Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); - Console.WriteLine("When JIT'ed, two strings always have same object reference"); - Console.WriteLine(); - return 9; - } - - Console.WriteLine(); - if (passed) + if (TestSameObjRef()) { Console.WriteLine("PASSED"); return 100; diff --git a/src/tests/JIT/Methodical/stringintern/test2.cs b/src/tests/JIT/Methodical/stringintern/test2.cs index dba1862629e0d..cd5ac6b824e85 100644 --- a/src/tests/JIT/Methodical/stringintern/test2.cs +++ b/src/tests/JIT/Methodical/stringintern/test2.cs @@ -118,130 +118,9 @@ public static bool TestSameObjRef() return passed; } - public static bool TestDiffObjRef() + public static int Main() { - Console.WriteLine(); - Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); - Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); - Console.WriteLine("When JIT'ed, two strings always have same object reference"); - Console.WriteLine(); - Console.WriteLine("Testing DiffObjRef"); - - bool passed = true; - - switch (C.teststr1) - { - case "static \uC09C\u7B8B field": - switch (C.teststr2[0]) - { - case "\u3F2Aarray element 0": - break; - default: - passed = false; - break; - } - break; - - default: - passed = false; - break; - } - - switch (C.teststr3()) - { - case @"method return\\": - switch (GenC.teststr5) - { - case "": - switch (C.teststr3()) - { - case @"method return\\": - break; - default: - passed = false; - break; - } - break; - default: - passed = false; - break; - } - break; - default: - passed = false; - break; - } - - for (int i = 1; (i < teststr2.Length) && (object)C.teststr2[i] == (object)teststr2[i]; i++) - { - Console.WriteLine("for, (object)C.teststr2[i]==(object)teststr2[i] is not expected, FAILED"); - passed = false; - } - - switch (GenC.teststr1) - { - case "static \uC09C\u7B8B field": - passed = false; - break; - default: - switch (GenC.teststr2[0]) - { - case "GenC \u3F2Aarray element 0": - break; - default: - passed = false; - break; - } - break; - } - - switch (GenC.teststr3()) - { - case @"GenC method return\\": - switch (GenC.teststr4) - { - case "GenC const string\"": - break; - default: - passed = false; - break; - } - break; - default: - passed = false; - break; - } - - for (int i = 1; (i < teststr2.Length) && (object)GenC.teststr2[i] == (object)"GenC array element 1\uCB53"; i++) - { - Console.WriteLine("for, (object)GenC.teststr2[i]==(object)C.teststr2[i] is not expected, FAILED"); - passed = false; - } - - return passed; - } - - public static int Main(string[] args) - { - bool passed = false; - - if ((args.Length < 1) || (args[0].ToUpper() == "SAMEOBJREF")) - passed = TestSameObjRef(); - else if (args[0].ToUpper() == "DIFFOBJREF") - passed = TestDiffObjRef(); - else - { - Console.WriteLine("Usage: Test2.exe [SameObjRef|DiffObjRef]"); - Console.WriteLine(); - Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); - Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); - Console.WriteLine("When JIT'ed, two strings always have same object reference"); - Console.WriteLine(); - return 9; - } - - Console.WriteLine(); - if (passed) + if (TestSameObjRef()) { Console.WriteLine("PASSED"); return 100; diff --git a/src/tests/JIT/Methodical/stringintern/test4.cs b/src/tests/JIT/Methodical/stringintern/test4.cs index 79216acee2882..eb6b0dde88dad 100644 --- a/src/tests/JIT/Methodical/stringintern/test4.cs +++ b/src/tests/JIT/Methodical/stringintern/test4.cs @@ -243,269 +243,9 @@ public static bool TestSameObjRef() return passed; } - public static bool TestDiffObjRef() + public static int Main() { - Console.WriteLine(); - Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); - Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); - Console.WriteLine("When JIT'ed, two strings always have same object reference"); - Console.WriteLine(); - Console.WriteLine("Testing DiffObjRef"); - - bool passed = true; - - string b = null; - - try - { - teststr1 = "static \uC09C\u7B8B field"; - b = C.teststr1; - throw new Exception(); - } - catch (System.Exception) - { - } - - if ((object)teststr1 == (object)b) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr1 == (object) b is NOT expected"); - } - - try - { - teststr2[0] = "\u3F2Aarray element 0"; - b = C.teststr2[0]; - throw new Exception(); - } - catch (System.Exception) - { - if ((object)teststr2[0] == (object)C.teststr2[0]) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr2[0] == (object)C.teststr2[0] is NOT expected"); - } - } - - try - { - throw new Exception(); - } - catch (System.Exception) - { - teststr2[1] = "array element 1\uCB53"; - b = C.teststr2[1]; - } - - if ((object)teststr2[1] == (object)b) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr2[1] == (object) b is NOT expected"); - } - - try - { - throw new Exception(); - } - catch (System.Exception) - { - } - finally - { - teststr2[2] = "array \u47BBelement 2"; - } - - if ((object)teststr2[2] == (object)C.teststr2[2]) - { - passed = false; - Console.WriteLine("FAILED, (object)teststr2[2] == (object)C.teststr2[2] is NOT expected"); - } - - try - { - teststr3 = @"method return\\"; - throw new Exception(); - } - catch (System.Exception) - { - if ((object)teststr3 == (object)C.teststr3()) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr3 == (object)C.teststr3() is NOT expected"); - } - try - { - } - finally - { - // Special case for const literal teststr4 - // two consecutive LDSTR is emitted by C# compiler for the following statement - // as a result, both are interned in the same module and object comparison returns true - if ((object)teststr4 != (object)C.teststr4) - { - passed = false; - Console.WriteLine("FAILED, (object)teststr4 == (object)C.teststr4 is expected"); - } - try - { - throw new Exception(); - } - catch - { - } - finally - { - teststr5 = String.Empty; - // Special case for String.Empty - // String.Empty is loaded using LDSFLD, rather than LDSTR in any module - // as a result, it is always the same reference to [mscorlib]System.String::Empty, - // and object comparison return true - if ((object)teststr5 != (object)C.teststr5) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr5 == (object)C.teststr5 is expected"); - } - } - } - } - - // Generic Class - try - { - teststr1 = "GenC static \uC09C\u7B8B field"; - b = GenC.teststr1; - throw new Exception(); - } - catch (System.Exception) - { - } - - if ((object)teststr1 == (object)b) - { - passed = false; - Console.WriteLine("FAILED, (object)teststr1 == (object)GenC.teststr1 is NOT expected"); - } - - try - { - teststr2[0] = "GenC \u3F2Aarray element 0"; - throw new Exception(); - } - catch (System.Exception) - { - if ((object)teststr2[0] == (object)GenC.teststr2[0]) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr2[0] == (object)GenC.teststr2[0] is NOT expected"); - } - } - - try - { - throw new Exception(); - } - catch (System.Exception) - { - teststr2[1] = "GenC array element 1\uCB53"; - b = GenC.teststr2[1]; - } - - if ((object)teststr2[1] == (object)b) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr2[1] == (object)GenC.teststr2[1] is NOT expected"); - } - - try - { - throw new Exception(); - } - catch (System.Exception) - { - } - finally - { - teststr2[2] = "GenC array \u47BBelement 2"; - } - - if ((object)teststr2[2] == (object)GenC.teststr2[2]) - { - passed = false; - Console.WriteLine("FAILED, (object)teststr2[2] == (object)GenC.teststr2[2] is NOT expected"); - } - - try - { - teststr3 = @"GenC method return\\"; - throw new Exception(); - } - catch (System.Exception) - { - if ((object)teststr3 == (object)GenC.teststr3()) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr3 == (object)GenC.teststr3() is NOT expected"); - } - try - { - } - finally - { - // Special case for const literal teststr4 - // two consecutive LDSTR is emitted by C# compiler for the following statement - // as a result, both are interned in the same module and object comparison returns true - if ((object)testgenstr4 != (object)GenC.teststr4) - { - passed = false; - Console.WriteLine("FAILED, (object)testgenstr4 == (object)GenC.teststr4 is expected"); - } - try - { - throw new Exception(); - } - catch - { - } - finally - { - teststr5 = String.Empty; - // Special case for String.Empty - // String.Empty is loaded using LDSFLD, rather than LDSTR in any module - // as a result, it is always the same reference to [mscorlib]System.String::Empty, - // and object comparison return true - if ((object)teststr5 != (object)GenC.teststr5) - { - passed = false; - Console.WriteLine("FAILED, (object) teststr5 == (object)GenC.teststr5 is expected"); - } - } - } - } - - return passed; - } - - public static int Main(string[] args) - { - bool passed = false; - - if ((args.Length < 1) || (args[0].ToUpper() == "SAMEOBJREF")) - passed = TestSameObjRef(); - else if (args[0].ToUpper() == "DIFFOBJREF") - passed = TestDiffObjRef(); - else - { - Console.WriteLine("Usage: Test4.exe [SameObjRef|DiffObjRef]"); - Console.WriteLine(); - Console.WriteLine("When NGEN'ed, two strings in different modules have different object reference"); - Console.WriteLine("When NGEN'ed, two strings in the same module have same object reference"); - Console.WriteLine("When JIT'ed, two strings always have same object reference"); - Console.WriteLine(); - return 9; - } - - Console.WriteLine(); - if (passed) + if (TestSameObjRef()) { Console.WriteLine("PASSED"); return 100; diff --git a/src/tests/JIT/Methodical/structs/StructWithSingleFloat.cs b/src/tests/JIT/Methodical/structs/StructWithSingleFloat.cs index 4509b8ea336ef..2e6473bfc6e92 100644 --- a/src/tests/JIT/Methodical/structs/StructWithSingleFloat.cs +++ b/src/tests/JIT/Methodical/structs/StructWithSingleFloat.cs @@ -35,7 +35,7 @@ public void Method0() return; } } - public static int Main(string[] args) + public static int Main() { new TestClass().Method0(); return s_s2_16.float_2 == 1.5f ? 100 : 0; diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_33972/Runtime_33972.cs b/src/tests/JIT/Regression/JitBlue/Runtime_33972/Runtime_33972.cs new file mode 100644 index 0000000000000..7535cd334d962 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_33972/Runtime_33972.cs @@ -0,0 +1,559 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.Arm; + +class Program +{ + // CompareEqual + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_Byte_Zero(Vector64 left) + { + return AdvSimd.CompareEqual(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_SByte_Zero(Vector64 left) + { + return AdvSimd.CompareEqual(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_UInt16_Zero(Vector64 left) + { + return AdvSimd.CompareEqual(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_Int16_Zero(Vector64 left) + { + return AdvSimd.CompareEqual(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_UInt32_Zero(Vector64 left) + { + return AdvSimd.CompareEqual(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_Int32_Zero(Vector64 left) + { + return AdvSimd.CompareEqual(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_Single_Zero(Vector64 left) + { + return AdvSimd.CompareEqual(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_Byte_Zero(Vector128 left) + { + return AdvSimd.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_SByte_Zero(Vector128 left) + { + return AdvSimd.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_UInt16_Zero(Vector128 left) + { + return AdvSimd.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_Int16_Zero(Vector128 left) + { + return AdvSimd.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_UInt32_Zero(Vector128 left) + { + return AdvSimd.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_Int32_Zero(Vector128 left) + { + return AdvSimd.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_Single_Zero(Vector128 left) + { + return AdvSimd.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero(Vector128 left) + { + return AdvSimd.Arm64.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero(Vector128 left) + { + return AdvSimd.Arm64.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero(Vector128 left) + { + return AdvSimd.Arm64.CompareEqual(left, Vector128.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero(Vector64 left) + { + return AdvSimd.Arm64.CompareEqualScalar(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero(Vector64 left) + { + return AdvSimd.Arm64.CompareEqualScalar(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero(Vector64 left) + { + return AdvSimd.Arm64.CompareEqualScalar(left, Vector64.Zero); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero(Vector64 left) + { + return AdvSimd.Arm64.CompareEqualScalar(left, Vector64.Zero); + } + + // CompareEqual Swapped + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_Byte_Zero_Swapped(Vector64 right) + { + return AdvSimd.CompareEqual(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_SByte_Zero_Swapped(Vector64 right) + { + return AdvSimd.CompareEqual(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_UInt16_Zero_Swapped(Vector64 right) + { + return AdvSimd.CompareEqual(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_Int16_Zero_Swapped(Vector64 right) + { + return AdvSimd.CompareEqual(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_UInt32_Zero_Swapped(Vector64 right) + { + return AdvSimd.CompareEqual(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_Int32_Zero_Swapped(Vector64 right) + { + return AdvSimd.CompareEqual(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_CompareEqual_Vector64_Single_Zero_Swapped(Vector64 right) + { + return AdvSimd.CompareEqual(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_Byte_Zero_Swapped(Vector128 right) + { + return AdvSimd.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_SByte_Zero_Swapped(Vector128 right) + { + return AdvSimd.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_UInt16_Zero_Swapped(Vector128 right) + { + return AdvSimd.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_Int16_Zero_Swapped(Vector128 right) + { + return AdvSimd.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_UInt32_Zero_Swapped(Vector128 right) + { + return AdvSimd.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_Int32_Zero_Swapped(Vector128 right) + { + return AdvSimd.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_CompareEqual_Vector128_Single_Zero_Swapped(Vector128 right) + { + return AdvSimd.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero_Swapped(Vector128 right) + { + return AdvSimd.Arm64.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero_Swapped(Vector128 right) + { + return AdvSimd.Arm64.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector128 AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero_Swapped(Vector128 right) + { + return AdvSimd.Arm64.CompareEqual(Vector128.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero_Swapped(Vector64 right) + { + return AdvSimd.Arm64.CompareEqualScalar(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero_Swapped(Vector64 right) + { + return AdvSimd.Arm64.CompareEqualScalar(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero_Swapped(Vector64 right) + { + return AdvSimd.Arm64.CompareEqualScalar(Vector64.Zero, right); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + static Vector64 AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero_Swapped(Vector64 right) + { + return AdvSimd.Arm64.CompareEqualScalar(Vector64.Zero, right); + } + + // Validation + + unsafe static bool ValidateResult_Vector64(Vector64 result, T expectedElementValue) where T : unmanaged + { + var succeeded = true; + + for (var i = 0; i < (8 / sizeof(T)); i++) + { + if (!result.GetElement(i).Equals(expectedElementValue)) + { + succeeded = false; + } + } + + return succeeded; + } + + unsafe static bool ValidateResult_Vector64(Vector64 result, Vector64 expectedElementValue) where T : unmanaged + { + var succeeded = true; + + for (var i = 0; i < (8 / sizeof(T)); i++) + { + if (!result.GetElement(i).Equals(expectedElementValue.GetElement(i))) + { + succeeded = false; + } + } + + return succeeded; + } + + unsafe static bool ValidateResult_Vector128(Vector128 result, T expectedElementValue) where T : unmanaged + { + var succeeded = true; + + for (var i = 0; i < (16 / sizeof(T)); i++) + { + if (!result.GetElement(i).Equals(expectedElementValue)) + { + succeeded = false; + } + } + + return succeeded; + } + + unsafe static bool ValidateResult_Vector128(Vector128 result, Vector128 expectedElementValue) where T : unmanaged + { + var succeeded = true; + + for (var i = 0; i < (16 / sizeof(T)); i++) + { + if (!result.GetElement(i).Equals(expectedElementValue.GetElement(i))) + { + succeeded = false; + } + } + + return succeeded; + } + + static int Tests_AdvSimd() + { + var result = 100; + + // Begin CompareEqual Tests + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_Byte_Zero(Vector64.Zero), Byte.MaxValue)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_SByte_Zero(Vector64.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_UInt16_Zero(Vector64.Zero), UInt16.MaxValue)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_Int16_Zero(Vector64.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_UInt32_Zero(Vector64.Zero), UInt32.MaxValue)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_Int32_Zero(Vector64.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_Single_Zero(Vector64.Zero), Single.NaN)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_Byte_Zero(Vector128.Zero), Byte.MaxValue)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_SByte_Zero(Vector128.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_UInt16_Zero(Vector128.Zero), UInt16.MaxValue)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_Int16_Zero(Vector128.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_UInt32_Zero(Vector128.Zero), UInt32.MaxValue)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_Int32_Zero(Vector128.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_Single_Zero(Vector128.Zero), Single.NaN)) + result = -1; + + // End CompareEqual Tests + + return result; + } + + static int Tests_AdvSimd_Swapped() + { + var result = 100; + + // Begin CompareEqual Tests + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_Byte_Zero_Swapped(Vector64.Zero), Byte.MaxValue)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_SByte_Zero_Swapped(Vector64.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_UInt16_Zero_Swapped(Vector64.Zero), UInt16.MaxValue)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_Int16_Zero_Swapped(Vector64.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_UInt32_Zero_Swapped(Vector64.Zero), UInt32.MaxValue)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_Int32_Zero_Swapped(Vector64.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_CompareEqual_Vector64_Single_Zero_Swapped(Vector64.Zero), Single.NaN)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_Byte_Zero_Swapped(Vector128.Zero), Byte.MaxValue)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_SByte_Zero_Swapped(Vector128.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_UInt16_Zero_Swapped(Vector128.Zero), UInt16.MaxValue)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_Int16_Zero_Swapped(Vector128.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_UInt32_Zero_Swapped(Vector128.Zero), UInt32.MaxValue)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_Int32_Zero_Swapped(Vector128.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_CompareEqual_Vector128_Single_Zero_Swapped(Vector128.Zero), Single.NaN)) + result = -1; + + // End CompareEqual Tests + + return result; + } + + static int Tests_AdvSimd_Arm64() + { + var result = 100; + + // Begin CompareEqual Tests + + if (!ValidateResult_Vector128(AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero(Vector128.Zero), Double.NaN)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero(Vector128.Zero), UInt64.MaxValue)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero(Vector128.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero(Vector64.Zero), Vector64.CreateScalar(Single.NaN))) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero(Vector64.Zero), Vector64.CreateScalar(Double.NaN))) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero(Vector64.Zero), Vector64.CreateScalar(UInt64.MaxValue))) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero(Vector64.Zero), Vector64.CreateScalar(-1L))) + result = -1; + + // End CompareEqual Tests + + return result; + } + + static int Tests_AdvSimd_Arm64_Swapped() + { + var result = 100; + + // Begin CompareEqual Tests + + if (!ValidateResult_Vector128(AdvSimd_Arm64_CompareEqual_Vector128_Double_Zero_Swapped(Vector128.Zero), Double.NaN)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_Arm64_CompareEqual_Vector128_UInt64_Zero_Swapped(Vector128.Zero), UInt64.MaxValue)) + result = -1; + + if (!ValidateResult_Vector128(AdvSimd_Arm64_CompareEqual_Vector128_Int64_Zero_Swapped(Vector128.Zero), -1)) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_Arm64_CompareEqualScalar_Vector64_Single_Zero_Swapped(Vector64.Zero), Vector64.CreateScalar(Single.NaN))) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_Arm64_CompareEqualScalar_Vector64_Double_Zero_Swapped(Vector64.Zero), Vector64.CreateScalar(Double.NaN))) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_Arm64_CompareEqualScalar_Vector64_UInt64_Zero_Swapped(Vector64.Zero), Vector64.CreateScalar(UInt64.MaxValue))) + result = -1; + + if (!ValidateResult_Vector64(AdvSimd_Arm64_CompareEqualScalar_Vector64_Int64_Zero_Swapped(Vector64.Zero), Vector64.CreateScalar(-1L))) + result = -1; + + // End CompareEqual Tests + + return result; + } + + static int Main(string[] args) + { + var result = 100; + + if (AdvSimd.IsSupported) + { + Console.WriteLine("Testing AdvSimd"); + + if (result != -1) + { + result = Tests_AdvSimd(); + } + if (result != -1) + { + result = Tests_AdvSimd_Swapped(); + } + + if (result == -1) + { + Console.WriteLine("AdvSimd Tests Failed"); + } + else + { + Console.WriteLine("AdvSimd Tests Passed"); + } + } + else + { + Console.WriteLine("Skipped AdvSimd Tests"); + } + + if (AdvSimd.Arm64.IsSupported) + { + Console.WriteLine("Testing AdvSimd_Arm64"); + + if (result != -1) + { + result = Tests_AdvSimd_Arm64(); + } + if (result != -1) + { + result = Tests_AdvSimd_Arm64_Swapped(); + } + + if (result == -1) + { + Console.WriteLine("AdvSimd_Arm64 Tests Failed"); + } + else + { + Console.WriteLine("AdvSimd_Arm64 Tests Passed"); + } + } + else + { + Console.WriteLine("Skipped AdvSimd_Arm64 Tests"); + } + + return result; + } +} diff --git a/src/tests/JIT/Methodical/NaN/arithm32_cs_ro.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_33972/Runtime_33972.csproj similarity index 71% rename from src/tests/JIT/Methodical/NaN/arithm32_cs_ro.csproj rename to src/tests/JIT/Regression/JitBlue/Runtime_33972/Runtime_33972.csproj index 0e464aed7200c..bf6f589eb325b 100644 --- a/src/tests/JIT/Methodical/NaN/arithm32_cs_ro.csproj +++ b/src/tests/JIT/Regression/JitBlue/Runtime_33972/Runtime_33972.csproj @@ -1,13 +1,13 @@ Exe - 1 None True + True - + diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_34587/Runtime_34587.cs b/src/tests/JIT/Regression/JitBlue/Runtime_34587/Runtime_34587.cs index 46718c9911d3b..543e6b5804158 100644 --- a/src/tests/JIT/Regression/JitBlue/Runtime_34587/Runtime_34587.cs +++ b/src/tests/JIT/Regression/JitBlue/Runtime_34587/Runtime_34587.cs @@ -2,7 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Numerics; using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; @@ -69,6 +71,12 @@ public static int Main() TestLibrary.TestFramework.LogInformation($" Sha1.Arm64: {Sha1.Arm64.IsSupported}"); TestLibrary.TestFramework.LogInformation($" Sha256.Arm64: {Sha256.Arm64.IsSupported}"); + TestLibrary.TestFramework.LogInformation("Supported Cross Platform ISAs:"); + TestLibrary.TestFramework.LogInformation($" Vector: {Vector.IsHardwareAccelerated}; {Vector.Count}"); + TestLibrary.TestFramework.LogInformation($" Vector64: {Vector64.IsHardwareAccelerated}"); + TestLibrary.TestFramework.LogInformation($" Vector128: {Vector128.IsHardwareAccelerated}"); + TestLibrary.TestFramework.LogInformation($" Vector256: {Vector256.IsHardwareAccelerated}"); + bool succeeded = true; succeeded &= ValidateArm(); @@ -89,6 +97,10 @@ private static bool ValidateArm() succeeded &= ValidateRdm(); succeeded &= ValidateSha1(); succeeded &= ValidateSha256(); + succeeded &= ValidateVectorT(); + succeeded &= ValidateVector64(); + succeeded &= ValidateVector128(); + succeeded &= ValidateVector256(); return succeeded; @@ -235,6 +247,58 @@ static bool ValidateSha256() return succeeded; } + + static bool ValidateVectorT() + { + bool succeeded = true; + + if (AdvSimd.IsSupported) + { + succeeded &= Vector.IsHardwareAccelerated; + succeeded &= Vector.Count == 16; + } + + return succeeded; + } + + static bool ValidateVector64() + { + bool succeeded = true; + + if (AdvSimd.IsSupported) + { + succeeded &= Vector64.IsHardwareAccelerated; + succeeded &= Vector64.Count == 8; + } + + return succeeded; + } + + static bool ValidateVector128() + { + bool succeeded = true; + + if (AdvSimd.IsSupported) + { + succeeded &= Vector128.IsHardwareAccelerated; + succeeded &= Vector128.Count == 16; + } + + return succeeded; + } + + static bool ValidateVector256() + { + bool succeeded = true; + + if (AdvSimd.IsSupported) + { + succeeded &= !Vector256.IsHardwareAccelerated; + succeeded &= Vector256.Count == 32; + } + + return succeeded; + } } public static bool ValidateX86() @@ -257,6 +321,10 @@ public static bool ValidateX86() succeeded &= ValidateLzcnt(); succeeded &= ValidatePclmulqdq(); succeeded &= ValidatePopcnt(); + succeeded &= ValidateVectorT(); + succeeded &= ValidateVector64(); + succeeded &= ValidateVector128(); + succeeded &= ValidateVector256(); return succeeded; @@ -547,5 +615,67 @@ static bool ValidatePopcnt() return succeeded; } + + static bool ValidateVectorT() + { + bool succeeded = true; + + if (Avx2.IsSupported) + { + succeeded &= Vector.IsHardwareAccelerated; + succeeded &= Vector.Count == 32; + } + else if (Sse2.IsSupported) + { + succeeded &= Vector.IsHardwareAccelerated; + succeeded &= Vector.Count == 16; + } + + return succeeded; + } + + static bool ValidateVector64() + { + bool succeeded = true; + + if (Sse.IsSupported) + { + succeeded &= !Vector64.IsHardwareAccelerated; + succeeded &= Vector64.Count == 8; + } + + return succeeded; + } + + static bool ValidateVector128() + { + bool succeeded = true; + + if (Sse.IsSupported) + { + succeeded &= Vector128.IsHardwareAccelerated; + succeeded &= Vector128.Count == 16; + } + + return succeeded; + } + + static bool ValidateVector256() + { + bool succeeded = true; + + if (Avx.IsSupported) + { + succeeded &= Vector256.IsHardwareAccelerated; + succeeded &= Vector256.Count == 32; + } + else if (Sse.IsSupported) + { + succeeded &= !Vector256.IsHardwareAccelerated; + succeeded &= Vector256.Count == 32; + } + + return succeeded; + } } } diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.cs b/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.cs new file mode 100644 index 0000000000000..791037a867088 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Text; +using System.Text.Encodings.Web; + +namespace Runtime_60035 +{ + class Program + { + static int Main(string[] args) + { + byte[] inputBytes = Encoding.UTF8.GetBytes("https://github.com/dotnet/runtime"); + Console.WriteLine(UrlEncoder.Default.FindFirstCharacterToEncodeUtf8(inputBytes)); + return 100; + } + } +} diff --git a/src/tests/JIT/Methodical/NaN/arithm64_cs_ro.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.csproj similarity index 67% rename from src/tests/JIT/Methodical/NaN/arithm64_cs_ro.csproj rename to src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.csproj index f2be2ec44a34c..5f1746c4cabc3 100644 --- a/src/tests/JIT/Methodical/NaN/arithm64_cs_ro.csproj +++ b/src/tests/JIT/Regression/JitBlue/Runtime_60035/Runtime_60035.csproj @@ -1,12 +1,11 @@ - - Exe - None True + Exe + net6.0 - + diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_62108/Runtime_62108.cs b/src/tests/JIT/Regression/JitBlue/Runtime_62108/Runtime_62108.cs new file mode 100644 index 0000000000000..a4e5e9dfc0164 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_62108/Runtime_62108.cs @@ -0,0 +1,43 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; + +public class Runtime_62108 +{ + public static int Main(string[] args) + { + try + { + new Runtime_62108().LeafMethod6(); + } + catch (DivideByZeroException) + { + return 100; + } + + return 101; + } + + public struct S1 + { + public struct S1_D1_F1 + { + public double double_2; + } + public int int_4; + } + + static S1 s_s1_23 = new S1(); + static int s_int_14 = 2; + + S1 s1_40 = new S1(); + + [MethodImpl(MethodImplOptions.NoInlining)] + public int LeafMethod6() + { + return s_s1_23.int_4 / 15 + 4 << (s_int_14 |= s_int_14 / (s_s1_23.int_4 += s1_40.int_4) + 41); + } +} diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_62108/Runtime_62108.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_62108/Runtime_62108.csproj new file mode 100644 index 0000000000000..228aaa253acfc --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_62108/Runtime_62108.csproj @@ -0,0 +1,17 @@ + + + Exe + True + + + + + + + \ No newline at end of file diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_63610/Runtime_63610.cs b/src/tests/JIT/Regression/JitBlue/Runtime_63610/Runtime_63610.cs new file mode 100644 index 0000000000000..8b6bcd39894b2 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_63610/Runtime_63610.cs @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Runtime.CompilerServices; + +public class Runtime_63610 +{ + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Test(int[] x) + { + try + { + Callee1(x); + } + catch + { + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Callee1(int[] x) => Callee2(x, 0); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static int Callee2(int[] x, int index) + { + if (x == null) + Callee3(); + + return x.Length; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void Callee3() {} + + public static int Main() + { + // Make sure it doesn't assert + // https://github.com/dotnet/runtime/issues/63610 + Test(new int[42]); + return 100; + } +} diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_63610/Runtime_63610.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_63610/Runtime_63610.csproj new file mode 100644 index 0000000000000..f492aeac9d056 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_63610/Runtime_63610.csproj @@ -0,0 +1,9 @@ + + + Exe + True + + + + + \ No newline at end of file diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_63942/Runtime_63942.cs b/src/tests/JIT/Regression/JitBlue/Runtime_63942/Runtime_63942.cs new file mode 100644 index 0000000000000..a4abd8fd4bf63 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_63942/Runtime_63942.cs @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// Found by Antigen + +public class Runtime_63942 +{ + public static int Main() + { + var _ = 3.14.ToString(); + return 100; + } +} diff --git a/src/tests/JIT/Regression/JitBlue/Runtime_63942/Runtime_63942.csproj b/src/tests/JIT/Regression/JitBlue/Runtime_63942/Runtime_63942.csproj new file mode 100644 index 0000000000000..9756f0815d4d6 --- /dev/null +++ b/src/tests/JIT/Regression/JitBlue/Runtime_63942/Runtime_63942.csproj @@ -0,0 +1,21 @@ + + + Exe + True + + + + + + + \ No newline at end of file diff --git a/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b14324/b14324.ilproj b/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b14324/b14324.ilproj index 085ffeeb0be14..cd05b15478e76 100644 --- a/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b14324/b14324.ilproj +++ b/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b14324/b14324.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b14324/repro.il b/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b14324/repro.il index 5ddb33eaca0f4..11f00d3e400ee 100644 --- a/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b14324/repro.il +++ b/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M01/b14324/repro.il @@ -1,6 +1,6 @@ // Test localloc with tail call followed by jump .assembly extern legacy library mscorlib {} -.assembly extern common{} +.assembly extern localloc_common{} .assembly extern legacy library mscorlib {} .assembly 'repro'{} .assembly extern xunit.core {} @@ -28,7 +28,7 @@ IL_0012: ldloc.0 IL_0013: ldsfld int32 LocallocTest::locallocSize IL_0018: ldc.i4 1000 - IL_001d: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_001d: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0032: newobj instance void LocallocTest::.ctor() @@ -72,7 +72,7 @@ IL_0021: ldarg.s ar1 IL_0023: ldsfld int32 LocallocTest::locallocSize IL_0028: ldc.i4 1000 - IL_002d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_002d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b14355/b14355.ilproj b/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b14355/b14355.ilproj index 4d8cd6db8cd7c..a997b20fc34f9 100644 --- a/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b14355/b14355.ilproj +++ b/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b14355/b14355.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b14355/call01.il b/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b14355/call01.il index 44f52cbcb6b05..b67b0ab4749fa 100644 --- a/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b14355/call01.il +++ b/src/tests/JIT/Regression/VS-ia64-JIT/V1.2-M02/b14355/call01.il @@ -13,7 +13,7 @@ .assembly extern mscorlib { } -.assembly extern common +.assembly extern localloc_common { .ver 0:0:0:0 } @@ -56,27 +56,27 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 IL_0019: ldc.i4.4 - IL_001a: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_001a: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_001f: mul IL_0020: localloc IL_0022: stloc.3 - IL_0023: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0023: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0028: stsfld int32 LocallocTest::locallocSize IL_002d: ldloc.2 IL_002e: ldsfld int32 LocallocTest::locallocSize IL_0033: ldc.i4 0x3e8 - IL_0038: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0038: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_003d: ldloc.3 IL_003e: ldsfld int32 LocallocTest::locallocSize IL_0043: ldc.i4 0x7d0 - IL_0048: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0048: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_004d: ldc.i4.1 @@ -109,7 +109,7 @@ IL_0069: ldloc.2 IL_006a: ldsfld int32 LocallocTest::locallocSize IL_006f: ldc.i4 0x3e8 - IL_0074: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -123,7 +123,7 @@ IL_0085: ldloc.3 IL_0086: ldsfld int32 LocallocTest::locallocSize IL_008b: ldc.i4 0x7d0 - IL_0090: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0090: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -136,7 +136,7 @@ IL_009c: ldstr "local1" IL_00a1: ldloc.0 IL_00a2: ldc.i8 0xfedcba9876543210 - IL_00ab: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ab: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, uint64, uint64) IL_00b0: brtrue.s IL_00b7 @@ -148,7 +148,7 @@ IL_00b7: ldstr "local2" IL_00bc: ldloc.1 IL_00bd: ldc.i8 0xfedcba9876543211 - IL_00c6: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00c6: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, uint64, uint64) IL_00cb: brtrue.s IL_00d2 @@ -217,32 +217,32 @@ IL_0020: ldstr "error\n" IL_0025: call void [System.Console]System.Console::WriteLine(string) IL_002a: ldc.i4.4 - IL_002b: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_002b: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0030: mul IL_0031: localloc IL_0033: stloc.0 IL_0034: ldc.i4.4 - IL_0035: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0035: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_003a: mul IL_003b: localloc IL_003d: stloc.1 IL_003e: ldloc.0 IL_003f: ldsfld int32 LocallocTest::locallocSize IL_0044: ldc.i4 0xbb8 - IL_0049: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0049: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_004e: ldloc.1 IL_004f: ldsfld int32 LocallocTest::locallocSize IL_0054: ldc.i4 0xfa0 - IL_0059: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0059: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_005e: ldstr "ar1" IL_0063: ldarg.s ar1 IL_0065: ldsfld int32 LocallocTest::locallocSize IL_006a: ldc.i4 0x3e8 - IL_006f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -256,7 +256,7 @@ IL_007f: ldarg.s ar2 IL_0081: ldsfld int32 LocallocTest::locallocSize IL_0086: ldc.i4 0x7d0 - IL_008b: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_008b: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -270,7 +270,7 @@ IL_009b: ldloc.0 IL_009c: ldsfld int32 LocallocTest::locallocSize IL_00a1: ldc.i4 0xbb8 - IL_00a6: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00a6: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -284,7 +284,7 @@ IL_00b6: ldloc.1 IL_00b7: ldsfld int32 LocallocTest::locallocSize IL_00bc: ldc.i4 0xfa0 - IL_00c1: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00c1: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/Stress/ABI/Callee.cs b/src/tests/JIT/Stress/ABI/Callee.cs index 70da14bc03763..89f4ac378467f 100644 --- a/src/tests/JIT/Stress/ABI/Callee.cs +++ b/src/tests/JIT/Stress/ABI/Callee.cs @@ -12,8 +12,10 @@ namespace ABIStress { class Callee { - private static readonly MethodInfo s_hashCodeAddMethod = - typeof(HashCode).GetMethods().Single(mi => mi.Name == "Add" && mi.GetParameters().Length == 1); + private static readonly MethodInfo s_memoryMarshalCreateReadOnlySpanMethod = + typeof(MemoryMarshal).GetMethod("CreateReadOnlySpan").MakeGenericMethod(typeof(byte)); + private static readonly MethodInfo s_hashCodeAddBytesMethod = + typeof(HashCode).GetMethod("AddBytes"); private static readonly MethodInfo s_hashCodeToHashCodeMethod = typeof(HashCode).GetMethod("ToHashCode"); @@ -51,8 +53,12 @@ public void Emit() { TypeEx pm = Parameters[i]; g.Emit(OpCodes.Ldloca, hashCode); - g.Emit(OpCodes.Ldarg, checked((short)i)); - g.Emit(OpCodes.Call, s_hashCodeAddMethod.MakeGenericMethod(pm.Type)); + + g.Emit(OpCodes.Ldarga, checked((short)i)); + g.Emit(OpCodes.Ldc_I4, pm.Size); + g.Emit(OpCodes.Call, s_memoryMarshalCreateReadOnlySpanMethod); + + g.Emit(OpCodes.Call, s_hashCodeAddBytesMethod); } g.Emit(OpCodes.Ldloca, hashCode); diff --git a/src/tests/JIT/Stress/ABI/Config.cs b/src/tests/JIT/Stress/ABI/Config.cs index db4a68d77dbb5..9a889672b5342 100644 --- a/src/tests/JIT/Stress/ABI/Config.cs +++ b/src/tests/JIT/Stress/ABI/Config.cs @@ -12,7 +12,7 @@ internal class Config internal const string PInvokerPrefix = "ABIStress_PInvoker"; internal const string PInvokeePrefix = "ABIStress_PInvokee"; - internal const string InstantiatingStubPrefix = "ABIStress_InstantiatingStub_"; + internal const string StubPrefix = "ABIStress_Stub_"; internal static StressModes StressModes { get; set; } = StressModes.None; diff --git a/src/tests/JIT/Stress/ABI/Program.cs b/src/tests/JIT/Stress/ABI/Program.cs index 6fa983005e674..8eab812a5748c 100644 --- a/src/tests/JIT/Stress/ABI/Program.cs +++ b/src/tests/JIT/Stress/ABI/Program.cs @@ -24,7 +24,7 @@ static void Usage() Console.WriteLine("Usage: [--verbose] [--caller-index ] [--num-calls ] [--tailcalls] [--pinvokes] [--instantiatingstubs] [--unboxingstubs] [--sharedgenericunboxingstubs] [--max-params ] [--no-ctrlc-summary]"); Console.WriteLine("Either --caller-index or --num-calls must be specified."); Console.WriteLine("Example: --num-calls 100"); - Console.WriteLine(" Stress first 100 tailcalls and pinvokes"); + Console.WriteLine(" Stress first 100 of all kinds"); Console.WriteLine("Example: --tailcalls --caller-index 37 --verbose"); Console.WriteLine(" Stress tailcaller 37, verbose output"); Console.WriteLine("Example: --pinvokes --num-calls 1000"); @@ -263,7 +263,7 @@ private static (object callerResult, object calleeResult) InvokeCallerCallee( Console.WriteLine("Invoking caller through reflection with args"); for (int j = 0; j < outerArgs.Length; j++) { - Console.Write($"arg{j}="); + Console.Write($"arg{j}({outerArgs[j].GetType().Name})="); DumpObject(outerArgs[j]); } } @@ -275,7 +275,7 @@ private static (object callerResult, object calleeResult) InvokeCallerCallee( Console.WriteLine("Invoking callee through reflection with args"); for (int j = 0; j < innerArgs.Length; j++) { - Console.Write($"arg{j}="); + Console.Write($"arg{j}({innerArgs[j].GetType().Name})="); DumpObject(innerArgs[j]); } } @@ -329,7 +329,7 @@ public static void EmitDumpValues(string listName, ILGenerator g, IEnumerable pms; do { pms = RandomParameters(s_allTypes, rand); - } while (pms.Count > 16); + } while (pms.Count > 16); // GetDelegateType supports only up to 16 arguments Type delegateType = GetDelegateType(pms, typeof(int)); - Callee callee = new Callee(callerName+"Callee", pms);// CreateCallee(Config.PInvokeePrefix + calleeIndex, s_allTypes); + Callee callee = new Callee(callerName+"Callee", pms); callee.Emit(); Delegate calleeDelegate = callee.Method.CreateDelegate(delegateType); diff --git a/src/tests/JIT/Methodical/eh/common/common.cs b/src/tests/JIT/common/eh_common.cs similarity index 89% rename from src/tests/JIT/Methodical/eh/common/common.cs rename to src/tests/JIT/common/eh_common.cs index a8c0c73397eaa..bac1a9dc14793 100644 --- a/src/tests/JIT/Methodical/eh/common/common.cs +++ b/src/tests/JIT/common/eh_common.cs @@ -95,8 +95,8 @@ public class TestLog protected string expectedOut; protected string expectedError; - protected TextWriter stdOut; - protected TextWriter stdError; + protected static TextWriter stdOut = System.Console.Out; + protected static TextWriter stdError = System.Console.Error; protected StringWriter testOut; protected StringWriter testError; @@ -114,16 +114,15 @@ public TestLog(object expOut, object expError) { this.expectedOut = expOut == null ? String.Empty : expOut.ToString(); this.expectedError = expError == null ? String.Empty : expError.ToString(); - this.stdOut = System.Console.Out; - this.stdError = System.Console.Error; - this.testOut = new StringRecorder(this.stdOut, this.expectedOut != null ? this.expectedOut.ToString().Length * OUTPUT_LIMIT_FACTOR : 0); - this.testError = new StringRecorder(this.stdError, this.expectedError != null ? this.expectedError.ToString().Length * OUTPUT_LIMIT_FACTOR : 0); } // Start recoding by redirecting both stdout and stderr to // string recorders. public void StartRecording() { + this.testOut = new StringRecorder(stdOut, this.expectedOut != null ? this.expectedOut.ToString().Length * OUTPUT_LIMIT_FACTOR : 0); + this.testError = new StringRecorder(stdError, this.expectedError != null ? this.expectedError.ToString().Length * OUTPUT_LIMIT_FACTOR : 0); + System.Console.SetOut(this.testOut); System.Console.SetError(this.testError); } @@ -135,8 +134,8 @@ public void StopRecording() // For now we disable the ability of stop recoding, so that we still recoed until the program exits. // This issue came up with finally being called twice. The first time we stop recoding and from this // point on we loose all output. - // System.Console.SetOut(this.stdOut); - // System.Console.SetError(this.stdError); + // System.Console.SetOut(stdOut); + // System.Console.SetError(stdError); } // Returns true if both expected output and expected error are @@ -215,23 +214,26 @@ protected string Diff() // diff results, and it returns failed result code. public int VerifyOutput() { + System.Console.SetOut(stdOut); + System.Console.SetError(stdError); + int retCode = -1; string diff = this.Diff(); if (String.Empty.Equals(diff)) { - // this.stdOut.WriteLine(); - // this.stdOut.WriteLine("PASSED"); + // stdOut.WriteLine(); + // stdOut.WriteLine("PASSED"); retCode = SUCC_RET_CODE; } else { - this.stdOut.WriteLine(); - this.stdOut.WriteLine("FAILED!"); - this.stdOut.WriteLine(); - this.stdOut.WriteLine("[EXPECTED OUTPUT]"); - this.stdOut.WriteLine(this.ExpectedOutput); - this.stdOut.WriteLine("[DIFF RESULT]"); - this.stdOut.WriteLine(diff); + stdOut.WriteLine(); + stdOut.WriteLine("FAILED!"); + stdOut.WriteLine(); + stdOut.WriteLine("[EXPECTED OUTPUT]"); + stdOut.WriteLine(this.ExpectedOutput); + stdOut.WriteLine("[DIFF RESULT]"); + stdOut.WriteLine(diff); retCode = FAIL_RET_CODE; } return retCode; diff --git a/src/tests/JIT/common/eh_common.csproj b/src/tests/JIT/common/eh_common.csproj new file mode 100644 index 0000000000000..8498804738403 --- /dev/null +++ b/src/tests/JIT/common/eh_common.csproj @@ -0,0 +1,9 @@ + + + Library + False + + + + + diff --git a/src/tests/JIT/jit64/localloc/common/common.il b/src/tests/JIT/common/localloc_common.il similarity index 99% rename from src/tests/JIT/jit64/localloc/common/common.il rename to src/tests/JIT/common/localloc_common.il index 4857a3a5ed739..90955f3ac5996 100644 --- a/src/tests/JIT/jit64/localloc/common/common.il +++ b/src/tests/JIT/common/localloc_common.il @@ -5,12 +5,11 @@ .assembly extern System.Console { auto } .assembly extern mscorlib { auto } -.assembly common +.assembly localloc_common { .hash algorithm 0x00008004 .ver 0:0:0:0 } -.module common.dll .custom instance void [mscorlib]System.Security.UnverifiableCodeAttribute::.ctor() = ( 01 00 00 00 ) .imagebase 0x00400000 .subsystem 0x00000003 diff --git a/src/tests/JIT/jit64/localloc/common/common.ilproj b/src/tests/JIT/common/localloc_common.ilproj similarity index 100% rename from src/tests/JIT/jit64/localloc/common/common.ilproj rename to src/tests/JIT/common/localloc_common.ilproj diff --git a/src/tests/JIT/jit64/eh/Common/common.cs b/src/tests/JIT/jit64/eh/Common/common.cs deleted file mode 100644 index a6a0a4a1479ac..0000000000000 --- a/src/tests/JIT/jit64/eh/Common/common.cs +++ /dev/null @@ -1,279 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -// Throw in catch handler - -using System; -using System.IO; - -namespace TestUtil -{ - - // This class implements a string writer that writes to a string buffer and a - // given text writer, which allows echoing the written string if stdout is - // specified as the text writer. - - public class StringRecorder : StringWriter - { - private TextWriter outStream; - private int outLimit; // maximum output size limit in characters - private bool bufferIsFull; // if set, stop writting/recording output - - // Constructs a new StringRecorder that writes to the given TextWriter. - public StringRecorder(TextWriter ostream, int olimit) - { - if (ostream == null) - { - throw new ArgumentNullException("ostream", "Output stream cannot be null."); - } - this.outStream = ostream; - this.outLimit = olimit; - this.bufferIsFull = false; - } - - public StringRecorder(TextWriter ostream) : this(ostream, 0) - { - } - - // Only these three methods need to be overridden in order to override - // all different overloads of Write/WriteLine methods. - - public override void Write(char c) - { - if (!this.bufferIsFull) - { - outStream.Write(c); - base.Write(c); - this.CheckOverflow(); - } - } - - public override void Write(string val) - { - if (!this.bufferIsFull) - { - outStream.Write(val); - base.Write(val); - this.CheckOverflow(); - } - } - - public override void Write(char[] buffer, int index, int count) - { - if (!this.bufferIsFull) - { - outStream.Write(buffer, index, count); - base.Write(buffer, index, count); - this.CheckOverflow(); - } - } - - protected void CheckOverflow() - { - if (this.outLimit > 0 && this.ToString().Length > this.outLimit) - { - this.bufferIsFull = true; - this.outStream.WriteLine("ERROR: Output exceeded maximum limit, extra output will be discarded!"); - } - } - } - - - - // This class represents a test log. It allows for redirecting both stdout - // and stderr of the test to StringRecorder objects. The redirected output - // can then be compared to expected output supplied to the class - // constructor. - - public class TestLog - { - - const int SUCC_RET_CODE = 100; - const int FAIL_RET_CODE = 1; - const int OUTPUT_LIMIT_FACTOR = 100; - - const string IGNORE_STR = "#IGNORE#"; - - protected string expectedOut; - protected string expectedError; - protected TextWriter stdOut; - protected TextWriter stdError; - protected StringWriter testOut; - protected StringWriter testError; - - public TestLog() : this(null, null) - { - } - - public TestLog(object expOut) : this(expOut, null) - { - } - - // Creates a new TestLog and set both expected output, and - // expected error to supplied values. - public TestLog(object expOut, object expError) - { - this.expectedOut = expOut == null ? String.Empty : expOut.ToString(); - this.expectedError = expError == null ? String.Empty : expError.ToString(); - this.stdOut = System.Console.Out; - this.stdError = System.Console.Error; - this.testOut = new StringRecorder(this.stdOut, this.expectedOut != null ? this.expectedOut.ToString().Length * OUTPUT_LIMIT_FACTOR : 0); - this.testError = new StringRecorder(this.stdError, this.expectedError != null ? this.expectedError.ToString().Length * OUTPUT_LIMIT_FACTOR : 0); - } - - // Start recoding by redirecting both stdout and stderr to - // string recorders. - public void StartRecording() - { - System.Console.SetOut(this.testOut); - System.Console.SetError(this.testError); - } - - // Stop recording by resetting both stdout and stderr to their - // initial values. - public void StopRecording() - { - // For now we disable the ability of stop recoding, so that we still recoed until the program exits. - // This issue came up with finally being called twice. The first time we stop recoding and from this - // point on we loose all output. - // System.Console.SetOut(this.stdOut); - // System.Console.SetError(this.stdError); - } - - // Returns true if both expected output and expected error are - // identical to actual output and actual error; false otherwise. - protected bool Identical() - { - return this.testOut.ToString().Equals(this.expectedOut) && this.testError.ToString().Equals(this.expectedError); - } - - // Display differences between expected output and actual output. - protected string Diff() - { - string result = String.Empty; - if (!this.testOut.ToString().Equals(this.expectedOut)) - { - string newLine = this.testOut.NewLine; - string delimStr = newLine[0].ToString(); - string[] actualLines = ((this.ActualOutput.Trim()).Replace(newLine, delimStr)).Split(delimStr.ToCharArray()); - string[] expectedLines = ((this.ExpectedOutput.Trim()).Replace(newLine, delimStr)).Split(delimStr.ToCharArray()); - int commonLineCount = actualLines.Length < expectedLines.Length ? actualLines.Length : expectedLines.Length; - bool identical = true; - for (int i = 0; i < commonLineCount && identical; ++i) - { - string actualLine = actualLines[i]; - string expectedLine = expectedLines[i]; - bool similar = true; - while (!actualLine.Equals(expectedLine) && similar) - { - bool ignoreMode = false; - while (expectedLine.StartsWith(IGNORE_STR)) - { - expectedLine = expectedLine.Substring(IGNORE_STR.Length); - ignoreMode = true; - } - int nextIgnore = expectedLine.IndexOf(IGNORE_STR); - if (nextIgnore > 0) - { - string expectedToken = expectedLine.Substring(0, nextIgnore); - int at = actualLine.IndexOf(expectedToken); - similar = (at == 0) || (ignoreMode && at > 0); - expectedLine = expectedLine.Substring(nextIgnore); - actualLine = similar ? actualLine.Substring(at + expectedToken.Length) : actualLine; - } - else - { - similar = (ignoreMode && actualLine.EndsWith(expectedLine)) || actualLine.Equals(expectedLine); - expectedLine = String.Empty; - actualLine = String.Empty; - } - } - if (!similar) - { - result += ("< " + expectedLines[i] + newLine); - result += "---" + newLine; - result += ("> " + actualLines[i] + newLine); - identical = false; - } - } - if (identical) - { - for (int i = commonLineCount; i < expectedLines.Length; ++i) - { - result += ("< " + expectedLines[i] + newLine); - } - for (int i = commonLineCount; i < actualLines.Length; ++i) - { - result += ("< " + actualLines[i] + newLine); - } - } - } - return result; - } - - // Verifies test output and error strings. If identical it returns - // successful return code; otherwise it prints expected output and - // diff results, and it returns failed result code. - public int VerifyOutput() - { - int retCode = -1; - string diff = this.Diff(); - if (String.Empty.Equals(diff)) - { - // this.stdOut.WriteLine(); - // this.stdOut.WriteLine("PASSED"); - retCode = SUCC_RET_CODE; - } - else - { - this.stdOut.WriteLine(); - this.stdOut.WriteLine("FAILED!"); - this.stdOut.WriteLine(); - this.stdOut.WriteLine("[EXPECTED OUTPUT]"); - this.stdOut.WriteLine(this.ExpectedOutput); - this.stdOut.WriteLine("[DIFF RESULT]"); - this.stdOut.WriteLine(diff); - retCode = FAIL_RET_CODE; - } - return retCode; - } - - // Returns actual test output. - public string ActualOutput - { - get - { - return this.testOut.ToString(); - } - } - - // Returns actual test error. - public string ActualError - { - get - { - return this.testError.ToString(); - } - } - - // Returns expected test output. - public string ExpectedOutput - { - get - { - return this.expectedOut.ToString(); - } - } - - // Returns expected test error. - public string ExpectedError - { - get - { - return this.expectedError.ToString(); - } - } - } - -} - diff --git a/src/tests/JIT/jit64/eh/Common/common.csproj b/src/tests/JIT/jit64/eh/Common/common.csproj deleted file mode 100644 index 917b2e664b421..0000000000000 --- a/src/tests/JIT/jit64/eh/Common/common.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - Library - BuildOnly - false - - - - False - - - - - diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset1.csproj b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset1.csproj index 15036e2bebdad..81ebaed8c56fd 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset1.csproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset1.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset1_o.csproj b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset1_o.csproj index 6976cc43c8219..2abef8da58907 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset1_o.csproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset1_o.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset2.csproj b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset2.csproj index e02ec0bb6052f..d5eba66acbfef 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset2.csproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset2.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset2_o.csproj b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset2_o.csproj index 724de8af6291b..f52038eeb4d59 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset2_o.csproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset2_o.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset3.csproj b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset3.csproj index 9126a6c3006cb..354fb3bec09f2 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset3.csproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset3.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset3_o.csproj b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset3_o.csproj index 8fb310f9157eb..0c988b857a05a 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset3_o.csproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nestedTryRegionsWithSameOffset3_o.csproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitincatch.il b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitincatch.il index 1f38e97f6a591..1bf95156761b1 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitincatch.il +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitincatch.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nonlocalexitincatch.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -45,19 +45,19 @@ ldstr " in finally 2" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call void Run() ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitincatch.ilproj b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitincatch.ilproj index b47fad0e56cdd..0205c4188ecbe 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitincatch.ilproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitincatch.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally.il b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally.il index 0f7377c52ad30..d446846d89974 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally.il +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nonlocalexitinfinally.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -45,19 +45,19 @@ ldstr " in finally 2" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call void Run() ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally.ilproj b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally.ilproj index ce687e68fba9a..13c507b0746e4 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally.ilproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinfinally.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler.il b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler.il index f1fb3c16503aa..0eb70159c13ea 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler.il +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nonlocalexitinhandler.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -48,19 +48,19 @@ ldstr " in finally 2" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call void Run() ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler.ilproj b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler.ilproj index cf1306e93a76d..20c9dc98a6dea 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler.ilproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinhandler.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinroot.il b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinroot.il index 6e9c176cfce6a..3226227fd3a17 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinroot.il +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinroot.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nonlocalexitinroot.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -39,19 +39,19 @@ ldstr "in finally 2" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call void Run() ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinroot.ilproj b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinroot.ilproj index fdcb5bc0ed72f..0bbd4157df6af 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinroot.ilproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitinroot.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitintry.il b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitintry.il index cd1d68a038961..0604aae8d230d 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitintry.il +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitintry.il @@ -9,7 +9,7 @@ .ver 4:0:0:0 } .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly test {} .module nonlocalexitintry.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -45,19 +45,19 @@ ldstr "in catch" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() call void Run() ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitintry.ilproj b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitintry.ilproj index e5d8ef4996f1b..7af83ce878a37 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitintry.ilproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalexitintry.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalgotoinatryblockinahandler.csproj b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalgotoinatryblockinahandler.csproj index 348b9879546ef..ce7e56c3e9bd0 100644 --- a/src/tests/JIT/jit64/eh/FinallyExec/nonlocalgotoinatryblockinahandler.csproj +++ b/src/tests/JIT/jit64/eh/FinallyExec/nonlocalgotoinatryblockinahandler.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/Leaves/nonlocalexitfromnestedcatch.csproj b/src/tests/JIT/jit64/eh/Leaves/nonlocalexitfromnestedcatch.csproj index 2e30b0b918301..23bd18f021148 100644 --- a/src/tests/JIT/jit64/eh/Leaves/nonlocalexitfromnestedcatch.csproj +++ b/src/tests/JIT/jit64/eh/Leaves/nonlocalexitfromnestedcatch.csproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter1.il b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter1.il index 012fbbcceb116..b362ae0f79f20 100644 --- a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter1.il +++ b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter1.il @@ -11,7 +11,7 @@ .assembly extern mscorlib {} .assembly test {} .module test.exe -.assembly extern common {} +.assembly extern eh_common {} .method public static int32 Main() @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -48,11 +48,11 @@ ldstr "caught an exception!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -71,10 +71,10 @@ DONE: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter1.ilproj b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter1.ilproj index bd082b9265399..429b7e5a039ab 100644 --- a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter1.ilproj +++ b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter1.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter2.il b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter2.il index 4c0ef0a96c560..2b321f329b308 100644 --- a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter2.il +++ b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter2.il @@ -10,7 +10,7 @@ } .assembly extern mscorlib {} .assembly test {} -.assembly extern common {} +.assembly extern eh_common {} .module test.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -48,11 +48,11 @@ ldstr "caught an exception!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -71,10 +71,10 @@ DONE: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter2.ilproj b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter2.ilproj index 8e10cffff5853..f16ac19886792 100644 --- a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter2.ilproj +++ b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter2.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter3.il b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter3.il index fa0d3e8bb67fd..6121cad324710 100644 --- a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter3.il +++ b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter3.il @@ -10,7 +10,7 @@ } .assembly extern mscorlib {} .assembly test {} -.assembly extern common {} +.assembly extern eh_common {} .module test.exe @@ -20,7 +20,7 @@ .maxstack 2 .locals init ( class [mscorlib]System.IO.StringWriter expectedOut, - class [common]TestUtil.TestLog testLog + class [eh_common]TestUtil.TestLog testLog ) @@ -57,11 +57,11 @@ ldstr "caught an exception!" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) stloc.s testLog ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -80,10 +80,10 @@ DONE: ldloc.s testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() ldloc.s testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter3.ilproj b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter3.ilproj index 89ccc762cbb90..93a7d72cef9dd 100644 --- a/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter3.ilproj +++ b/src/tests/JIT/jit64/eh/basics/throwinfinallyintryfilter3.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/eh/basics/throwisfirstinstruction.il b/src/tests/JIT/jit64/eh/basics/throwisfirstinstruction.il index 90ceefe4e802f..949d0aa0fe212 100644 --- a/src/tests/JIT/jit64/eh/basics/throwisfirstinstruction.il +++ b/src/tests/JIT/jit64/eh/basics/throwisfirstinstruction.il @@ -9,13 +9,13 @@ } .assembly extern xunit.core {} .assembly extern mscorlib {} -.assembly extern common {} +.assembly extern eh_common {} .assembly 'throwisfirstinstruction' {} .class private auto ansi beforefieldinit test extends [mscorlib]System.Object { - .field private static class [common]TestUtil.TestLog testLog + .field private static class [eh_common]TestUtil.TestLog testLog .method private hidebysig specialname rtspecialname static void .cctor() cil managed { .maxstack 2 @@ -31,8 +31,8 @@ ldstr "after try" callvirt instance void [mscorlib]System.IO.TextWriter::WriteLine(string) ldloc.s expectedOut - newobj instance void [common]TestUtil.TestLog::.ctor(object) - stsfld class [common]TestUtil.TestLog test::testLog + newobj instance void [eh_common]TestUtil.TestLog::.ctor(object) + stsfld class [eh_common]TestUtil.TestLog test::testLog ret } @@ -43,8 +43,8 @@ ) .entrypoint - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance void [common]TestUtil.TestLog::StartRecording() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StartRecording() .try { @@ -63,11 +63,11 @@ ldstr "after try" call void [System.Console]System.Console::WriteLine(string) - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance void [common]TestUtil.TestLog::StopRecording() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance void [eh_common]TestUtil.TestLog::StopRecording() - ldsfld class [common]TestUtil.TestLog test::testLog - callvirt instance int32 [common]TestUtil.TestLog::VerifyOutput() + ldsfld class [eh_common]TestUtil.TestLog test::testLog + callvirt instance int32 [eh_common]TestUtil.TestLog::VerifyOutput() ret } diff --git a/src/tests/JIT/jit64/eh/basics/throwisfirstinstruction.ilproj b/src/tests/JIT/jit64/eh/basics/throwisfirstinstruction.ilproj index b345254719af3..36bb329806798 100644 --- a/src/tests/JIT/jit64/eh/basics/throwisfirstinstruction.ilproj +++ b/src/tests/JIT/jit64/eh/basics/throwisfirstinstruction.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/call/call05_dynamic.il b/src/tests/JIT/jit64/localloc/call/call05_dynamic.il index b51a997eb4e70..6b4fb63cbf68a 100644 --- a/src/tests/JIT/jit64/localloc/call/call05_dynamic.il +++ b/src/tests/JIT/jit64/localloc/call/call05_dynamic.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'call05_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -28,29 +28,29 @@ class LocallocTest V_2, int32 V_3) IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0002: mul IL_0003: localloc IL_0005: stloc.0 IL_0006: ldc.i4.4 - IL_0007: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0007: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0008: mul IL_0009: localloc IL_000b: stloc.1 - IL_000c: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_000c: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_000d: stsfld int32 LocallocTest::locallocSize IL_0012: ldloc.0 IL_0013: ldsfld int32 LocallocTest::locallocSize IL_0018: ldc.i4 1000 - IL_001d: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_001d: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0022: ldloc.1 IL_0023: ldsfld int32 LocallocTest::locallocSize IL_0028: ldc.i4 2000 - IL_002d: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002d: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) @@ -138,32 +138,32 @@ int32* intArray2, int32 V_2) IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0002: mul IL_0003: localloc IL_0005: stloc.0 IL_0006: ldc.i4.4 - IL_0007: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0007: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0008: mul IL_0009: localloc IL_000b: stloc.1 IL_000c: ldloc.0 IL_000d: ldsfld int32 LocallocTest::locallocSize IL_0012: ldc.i4 0xbb8 - IL_0017: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0017: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_001c: ldloc.1 IL_001d: ldsfld int32 LocallocTest::locallocSize IL_0022: ldc.i4 0xfa0 - IL_0027: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0027: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_002c: ldstr "ar1" IL_0031: ldarg.s ar1 IL_0033: ldsfld int32 LocallocTest::locallocSize IL_0038: ldc.i4 1000 - IL_003d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_003d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -177,7 +177,7 @@ IL_004d: ldarg.s ar2 IL_004f: ldsfld int32 LocallocTest::locallocSize IL_0054: ldc.i4 2000 - IL_0059: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0059: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -191,7 +191,7 @@ IL_0069: ldloc.0 IL_006a: ldsfld int32 LocallocTest::locallocSize IL_006f: ldc.i4 3000 - IL_0074: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -205,7 +205,7 @@ IL_0084: ldloc.1 IL_0085: ldsfld int32 LocallocTest::locallocSize IL_008a: ldc.i4 4000 - IL_008f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_008f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/call/call05_dynamic.ilproj b/src/tests/JIT/jit64/localloc/call/call05_dynamic.ilproj index 1d325a72f81f3..a87f33bc33d73 100644 --- a/src/tests/JIT/jit64/localloc/call/call05_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/call/call05_dynamic.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/call/call05_large.il b/src/tests/JIT/jit64/localloc/call/call05_large.il index abe3a04dd7e39..6a60e5f03026c 100644 --- a/src/tests/JIT/jit64/localloc/call/call05_large.il +++ b/src/tests/JIT/jit64/localloc/call/call05_large.il @@ -8,7 +8,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'call05_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -43,13 +43,13 @@ IL_0012: ldloc.0 IL_0013: ldsfld int32 LocallocTest::locallocSize IL_0018: ldc.i4 1000 - IL_001d: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_001d: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0022: ldloc.1 IL_0023: ldsfld int32 LocallocTest::locallocSize IL_0028: ldc.i4 2000 - IL_002d: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002d: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) @@ -149,20 +149,20 @@ IL_000c: ldloc.0 IL_000d: ldsfld int32 LocallocTest::locallocSize IL_0012: ldc.i4 0xbb8 - IL_0017: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0017: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_001c: ldloc.1 IL_001d: ldsfld int32 LocallocTest::locallocSize IL_0022: ldc.i4 0xfa0 - IL_0027: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0027: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_002c: ldstr "ar1" IL_0031: ldarg.s ar1 IL_0033: ldsfld int32 LocallocTest::locallocSize IL_0038: ldc.i4 1000 - IL_003d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_003d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -176,7 +176,7 @@ IL_004d: ldarg.s ar2 IL_004f: ldsfld int32 LocallocTest::locallocSize IL_0054: ldc.i4 2000 - IL_0059: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0059: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -190,7 +190,7 @@ IL_0069: ldloc.0 IL_006a: ldsfld int32 LocallocTest::locallocSize IL_006f: ldc.i4 3000 - IL_0074: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -204,7 +204,7 @@ IL_0084: ldloc.1 IL_0085: ldsfld int32 LocallocTest::locallocSize IL_008a: ldc.i4 4000 - IL_008f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_008f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/call/call05_large.ilproj b/src/tests/JIT/jit64/localloc/call/call05_large.ilproj index 01adc4f1118d9..016265d613c50 100644 --- a/src/tests/JIT/jit64/localloc/call/call05_large.ilproj +++ b/src/tests/JIT/jit64/localloc/call/call05_large.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/call/call05_small.il b/src/tests/JIT/jit64/localloc/call/call05_small.il index bef8fdb9e3f77..b8217e4cbd5e5 100644 --- a/src/tests/JIT/jit64/localloc/call/call05_small.il +++ b/src/tests/JIT/jit64/localloc/call/call05_small.il @@ -8,7 +8,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'call05_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -43,13 +43,13 @@ IL_0012: ldloc.0 IL_0013: ldsfld int32 LocallocTest::locallocSize IL_0018: ldc.i4 1000 - IL_001d: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_001d: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0022: ldloc.1 IL_0023: ldsfld int32 LocallocTest::locallocSize IL_0028: ldc.i4 2000 - IL_002d: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002d: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) @@ -149,20 +149,20 @@ IL_000c: ldloc.0 IL_000d: ldsfld int32 LocallocTest::locallocSize IL_0012: ldc.i4 0xbb8 - IL_0017: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0017: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_001c: ldloc.1 IL_001d: ldsfld int32 LocallocTest::locallocSize IL_0022: ldc.i4 0xfa0 - IL_0027: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0027: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_002c: ldstr "ar1" IL_0031: ldarg.s ar1 IL_0033: ldsfld int32 LocallocTest::locallocSize IL_0038: ldc.i4 1000 - IL_003d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_003d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -176,7 +176,7 @@ IL_004d: ldarg.s ar2 IL_004f: ldsfld int32 LocallocTest::locallocSize IL_0054: ldc.i4 2000 - IL_0059: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0059: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -190,7 +190,7 @@ IL_0069: ldloc.0 IL_006a: ldsfld int32 LocallocTest::locallocSize IL_006f: ldc.i4 3000 - IL_0074: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -204,7 +204,7 @@ IL_0084: ldloc.1 IL_0085: ldsfld int32 LocallocTest::locallocSize IL_008a: ldc.i4 4000 - IL_008f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_008f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/call/call05_small.ilproj b/src/tests/JIT/jit64/localloc/call/call05_small.ilproj index d5b22a1c1ed76..3322668227bca 100644 --- a/src/tests/JIT/jit64/localloc/call/call05_small.ilproj +++ b/src/tests/JIT/jit64/localloc/call/call05_small.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/call/call07_dynamic.il b/src/tests/JIT/jit64/localloc/call/call07_dynamic.il index d753ba25f249e..136047b6a455c 100644 --- a/src/tests/JIT/jit64/localloc/call/call07_dynamic.il +++ b/src/tests/JIT/jit64/localloc/call/call07_dynamic.il @@ -7,7 +7,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'call07_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -34,16 +34,16 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 - IL_0019: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0019: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_001e: stsfld int32 LocallocTest::locallocSize IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: newobj instance void LocallocTest::.ctor() @@ -76,7 +76,7 @@ IL_004f: ldstr "local1" IL_0054: ldloc.0 IL_0055: ldc.i8 0xfedcba9876543210 - IL_005e: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_005e: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0063: brtrue.s IL_006a @@ -88,7 +88,7 @@ IL_006a: ldstr "local2" IL_006f: ldloc.1 IL_0070: ldc.i8 0xfedcba9876543211 - IL_0079: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0079: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_007e: brtrue.s IL_0085 @@ -124,7 +124,7 @@ IL_0005: ldarg.s ar1 IL_0007: ldsfld int32 LocallocTest::locallocSize IL_000c: ldc.i4 1000 - IL_0011: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0011: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -172,20 +172,20 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 IL_0019: ldloc.2 IL_001a: ldsfld int32 LocallocTest::locallocSize IL_001f: ldc.i4 2000 - IL_0024: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0024: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0029: ldstr "local1" IL_002e: ldloc.0 IL_002f: ldc.i8 0xfedcba9876543210 - IL_0038: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0038: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_003d: brtrue.s IL_0043 @@ -196,7 +196,7 @@ IL_0043: ldstr "local2" IL_0048: ldloc.1 IL_0049: ldc.i8 0xfedcba9876543211 - IL_0052: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0057: brtrue.s IL_005d @@ -228,20 +228,20 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 IL_0019: ldloc.2 IL_001a: ldsfld int32 LocallocTest::locallocSize IL_001f: ldc.i4 3000 - IL_0024: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0024: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0029: ldstr "local1" IL_002e: ldloc.0 IL_002f: ldc.i8 0xfedcba9876543210 - IL_0038: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0038: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_003d: brtrue.s IL_0043 @@ -253,7 +253,7 @@ IL_0043: ldstr "local2" IL_0048: ldloc.1 IL_0049: ldc.i8 0xfedcba9876543211 - IL_0052: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0057: brtrue.s IL_005d @@ -265,7 +265,7 @@ IL_0062: ldarg.1 IL_0063: ldsfld int32 LocallocTest::locallocSize IL_0068: ldc.i4 1000 - IL_006d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -279,7 +279,7 @@ IL_007d: ldarg.2 IL_007e: ldsfld int32 LocallocTest::locallocSize IL_0083: ldc.i4 2000 - IL_0088: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0088: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -293,7 +293,7 @@ IL_0098: ldloc.2 IL_0099: ldsfld int32 LocallocTest::locallocSize IL_009e: ldc.i4 3000 - IL_00a3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00a3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -338,32 +338,32 @@ IL_000b: ret IL_000c: ldc.i4.4 - IL_000d: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_000d: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0012: mul IL_0013: localloc IL_0015: stloc ar3 IL_0019: ldloc.s ar3 IL_001b: ldsfld int32 LocallocTest::locallocSize IL_0020: ldc.i4 0xbb8 - IL_0025: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0025: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_002a: ldc.i4.4 - IL_002b: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_002b: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0030: mul IL_0031: localloc IL_0033: stloc.s ar4 IL_0035: ldloc.s ar4 IL_0037: ldsfld int32 LocallocTest::locallocSize IL_003c: ldc.i4 0xfa0 - IL_0041: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0041: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0046: ldstr "ar1" IL_004b: ldarg ar1 IL_004f: ldsfld int32 LocallocTest::locallocSize IL_0054: ldc.i4 0x3e8 - IL_0059: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0059: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -377,7 +377,7 @@ IL_0072: ldarg ar2 IL_0076: ldsfld int32 LocallocTest::locallocSize IL_007b: ldc.i4 0x7d0 - IL_0080: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0080: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -391,7 +391,7 @@ IL_0099: ldloc ar3 IL_009d: ldsfld int32 LocallocTest::locallocSize IL_00a2: ldc.i4 0xbb8 - IL_00a7: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00a7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -405,7 +405,7 @@ IL_00c0: ldloc ar4 IL_00c4: ldsfld int32 LocallocTest::locallocSize IL_00c9: ldc.i4 0xfa0 - IL_00ce: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00ce: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/call/call07_dynamic.ilproj b/src/tests/JIT/jit64/localloc/call/call07_dynamic.ilproj index ffa393dcfdb5f..ec1ed25880e4f 100644 --- a/src/tests/JIT/jit64/localloc/call/call07_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/call/call07_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/call/call07_small.il b/src/tests/JIT/jit64/localloc/call/call07_small.il index 774232f169d92..6df0c5a0dd369 100644 --- a/src/tests/JIT/jit64/localloc/call/call07_small.il +++ b/src/tests/JIT/jit64/localloc/call/call07_small.il @@ -7,7 +7,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'call07_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -43,7 +43,7 @@ IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: newobj instance void LocallocTest::.ctor() @@ -76,7 +76,7 @@ IL_004f: ldstr "local1" IL_0054: ldloc.0 IL_0055: ldc.i8 0xfedcba9876543210 - IL_005e: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_005e: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0063: brtrue.s IL_006a @@ -88,7 +88,7 @@ IL_006a: ldstr "local2" IL_006f: ldloc.1 IL_0070: ldc.i8 0xfedcba9876543211 - IL_0079: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0079: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_007e: brtrue.s IL_0085 @@ -124,7 +124,7 @@ IL_0005: ldarg.s ar1 IL_0007: ldsfld int32 LocallocTest::locallocSize IL_000c: ldc.i4 1000 - IL_0011: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0011: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -179,13 +179,13 @@ IL_0019: ldloc.2 IL_001a: ldsfld int32 LocallocTest::locallocSize IL_001f: ldc.i4 2000 - IL_0024: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0024: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0029: ldstr "local1" IL_002e: ldloc.0 IL_002f: ldc.i8 0xfedcba9876543210 - IL_0038: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0038: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_003d: brtrue.s IL_0043 @@ -196,7 +196,7 @@ IL_0043: ldstr "local2" IL_0048: ldloc.1 IL_0049: ldc.i8 0xfedcba9876543211 - IL_0052: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0057: brtrue.s IL_005d @@ -235,13 +235,13 @@ IL_0019: ldloc.2 IL_001a: ldsfld int32 LocallocTest::locallocSize IL_001f: ldc.i4 3000 - IL_0024: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0024: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0029: ldstr "local1" IL_002e: ldloc.0 IL_002f: ldc.i8 0xfedcba9876543210 - IL_0038: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0038: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_003d: brtrue.s IL_0043 @@ -253,7 +253,7 @@ IL_0043: ldstr "local2" IL_0048: ldloc.1 IL_0049: ldc.i8 0xfedcba9876543211 - IL_0052: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0057: brtrue.s IL_005d @@ -265,7 +265,7 @@ IL_0062: ldarg.1 IL_0063: ldsfld int32 LocallocTest::locallocSize IL_0068: ldc.i4 1000 - IL_006d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -279,7 +279,7 @@ IL_007d: ldarg.2 IL_007e: ldsfld int32 LocallocTest::locallocSize IL_0083: ldc.i4 2000 - IL_0088: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0088: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -293,7 +293,7 @@ IL_0098: ldloc.2 IL_0099: ldsfld int32 LocallocTest::locallocSize IL_009e: ldc.i4 3000 - IL_00a3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00a3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -345,7 +345,7 @@ IL_0019: ldloc.s ar3 IL_001b: ldsfld int32 LocallocTest::locallocSize IL_0020: ldc.i4 0xbb8 - IL_0025: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0025: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_002a: ldc.i4.4 @@ -356,14 +356,14 @@ IL_0035: ldloc.s ar4 IL_0037: ldsfld int32 LocallocTest::locallocSize IL_003c: ldc.i4 0xfa0 - IL_0041: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0041: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0046: ldstr "ar1" IL_004b: ldarg ar1 IL_004f: ldsfld int32 LocallocTest::locallocSize IL_0054: ldc.i4 0x3e8 - IL_0059: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0059: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -377,7 +377,7 @@ IL_0072: ldarg ar2 IL_0076: ldsfld int32 LocallocTest::locallocSize IL_007b: ldc.i4 0x7d0 - IL_0080: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0080: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -391,7 +391,7 @@ IL_0099: ldloc ar3 IL_009d: ldsfld int32 LocallocTest::locallocSize IL_00a2: ldc.i4 0xbb8 - IL_00a7: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00a7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -405,7 +405,7 @@ IL_00c0: ldloc ar4 IL_00c4: ldsfld int32 LocallocTest::locallocSize IL_00c9: ldc.i4 0xfa0 - IL_00ce: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00ce: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/call/call07_small.ilproj b/src/tests/JIT/jit64/localloc/call/call07_small.ilproj index df7dca6f570f5..8c6f65d7552b5 100644 --- a/src/tests/JIT/jit64/localloc/call/call07_small.ilproj +++ b/src/tests/JIT/jit64/localloc/call/call07_small.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh01_dynamic.csproj b/src/tests/JIT/jit64/localloc/eh/eh01_dynamic.csproj index c436fe588a060..c13f2ebf28be3 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh01_dynamic.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh01_dynamic.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh01_large.csproj b/src/tests/JIT/jit64/localloc/eh/eh01_large.csproj index d6b19431606e4..0047cacf67ea4 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh01_large.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh01_large.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh01_small.csproj b/src/tests/JIT/jit64/localloc/eh/eh01_small.csproj index 0d9ccd68eb799..1c8b1f4e321fe 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh01_small.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh01_small.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh02_dynamic.csproj b/src/tests/JIT/jit64/localloc/eh/eh02_dynamic.csproj index 218613f7ab713..100f3a2956203 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh02_dynamic.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh02_dynamic.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh02_large.csproj b/src/tests/JIT/jit64/localloc/eh/eh02_large.csproj index ceb92b78ecb7f..0cd835c20c6a1 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh02_large.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh02_large.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh02_small.csproj b/src/tests/JIT/jit64/localloc/eh/eh02_small.csproj index 29fdce2d53909..c2e763005c378 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh02_small.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh02_small.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh03_dynamic.il b/src/tests/JIT/jit64/localloc/eh/eh03_dynamic.il index a124c8d7c8667..c4a99c50776d5 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh03_dynamic.il +++ b/src/tests/JIT/jit64/localloc/eh/eh03_dynamic.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common {} +.assembly extern localloc_common {} .assembly 'eh03_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -39,29 +39,29 @@ IL_000f: add IL_0010: stloc.2 IL_0011: ldc.i4.4 - IL_0012: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0012: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0017: mul IL_0018: localloc IL_001a: stloc.3 IL_001b: ldc.i4.4 - IL_001c: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_001c: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0021: mul IL_0022: localloc IL_0024: stloc.s intArray2 - IL_0026: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0026: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_002b: stsfld int32 LocallocTest::locallocSize .try { IL_0030: ldloc.3 IL_0031: ldsfld int32 LocallocTest::locallocSize IL_0036: ldc.i4 1000 - IL_003b: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_003b: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0040: ldloc.s intArray2 IL_0042: ldsfld int32 LocallocTest::locallocSize IL_0047: ldc.i4 2000 - IL_004c: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_004c: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0051: ldstr "Test Exception" @@ -78,7 +78,7 @@ IL_0062: ldloc.3 IL_0063: ldsfld int32 LocallocTest::locallocSize IL_0068: ldc.i4 1000 - IL_006d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -90,7 +90,7 @@ IL_007b: ldloc.s intArray2 IL_007d: ldsfld int32 LocallocTest::locallocSize IL_0082: ldc.i4 2000 - IL_0087: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0087: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -109,7 +109,7 @@ IL_0095: ldloc.3 IL_0096: ldsfld int32 LocallocTest::locallocSize IL_009b: ldc.i4 1000 - IL_00a0: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00a0: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -121,7 +121,7 @@ IL_00ae: ldloc.s intArray2 IL_00b0: ldsfld int32 LocallocTest::locallocSize IL_00b5: ldc.i4 2000 - IL_00ba: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00ba: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -141,7 +141,7 @@ IL_00d2: ldloc.3 IL_00d3: ldsfld int32 LocallocTest::locallocSize IL_00d8: ldc.i4 1000 - IL_00dd: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00dd: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -155,7 +155,7 @@ IL_00ee: ldloc.s intArray2 IL_00f0: ldsfld int32 LocallocTest::locallocSize IL_00f5: ldc.i4 2000 - IL_00fa: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00fa: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -167,7 +167,7 @@ IL_0106: ldstr "local1" IL_010b: ldloc.1 IL_010c: ldc.i8 0xfedcba9876543210 - IL_0115: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0115: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_011a: brtrue.s IL_0121 @@ -179,7 +179,7 @@ IL_0121: ldstr "local2" IL_0126: ldloc.2 IL_0127: ldc.i8 0xfedcba9876543211 - IL_0130: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0130: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0135: brtrue.s IL_013c diff --git a/src/tests/JIT/jit64/localloc/eh/eh03_dynamic.ilproj b/src/tests/JIT/jit64/localloc/eh/eh03_dynamic.ilproj index c999924c0946e..51820ffdca570 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh03_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/eh/eh03_dynamic.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh03_large.il b/src/tests/JIT/jit64/localloc/eh/eh03_large.il index 784b850baf636..f259365129067 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh03_large.il +++ b/src/tests/JIT/jit64/localloc/eh/eh03_large.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common {} +.assembly extern localloc_common {} .assembly 'eh03_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -55,13 +55,13 @@ IL_0030: ldloc.3 IL_0031: ldsfld int32 LocallocTest::locallocSize IL_0036: ldc.i4 1000 - IL_003b: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_003b: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0040: ldloc.s intArray2 IL_0042: ldsfld int32 LocallocTest::locallocSize IL_0047: ldc.i4 2000 - IL_004c: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_004c: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0051: ldstr "Test Exception" @@ -78,7 +78,7 @@ IL_0062: ldloc.3 IL_0063: ldsfld int32 LocallocTest::locallocSize IL_0068: ldc.i4 1000 - IL_006d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -90,7 +90,7 @@ IL_007b: ldloc.s intArray2 IL_007d: ldsfld int32 LocallocTest::locallocSize IL_0082: ldc.i4 2000 - IL_0087: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0087: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -109,7 +109,7 @@ IL_0095: ldloc.3 IL_0096: ldsfld int32 LocallocTest::locallocSize IL_009b: ldc.i4 1000 - IL_00a0: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00a0: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -121,7 +121,7 @@ IL_00ae: ldloc.s intArray2 IL_00b0: ldsfld int32 LocallocTest::locallocSize IL_00b5: ldc.i4 2000 - IL_00ba: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00ba: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -141,7 +141,7 @@ IL_00d2: ldloc.3 IL_00d3: ldsfld int32 LocallocTest::locallocSize IL_00d8: ldc.i4 1000 - IL_00dd: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00dd: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -155,7 +155,7 @@ IL_00ee: ldloc.s intArray2 IL_00f0: ldsfld int32 LocallocTest::locallocSize IL_00f5: ldc.i4 2000 - IL_00fa: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00fa: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -167,7 +167,7 @@ IL_0106: ldstr "local1" IL_010b: ldloc.1 IL_010c: ldc.i8 0xfedcba9876543210 - IL_0115: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0115: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_011a: brtrue.s IL_0121 @@ -179,7 +179,7 @@ IL_0121: ldstr "local2" IL_0126: ldloc.2 IL_0127: ldc.i8 0xfedcba9876543211 - IL_0130: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0130: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0135: brtrue.s IL_013c diff --git a/src/tests/JIT/jit64/localloc/eh/eh03_large.ilproj b/src/tests/JIT/jit64/localloc/eh/eh03_large.ilproj index 72938c45d0e3e..e6d2aaff07308 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh03_large.ilproj +++ b/src/tests/JIT/jit64/localloc/eh/eh03_large.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh03_small.il b/src/tests/JIT/jit64/localloc/eh/eh03_small.il index 53b60ab333cbd..ebc6f454918d9 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh03_small.il +++ b/src/tests/JIT/jit64/localloc/eh/eh03_small.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common {} +.assembly extern localloc_common {} .assembly 'eh03_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -55,13 +55,13 @@ IL_0030: ldloc.3 IL_0031: ldsfld int32 LocallocTest::locallocSize IL_0036: ldc.i4 1000 - IL_003b: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_003b: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0040: ldloc.s intArray2 IL_0042: ldsfld int32 LocallocTest::locallocSize IL_0047: ldc.i4 2000 - IL_004c: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_004c: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0051: ldstr "Test Exception" @@ -78,7 +78,7 @@ IL_0062: ldloc.3 IL_0063: ldsfld int32 LocallocTest::locallocSize IL_0068: ldc.i4 1000 - IL_006d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -90,7 +90,7 @@ IL_007b: ldloc.s intArray2 IL_007d: ldsfld int32 LocallocTest::locallocSize IL_0082: ldc.i4 2000 - IL_0087: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0087: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -109,7 +109,7 @@ IL_0095: ldloc.3 IL_0096: ldsfld int32 LocallocTest::locallocSize IL_009b: ldc.i4 1000 - IL_00a0: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00a0: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -121,7 +121,7 @@ IL_00ae: ldloc.s intArray2 IL_00b0: ldsfld int32 LocallocTest::locallocSize IL_00b5: ldc.i4 2000 - IL_00ba: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00ba: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -141,7 +141,7 @@ IL_00d2: ldloc.3 IL_00d3: ldsfld int32 LocallocTest::locallocSize IL_00d8: ldc.i4 1000 - IL_00dd: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00dd: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -155,7 +155,7 @@ IL_00ee: ldloc.s intArray2 IL_00f0: ldsfld int32 LocallocTest::locallocSize IL_00f5: ldc.i4 2000 - IL_00fa: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00fa: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -167,7 +167,7 @@ IL_0106: ldstr "local1" IL_010b: ldloc.1 IL_010c: ldc.i8 0xfedcba9876543210 - IL_0115: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0115: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_011a: brtrue.s IL_0121 @@ -179,7 +179,7 @@ IL_0121: ldstr "local2" IL_0126: ldloc.2 IL_0127: ldc.i8 0xfedcba9876543211 - IL_0130: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0130: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0135: brtrue.s IL_013c diff --git a/src/tests/JIT/jit64/localloc/eh/eh03_small.ilproj b/src/tests/JIT/jit64/localloc/eh/eh03_small.ilproj index 9fbdc495b3f37..e740b2003d47a 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh03_small.ilproj +++ b/src/tests/JIT/jit64/localloc/eh/eh03_small.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh04_dynamic.il b/src/tests/JIT/jit64/localloc/eh/eh04_dynamic.il index efa5301677af7..f77c2a784204d 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh04_dynamic.il +++ b/src/tests/JIT/jit64/localloc/eh/eh04_dynamic.il @@ -8,7 +8,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh04_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -38,16 +38,16 @@ IL_000f: add IL_0010: stloc.2 IL_0011: ldc.i4.4 - IL_0012: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0012: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0017: mul IL_0018: localloc IL_001a: stloc.3 IL_001b: ldc.i4.4 - IL_001c: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_001c: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0021: mul IL_0022: localloc IL_0024: stloc.s intArray2 - IL_0026: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0026: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_002b: stsfld int32 LocallocTest::locallocSize .try { @@ -56,13 +56,13 @@ IL_0030: ldloc.3 IL_0031: ldsfld int32 LocallocTest::locallocSize IL_0036: ldc.i4 1000 - IL_003b: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_003b: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0040: ldloc.s intArray2 IL_0042: ldsfld int32 LocallocTest::locallocSize IL_0047: ldc.i4 2000 - IL_004c: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_004c: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0051: ldstr "Test Exception" @@ -78,7 +78,7 @@ IL_0061: ldloc.3 IL_0062: ldsfld int32 LocallocTest::locallocSize IL_0067: ldc.i4 1000 - IL_006c: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006c: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -90,7 +90,7 @@ IL_007a: ldloc.s intArray2 IL_007c: ldsfld int32 LocallocTest::locallocSize IL_0081: ldc.i4 2000 - IL_0086: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0086: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -117,7 +117,7 @@ IL_00a0: ldloc.3 IL_00a1: ldsfld int32 LocallocTest::locallocSize IL_00a6: ldc.i4 1000 - IL_00ab: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00ab: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -131,7 +131,7 @@ IL_00bc: ldloc.s intArray2 IL_00be: ldsfld int32 LocallocTest::locallocSize IL_00c3: ldc.i4 2000 - IL_00c8: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00c8: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -143,7 +143,7 @@ IL_00d4: ldstr "local1" IL_00d9: ldloc.1 IL_00da: ldc.i8 0xfedcba9876543210 - IL_00e3: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00e3: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00e8: brtrue.s IL_00ef @@ -155,7 +155,7 @@ IL_00ef: ldstr "local2" IL_00f4: ldloc.2 IL_00f5: ldc.i8 0xfedcba9876543211 - IL_00fe: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00fe: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0103: brtrue.s IL_010a diff --git a/src/tests/JIT/jit64/localloc/eh/eh04_dynamic.ilproj b/src/tests/JIT/jit64/localloc/eh/eh04_dynamic.ilproj index dee4da18f7d0f..a9903c64ca894 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh04_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/eh/eh04_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh04_large.il b/src/tests/JIT/jit64/localloc/eh/eh04_large.il index c6345752e3355..d1f336d1dd860 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh04_large.il +++ b/src/tests/JIT/jit64/localloc/eh/eh04_large.il @@ -8,7 +8,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh04_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -56,13 +56,13 @@ IL_0030: ldloc.3 IL_0031: ldsfld int32 LocallocTest::locallocSize IL_0036: ldc.i4 1000 - IL_003b: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_003b: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0040: ldloc.s intArray2 IL_0042: ldsfld int32 LocallocTest::locallocSize IL_0047: ldc.i4 2000 - IL_004c: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_004c: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0051: ldstr "Test Exception" @@ -78,7 +78,7 @@ IL_0061: ldloc.3 IL_0062: ldsfld int32 LocallocTest::locallocSize IL_0067: ldc.i4 1000 - IL_006c: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006c: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -90,7 +90,7 @@ IL_007a: ldloc.s intArray2 IL_007c: ldsfld int32 LocallocTest::locallocSize IL_0081: ldc.i4 2000 - IL_0086: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0086: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -117,7 +117,7 @@ IL_00a0: ldloc.3 IL_00a1: ldsfld int32 LocallocTest::locallocSize IL_00a6: ldc.i4 1000 - IL_00ab: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00ab: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -131,7 +131,7 @@ IL_00bc: ldloc.s intArray2 IL_00be: ldsfld int32 LocallocTest::locallocSize IL_00c3: ldc.i4 2000 - IL_00c8: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00c8: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -143,7 +143,7 @@ IL_00d4: ldstr "local1" IL_00d9: ldloc.1 IL_00da: ldc.i8 0xfedcba9876543210 - IL_00e3: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00e3: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00e8: brtrue.s IL_00ef @@ -155,7 +155,7 @@ IL_00ef: ldstr "local2" IL_00f4: ldloc.2 IL_00f5: ldc.i8 0xfedcba9876543211 - IL_00fe: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00fe: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0103: brtrue.s IL_010a diff --git a/src/tests/JIT/jit64/localloc/eh/eh04_large.ilproj b/src/tests/JIT/jit64/localloc/eh/eh04_large.ilproj index 129e5a3735598..d85937541c7a9 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh04_large.ilproj +++ b/src/tests/JIT/jit64/localloc/eh/eh04_large.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh04_small.il b/src/tests/JIT/jit64/localloc/eh/eh04_small.il index 71dd321d88479..50465d262c76d 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh04_small.il +++ b/src/tests/JIT/jit64/localloc/eh/eh04_small.il @@ -8,7 +8,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh04_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -56,13 +56,13 @@ IL_0030: ldloc.3 IL_0031: ldsfld int32 LocallocTest::locallocSize IL_0036: ldc.i4 1000 - IL_003b: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_003b: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0040: ldloc.s intArray2 IL_0042: ldsfld int32 LocallocTest::locallocSize IL_0047: ldc.i4 2000 - IL_004c: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_004c: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0051: ldstr "Test Exception" @@ -78,7 +78,7 @@ IL_0061: ldloc.3 IL_0062: ldsfld int32 LocallocTest::locallocSize IL_0067: ldc.i4 1000 - IL_006c: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_006c: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -90,7 +90,7 @@ IL_007a: ldloc.s intArray2 IL_007c: ldsfld int32 LocallocTest::locallocSize IL_0081: ldc.i4 2000 - IL_0086: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0086: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -117,7 +117,7 @@ IL_00a0: ldloc.3 IL_00a1: ldsfld int32 LocallocTest::locallocSize IL_00a6: ldc.i4 1000 - IL_00ab: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00ab: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -131,7 +131,7 @@ IL_00bc: ldloc.s intArray2 IL_00be: ldsfld int32 LocallocTest::locallocSize IL_00c3: ldc.i4 2000 - IL_00c8: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00c8: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -143,7 +143,7 @@ IL_00d4: ldstr "local1" IL_00d9: ldloc.1 IL_00da: ldc.i8 0xfedcba9876543210 - IL_00e3: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00e3: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00e8: brtrue.s IL_00ef @@ -155,7 +155,7 @@ IL_00ef: ldstr "local2" IL_00f4: ldloc.2 IL_00f5: ldc.i8 0xfedcba9876543211 - IL_00fe: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00fe: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0103: brtrue.s IL_010a diff --git a/src/tests/JIT/jit64/localloc/eh/eh04_small.ilproj b/src/tests/JIT/jit64/localloc/eh/eh04_small.ilproj index 08dfeef56ab90..fcf3c327ddfc2 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh04_small.ilproj +++ b/src/tests/JIT/jit64/localloc/eh/eh04_small.ilproj @@ -10,6 +10,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh05_dynamic.csproj b/src/tests/JIT/jit64/localloc/eh/eh05_dynamic.csproj index f22da2eead178..e28d8f8654dee 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh05_dynamic.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh05_dynamic.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh05_large.csproj b/src/tests/JIT/jit64/localloc/eh/eh05_large.csproj index e228c6496be82..5ee9afad1c1f2 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh05_large.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh05_large.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/eh/eh05_small.csproj b/src/tests/JIT/jit64/localloc/eh/eh05_small.csproj index 834f3dfa77b2e..852fb8bf99467 100644 --- a/src/tests/JIT/jit64/localloc/eh/eh05_small.csproj +++ b/src/tests/JIT/jit64/localloc/eh/eh05_small.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh05_dynamic.il b/src/tests/JIT/jit64/localloc/ehverify/eh05_dynamic.il index 57c8304469504..b611d3d2c9ea2 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh05_dynamic.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh05_dynamic.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh05_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -30,7 +30,7 @@ { IL_0015: pop IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh05_dynamic.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh05_dynamic.ilproj index 63977143503ac..73876f22c2d30 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh05_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh05_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh05_large.il b/src/tests/JIT/jit64/localloc/ehverify/eh05_large.il index bbbe22e02ca1d..eb9043ec0dc29 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh05_large.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh05_large.il @@ -7,7 +7,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh05_large'{} .class private auto ansi beforefieldinit LocallocTest diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh05_small.il b/src/tests/JIT/jit64/localloc/ehverify/eh05_small.il index c6b673d44056c..79a02d630c61f 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh05_small.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh05_small.il @@ -7,7 +7,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh05_small'{} .class private auto ansi beforefieldinit LocallocTest diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh06_dynamic.il b/src/tests/JIT/jit64/localloc/ehverify/eh06_dynamic.il index 6f7b052f29b94..f63f6ce2a34fb 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh06_dynamic.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh06_dynamic.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh06_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -27,7 +27,7 @@ finally { IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh06_dynamic.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh06_dynamic.ilproj index ef17d05a0a994..84ce4573b85b5 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh06_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh06_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh06_large.il b/src/tests/JIT/jit64/localloc/ehverify/eh06_large.il index 1c1f421d6810a..04a2606025ca1 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh06_large.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh06_large.il @@ -7,7 +7,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh06_large'{} .class private auto ansi beforefieldinit LocallocTest diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh06_small.il b/src/tests/JIT/jit64/localloc/ehverify/eh06_small.il index f865a02a08a43..b6f2fbe40f2c6 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh06_small.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh06_small.il @@ -7,7 +7,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh06_small'{} .class private auto ansi beforefieldinit LocallocTest diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh07_dynamic.il b/src/tests/JIT/jit64/localloc/ehverify/eh07_dynamic.il index 81f0eda710c57..9aca078692989 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh07_dynamic.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh07_dynamic.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh07_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -28,7 +28,7 @@ { pop IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh07_dynamic.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh07_dynamic.ilproj index 6dc3bcc32d881..d404761d93687 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh07_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh07_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh07_large.il b/src/tests/JIT/jit64/localloc/ehverify/eh07_large.il index 9502fe09cfa2c..84698772b9122 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh07_large.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh07_large.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh07_large'{} .class private auto ansi beforefieldinit LocallocTest diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh07_large.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh07_large.ilproj index 83c08fabbbfa9..3339b7ce992be 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh07_large.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh07_large.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh07_small.il b/src/tests/JIT/jit64/localloc/ehverify/eh07_small.il index efc37edc7410a..9898e7869c100 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh07_small.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh07_small.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh07_small'{} .class private auto ansi beforefieldinit LocallocTest diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh07_small.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh07_small.ilproj index 13417b854d8cd..32b4c8de7e94c 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh07_small.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh07_small.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh08_dynamic.il b/src/tests/JIT/jit64/localloc/ehverify/eh08_dynamic.il index 331c9940bd85d..022f8f92312c9 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh08_dynamic.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh08_dynamic.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh08_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -27,7 +27,7 @@ fault { IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh08_dynamic.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh08_dynamic.ilproj index 5736cd7f76bd6..a1820ec6fb983 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh08_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh08_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh08_large.il b/src/tests/JIT/jit64/localloc/ehverify/eh08_large.il index c43bb2b377215..e09c646bb7fc5 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh08_large.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh08_large.il @@ -7,7 +7,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh08_large'{} .class private auto ansi beforefieldinit LocallocTest diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh08_small.il b/src/tests/JIT/jit64/localloc/ehverify/eh08_small.il index 1a2f4a07b7946..6456118c32978 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh08_small.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh08_small.il @@ -7,7 +7,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh08_small'{} .class private auto ansi beforefieldinit LocallocTest diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh09_dynamic.csproj b/src/tests/JIT/jit64/localloc/ehverify/eh09_dynamic.csproj index 4af966a1e3948..680468a2ce6b2 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh09_dynamic.csproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh09_dynamic.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh09_large.csproj b/src/tests/JIT/jit64/localloc/ehverify/eh09_large.csproj index 4af966a1e3948..680468a2ce6b2 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh09_large.csproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh09_large.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh09_small.csproj b/src/tests/JIT/jit64/localloc/ehverify/eh09_small.csproj index 4af966a1e3948..680468a2ce6b2 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh09_small.csproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh09_small.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh11_dynamic.il b/src/tests/JIT/jit64/localloc/ehverify/eh11_dynamic.il index 7cf71198d07f5..a462b6d162785 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh11_dynamic.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh11_dynamic.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh11_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -39,16 +39,16 @@ IL_000f: add IL_0010: stloc.2 IL_0011: ldc.i4.4 - IL_0012: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0012: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0017: mul IL_0018: localloc IL_001a: stloc.3 IL_001b: ldc.i4.4 - IL_001c: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_001c: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0021: mul IL_0022: localloc IL_0024: stloc.s intArray2 - IL_0026: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0026: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_002b: stsfld int32 LocallocTest::locallocSize .try { @@ -66,13 +66,13 @@ IL_003b: ldloc.3 IL_003c: ldsfld int32 LocallocTest::locallocSize IL_0041: ldc.i4 1000 - IL_0046: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0046: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_004b: ldloc.s intArray2 IL_004d: ldsfld int32 LocallocTest::locallocSize IL_0052: ldc.i4 2000 - IL_0057: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0057: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_005c: ldstr "Test Exception" @@ -88,7 +88,7 @@ IL_006c: ldloc.3 IL_006d: ldsfld int32 LocallocTest::locallocSize IL_0072: ldc.i4 1000 - IL_0077: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0077: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -100,7 +100,7 @@ IL_0085: ldloc.s intArray2 IL_0087: ldsfld int32 LocallocTest::locallocSize IL_008c: ldc.i4 2000 - IL_0091: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0091: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -128,7 +128,7 @@ IL_00ab: ldloc.3 IL_00ac: ldsfld int32 LocallocTest::locallocSize IL_00b1: ldc.i4 1000 - IL_00b6: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b6: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -142,7 +142,7 @@ IL_00c7: ldloc.s intArray2 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 2000 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -155,7 +155,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.1 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -167,7 +167,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.2 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh11_dynamic.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh11_dynamic.ilproj index 8bf4ea68e4378..fa4ebb678c022 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh11_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh11_dynamic.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh11_large.il b/src/tests/JIT/jit64/localloc/ehverify/eh11_large.il index 89d8af7e9ff6b..e0109628129a1 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh11_large.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh11_large.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh11_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -66,13 +66,13 @@ IL_003b: ldloc.3 IL_003c: ldsfld int32 LocallocTest::locallocSize IL_0041: ldc.i4 1000 - IL_0046: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0046: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_004b: ldloc.s intArray2 IL_004d: ldsfld int32 LocallocTest::locallocSize IL_0052: ldc.i4 2000 - IL_0057: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0057: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_005c: ldstr "Test Exception" @@ -88,7 +88,7 @@ IL_006c: ldloc.3 IL_006d: ldsfld int32 LocallocTest::locallocSize IL_0072: ldc.i4 1000 - IL_0077: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0077: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -100,7 +100,7 @@ IL_0085: ldloc.s intArray2 IL_0087: ldsfld int32 LocallocTest::locallocSize IL_008c: ldc.i4 2000 - IL_0091: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0091: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -128,7 +128,7 @@ IL_00ab: ldloc.3 IL_00ac: ldsfld int32 LocallocTest::locallocSize IL_00b1: ldc.i4 1000 - IL_00b6: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b6: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -142,7 +142,7 @@ IL_00c7: ldloc.s intArray2 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 2000 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -155,7 +155,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.1 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -167,7 +167,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.2 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh11_large.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh11_large.ilproj index 77247ceb83a71..69f589f6d10c2 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh11_large.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh11_large.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh11_small.il b/src/tests/JIT/jit64/localloc/ehverify/eh11_small.il index 4de02c60ddb39..887c03dbbc327 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh11_small.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh11_small.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh11_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -62,13 +62,13 @@ IL_003b: ldloc.3 IL_003c: ldsfld int32 LocallocTest::locallocSize IL_0041: ldc.i4 1000 - IL_0046: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0046: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_004b: ldloc.s intArray2 IL_004d: ldsfld int32 LocallocTest::locallocSize IL_0052: ldc.i4 2000 - IL_0057: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0057: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_005c: ldstr "Test Exception" @@ -84,7 +84,7 @@ IL_006c: ldloc.3 IL_006d: ldsfld int32 LocallocTest::locallocSize IL_0072: ldc.i4 1000 - IL_0077: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0077: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -96,7 +96,7 @@ IL_0085: ldloc.s intArray2 IL_0087: ldsfld int32 LocallocTest::locallocSize IL_008c: ldc.i4 2000 - IL_0091: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0091: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -124,7 +124,7 @@ IL_00ab: ldloc.3 IL_00ac: ldsfld int32 LocallocTest::locallocSize IL_00b1: ldc.i4 1000 - IL_00b6: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b6: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -138,7 +138,7 @@ IL_00c7: ldloc.s intArray2 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 2000 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -151,7 +151,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.1 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -163,7 +163,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.2 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh11_small.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh11_small.ilproj index 1f91686edc030..b158805738488 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh11_small.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh11_small.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh12_dynamic.il b/src/tests/JIT/jit64/localloc/ehverify/eh12_dynamic.il index 6fe573a8f340f..d551f42ae3078 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh12_dynamic.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh12_dynamic.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh12_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -36,16 +36,16 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 IL_0019: ldc.i4.4 - IL_001a: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_001a: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_001f: mul IL_0020: localloc IL_0022: stloc.3 - IL_0023: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0023: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0028: stsfld int32 LocallocTest::locallocSize .try { @@ -69,13 +69,13 @@ IL_0039: ldloc.2 IL_003a: ldsfld int32 LocallocTest::locallocSize IL_003f: ldc.i4 1000 - IL_0044: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0044: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0049: ldloc.3 IL_004a: ldsfld int32 LocallocTest::locallocSize IL_004f: ldc.i4 2000 - IL_0054: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0054: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0059: ldstr "Test Exception" @@ -92,7 +92,7 @@ IL_006a: ldloc.2 IL_006b: ldsfld int32 LocallocTest::locallocSize IL_0070: ldc.i4 1000 - IL_0075: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0075: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -106,7 +106,7 @@ IL_0089: ldloc.3 IL_008a: ldsfld int32 LocallocTest::locallocSize IL_008f: ldc.i4 2000 - IL_0094: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0094: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -131,7 +131,7 @@ IL_00ac: ldloc.2 IL_00ad: ldsfld int32 LocallocTest::locallocSize IL_00b2: ldc.i4 0x3e8 - IL_00b7: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -145,7 +145,7 @@ IL_00c8: ldloc.3 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 0x7d0 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -157,7 +157,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.0 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -169,7 +169,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.1 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh12_dynamic.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh12_dynamic.ilproj index 5edb540707439..d7f291e60fb65 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh12_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh12_dynamic.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh12_large.il b/src/tests/JIT/jit64/localloc/ehverify/eh12_large.il index 4490eab60c013..2f9cae4e5448e 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh12_large.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh12_large.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh12_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -69,13 +69,13 @@ IL_0039: ldloc.2 IL_003a: ldsfld int32 LocallocTest::locallocSize IL_003f: ldc.i4 1000 - IL_0044: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0044: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0049: ldloc.3 IL_004a: ldsfld int32 LocallocTest::locallocSize IL_004f: ldc.i4 2000 - IL_0054: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0054: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0059: ldstr "Test Exception" @@ -92,7 +92,7 @@ IL_006a: ldloc.2 IL_006b: ldsfld int32 LocallocTest::locallocSize IL_0070: ldc.i4 1000 - IL_0075: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0075: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -106,7 +106,7 @@ IL_0089: ldloc.3 IL_008a: ldsfld int32 LocallocTest::locallocSize IL_008f: ldc.i4 2000 - IL_0094: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0094: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -131,7 +131,7 @@ IL_00ac: ldloc.2 IL_00ad: ldsfld int32 LocallocTest::locallocSize IL_00b2: ldc.i4 0x3e8 - IL_00b7: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -145,7 +145,7 @@ IL_00c8: ldloc.3 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 0x7d0 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -157,7 +157,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.0 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -169,7 +169,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.1 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh12_large.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh12_large.ilproj index b80f92c1f188b..08286b6e6bc4f 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh12_large.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh12_large.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh12_small.il b/src/tests/JIT/jit64/localloc/ehverify/eh12_small.il index 5df0c1638f078..643d51c5efbf4 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh12_small.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh12_small.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh12_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -65,13 +65,13 @@ IL_0039: ldloc.2 IL_003a: ldsfld int32 LocallocTest::locallocSize IL_003f: ldc.i4 1000 - IL_0044: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0044: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0049: ldloc.3 IL_004a: ldsfld int32 LocallocTest::locallocSize IL_004f: ldc.i4 2000 - IL_0054: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0054: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0059: ldstr "Test Exception" @@ -88,7 +88,7 @@ IL_006a: ldloc.2 IL_006b: ldsfld int32 LocallocTest::locallocSize IL_0070: ldc.i4 1000 - IL_0075: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0075: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -102,7 +102,7 @@ IL_0089: ldloc.3 IL_008a: ldsfld int32 LocallocTest::locallocSize IL_008f: ldc.i4 2000 - IL_0094: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0094: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -127,7 +127,7 @@ IL_00ac: ldloc.2 IL_00ad: ldsfld int32 LocallocTest::locallocSize IL_00b2: ldc.i4 0x3e8 - IL_00b7: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -141,7 +141,7 @@ IL_00c8: ldloc.3 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 0x7d0 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -153,7 +153,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.0 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -165,7 +165,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.1 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh12_small.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh12_small.ilproj index b15b1d0a81a1e..2831b11aa17c2 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh12_small.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh12_small.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh13_dynamic.il b/src/tests/JIT/jit64/localloc/ehverify/eh13_dynamic.il index 9a83ff4d7ea01..2b50bd97d6142 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh13_dynamic.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh13_dynamic.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh13_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -36,16 +36,16 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 IL_0019: ldc.i4.4 - IL_001a: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_001a: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_001f: mul IL_0020: localloc IL_0022: stloc.3 - IL_0023: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0023: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0028: stsfld int32 LocallocTest::locallocSize .try { @@ -69,13 +69,13 @@ IL_0039: ldloc.2 IL_003a: ldsfld int32 LocallocTest::locallocSize IL_003f: ldc.i4 1000 - IL_0044: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0044: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0049: ldloc.3 IL_004a: ldsfld int32 LocallocTest::locallocSize IL_004f: ldc.i4 2000 - IL_0054: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0054: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0059: ldstr "Test Exception" @@ -97,7 +97,7 @@ IL_006a: ldloc.2 IL_006b: ldsfld int32 LocallocTest::locallocSize IL_0070: ldc.i4 0x3e8 - IL_0075: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0075: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -111,7 +111,7 @@ IL_0089: ldloc.3 IL_008a: ldsfld int32 LocallocTest::locallocSize IL_008f: ldc.i4 0x7d0 - IL_0094: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0094: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -131,7 +131,7 @@ IL_00ac: ldloc.2 IL_00ad: ldsfld int32 LocallocTest::locallocSize IL_00b2: ldc.i4 0x3e8 - IL_00b7: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -145,7 +145,7 @@ IL_00c8: ldloc.3 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 2000 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -157,7 +157,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.0 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -169,7 +169,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.1 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh13_dynamic.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh13_dynamic.ilproj index 7da52df043f03..1e1ecb3344c8c 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh13_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh13_dynamic.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh13_large.il b/src/tests/JIT/jit64/localloc/ehverify/eh13_large.il index 357e0c562c0e5..860fdcccf6934 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh13_large.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh13_large.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh13_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -69,13 +69,13 @@ IL_0039: ldloc.2 IL_003a: ldsfld int32 LocallocTest::locallocSize IL_003f: ldc.i4 1000 - IL_0044: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0044: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0049: ldloc.3 IL_004a: ldsfld int32 LocallocTest::locallocSize IL_004f: ldc.i4 2000 - IL_0054: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0054: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0059: ldstr "Test Exception" @@ -97,7 +97,7 @@ IL_006a: ldloc.2 IL_006b: ldsfld int32 LocallocTest::locallocSize IL_0070: ldc.i4 0x3e8 - IL_0075: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0075: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -111,7 +111,7 @@ IL_0089: ldloc.3 IL_008a: ldsfld int32 LocallocTest::locallocSize IL_008f: ldc.i4 0x7d0 - IL_0094: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0094: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -131,7 +131,7 @@ IL_00ac: ldloc.2 IL_00ad: ldsfld int32 LocallocTest::locallocSize IL_00b2: ldc.i4 0x3e8 - IL_00b7: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -145,7 +145,7 @@ IL_00c8: ldloc.3 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 2000 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -157,7 +157,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.0 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -169,7 +169,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.1 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh13_large.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh13_large.ilproj index 15f00f40ecf63..0c538c7d32bd0 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh13_large.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh13_large.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh13_small.il b/src/tests/JIT/jit64/localloc/ehverify/eh13_small.il index 7b815ce0c1fbc..7d0637f9c4cf5 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh13_small.il +++ b/src/tests/JIT/jit64/localloc/ehverify/eh13_small.il @@ -9,7 +9,7 @@ .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'eh13_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -65,13 +65,13 @@ IL_0039: ldloc.2 IL_003a: ldsfld int32 LocallocTest::locallocSize IL_003f: ldc.i4 1000 - IL_0044: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0044: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0049: ldloc.3 IL_004a: ldsfld int32 LocallocTest::locallocSize IL_004f: ldc.i4 2000 - IL_0054: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0054: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0059: ldstr "Test Exception" @@ -93,7 +93,7 @@ IL_006a: ldloc.2 IL_006b: ldsfld int32 LocallocTest::locallocSize IL_0070: ldc.i4 0x3e8 - IL_0075: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0075: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -107,7 +107,7 @@ IL_0089: ldloc.3 IL_008a: ldsfld int32 LocallocTest::locallocSize IL_008f: ldc.i4 0x7d0 - IL_0094: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0094: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -127,7 +127,7 @@ IL_00ac: ldloc.2 IL_00ad: ldsfld int32 LocallocTest::locallocSize IL_00b2: ldc.i4 0x3e8 - IL_00b7: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00b7: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -141,7 +141,7 @@ IL_00c8: ldloc.3 IL_00c9: ldsfld int32 LocallocTest::locallocSize IL_00ce: ldc.i4 2000 - IL_00d3: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_00d3: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -153,7 +153,7 @@ IL_00df: ldstr "local1" IL_00e4: ldloc.0 IL_00e5: ldc.i8 0xfedcba9876543210 - IL_00ee: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_00ee: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_00f3: brtrue.s IL_00fa @@ -165,7 +165,7 @@ IL_00fa: ldstr "local2" IL_00ff: ldloc.1 IL_0100: ldc.i8 0xfedcba9876543211 - IL_0109: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0109: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_010e: brtrue.s IL_0115 diff --git a/src/tests/JIT/jit64/localloc/ehverify/eh13_small.ilproj b/src/tests/JIT/jit64/localloc/ehverify/eh13_small.ilproj index 5f94131c44d92..dc65e4a3ef272 100644 --- a/src/tests/JIT/jit64/localloc/ehverify/eh13_small.ilproj +++ b/src/tests/JIT/jit64/localloc/ehverify/eh13_small.ilproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind01_dynamic.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind01_dynamic.csproj index 1b6c2bd504266..2120c17bb1447 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind01_dynamic.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind01_dynamic.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind01_large.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind01_large.csproj index a9413720a5631..e79791a3a3b2b 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind01_large.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind01_large.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind01_small.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind01_small.csproj index c44c9607a0a6f..ac0ac13196337 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind01_small.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind01_small.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind02_dynamic.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind02_dynamic.csproj index c5f482fd6e6a6..746f6a8bbb139 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind02_dynamic.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind02_dynamic.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind02_large.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind02_large.csproj index 57bfbf4e55f32..96e92c2266214 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind02_large.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind02_large.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind02_small.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind02_small.csproj index 9d53cd1ca260e..628e272b5e650 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind02_small.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind02_small.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind03_dynamic.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind03_dynamic.csproj index 72b9c010980fd..1a4812096bb25 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind03_dynamic.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind03_dynamic.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind03_large.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind03_large.csproj index 192410eac7fdb..1af405b23d6ea 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind03_large.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind03_large.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind03_small.csproj b/src/tests/JIT/jit64/localloc/unwind/unwind03_small.csproj index a8da8d06a22d5..cbc07a44baa80 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind03_small.csproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind03_small.csproj @@ -12,6 +12,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind04_dynamic.il b/src/tests/JIT/jit64/localloc/unwind/unwind04_dynamic.il index f2c313f958cba..4b32e8ae8b4cd 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind04_dynamic.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind04_dynamic.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind04_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -36,18 +36,18 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 - IL_0019: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0019: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_001e: stsfld int32 LocallocTest::locallocSize .try { IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -72,7 +72,7 @@ IL_004f: ldloc.2 IL_0050: ldsfld int32 LocallocTest::locallocSize IL_0055: ldc.i4 1000 - IL_005a: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_005a: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -84,7 +84,7 @@ IL_0065: ldstr "local1" IL_006a: ldloc.0 IL_006b: ldc.i8 0xfedcba9876543210 - IL_0074: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0079: brtrue.s IL_007f @@ -96,7 +96,7 @@ IL_007f: ldstr "local2" IL_0084: ldloc.1 IL_0085: ldc.i8 0xfedcba9876543211 - IL_008e: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_008e: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0093: brtrue.s IL_0099 @@ -120,14 +120,14 @@ .locals (int32* intArray2, class LocallocTest testObj) IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -166,7 +166,7 @@ IL_0048: ldloc.0 IL_0049: ldsfld int32 LocallocTest::locallocSize IL_004e: ldc.i4 2000 - IL_0053: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0053: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -194,14 +194,14 @@ .maxstack 4 .locals (int32* intArray3) IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try{ @@ -226,7 +226,7 @@ IL_004c: ldloc.0 IL_004d: ldsfld int32 LocallocTest::locallocSize IL_0052: ldc.i4 3000 - IL_0057: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0057: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind04_dynamic.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind04_dynamic.ilproj index 4162e1394aec6..390dc2d478f56 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind04_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind04_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind04_large.il b/src/tests/JIT/jit64/localloc/unwind/unwind04_large.il index 5c0d52e93b3e3..8c69ff783c77a 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind04_large.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind04_large.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind04_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -47,7 +47,7 @@ IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -72,7 +72,7 @@ IL_004f: ldloc.2 IL_0050: ldsfld int32 LocallocTest::locallocSize IL_0055: ldc.i4 1000 - IL_005a: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_005a: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -84,7 +84,7 @@ IL_0065: ldstr "local1" IL_006a: ldloc.0 IL_006b: ldc.i8 0xfedcba9876543210 - IL_0074: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0079: brtrue.s IL_007f @@ -96,7 +96,7 @@ IL_007f: ldstr "local2" IL_0084: ldloc.1 IL_0085: ldc.i8 0xfedcba9876543211 - IL_008e: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_008e: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0093: brtrue.s IL_0099 @@ -127,7 +127,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -166,7 +166,7 @@ IL_0048: ldloc.0 IL_0049: ldsfld int32 LocallocTest::locallocSize IL_004e: ldc.i4 2000 - IL_0053: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0053: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -201,7 +201,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try{ @@ -226,7 +226,7 @@ IL_004c: ldloc.0 IL_004d: ldsfld int32 LocallocTest::locallocSize IL_0052: ldc.i4 3000 - IL_0057: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0057: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind04_large.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind04_large.ilproj index 0dc644cde0dbe..648d208e761b9 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind04_large.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind04_large.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind04_small.il b/src/tests/JIT/jit64/localloc/unwind/unwind04_small.il index 2152e53c57ef9..0aa5fbe0bdc4a 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind04_small.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind04_small.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind04_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -45,7 +45,7 @@ IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -70,7 +70,7 @@ IL_004f: ldloc.2 IL_0050: ldsfld int32 LocallocTest::locallocSize IL_0055: ldc.i4 1000 - IL_005a: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_005a: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -82,7 +82,7 @@ IL_0065: ldstr "local1" IL_006a: ldloc.0 IL_006b: ldc.i8 0xfedcba9876543210 - IL_0074: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0074: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0079: brtrue.s IL_007f @@ -94,7 +94,7 @@ IL_007f: ldstr "local2" IL_0084: ldloc.1 IL_0085: ldc.i8 0xfedcba9876543211 - IL_008e: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_008e: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0093: brtrue.s IL_0099 @@ -123,7 +123,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -162,7 +162,7 @@ IL_0048: ldloc.0 IL_0049: ldsfld int32 LocallocTest::locallocSize IL_004e: ldc.i4 2000 - IL_0053: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0053: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -195,7 +195,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try{ @@ -220,7 +220,7 @@ IL_004c: ldloc.0 IL_004d: ldsfld int32 LocallocTest::locallocSize IL_0052: ldc.i4 3000 - IL_0057: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0057: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind04_small.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind04_small.ilproj index ec3e015c4853d..d47226cac683b 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind04_small.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind04_small.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind05_dynamic.il b/src/tests/JIT/jit64/localloc/unwind/unwind05_dynamic.il index a21de715bdb88..8fe4f6a963423 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind05_dynamic.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind05_dynamic.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind05_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -35,18 +35,18 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 - IL_0019: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0019: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_001e: stsfld int32 LocallocTest::locallocSize .try { IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -65,7 +65,7 @@ IL_0044: ldloc.2 IL_0045: ldsfld int32 LocallocTest::locallocSize IL_004a: ldc.i4 1000 - IL_004f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -77,7 +77,7 @@ IL_005a: ldstr "local1" IL_005f: ldloc.0 IL_0060: ldc.i8 0xfedcba9876543210 - IL_0069: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0069: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_006e: brtrue.s IL_0074 @@ -89,7 +89,7 @@ IL_0074: ldstr "local2" IL_0079: ldloc.1 IL_007a: ldc.i8 0xfedcba9876543211 - IL_0083: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0083: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0088: brtrue.s IL_008e @@ -113,14 +113,14 @@ .locals (int32* intArray2, class LocallocTest testObj) IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -158,7 +158,7 @@ IL_0042: ldloc.0 IL_0043: ldsfld int32 LocallocTest::locallocSize IL_0048: ldc.i4 2000 - IL_004d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -192,14 +192,14 @@ .maxstack 4 .locals (int32* intArray3) IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -225,7 +225,7 @@ IL_0047: ldloc.0 IL_0048: ldsfld int32 LocallocTest::locallocSize IL_004d: ldc.i4 3000 - IL_0052: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind05_dynamic.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind05_dynamic.ilproj index c905cff5f4ad0..6a1c2bac53899 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind05_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind05_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind05_large.il b/src/tests/JIT/jit64/localloc/unwind/unwind05_large.il index 743195ad4a8b3..c384b1ad50d40 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind05_large.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind05_large.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind05_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -46,7 +46,7 @@ IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -65,7 +65,7 @@ IL_0044: ldloc.2 IL_0045: ldsfld int32 LocallocTest::locallocSize IL_004a: ldc.i4 1000 - IL_004f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -77,7 +77,7 @@ IL_005a: ldstr "local1" IL_005f: ldloc.0 IL_0060: ldc.i8 0xfedcba9876543210 - IL_0069: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0069: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_006e: brtrue.s IL_0074 @@ -89,7 +89,7 @@ IL_0074: ldstr "local2" IL_0079: ldloc.1 IL_007a: ldc.i8 0xfedcba9876543211 - IL_0083: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0083: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0088: brtrue.s IL_008e @@ -120,7 +120,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -158,7 +158,7 @@ IL_0042: ldloc.0 IL_0043: ldsfld int32 LocallocTest::locallocSize IL_0048: ldc.i4 2000 - IL_004d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -199,7 +199,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -225,7 +225,7 @@ IL_0047: ldloc.0 IL_0048: ldsfld int32 LocallocTest::locallocSize IL_004d: ldc.i4 3000 - IL_0052: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind05_large.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind05_large.ilproj index ada6e192e122a..cabea474dd772 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind05_large.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind05_large.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind05_small.il b/src/tests/JIT/jit64/localloc/unwind/unwind05_small.il index 5f7f665f9e8b0..06f36159d2b09 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind05_small.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind05_small.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind05_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -44,7 +44,7 @@ IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -63,7 +63,7 @@ IL_0044: ldloc.2 IL_0045: ldsfld int32 LocallocTest::locallocSize IL_004a: ldc.i4 1000 - IL_004f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -75,7 +75,7 @@ IL_005a: ldstr "local1" IL_005f: ldloc.0 IL_0060: ldc.i8 0xfedcba9876543210 - IL_0069: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0069: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_006e: brtrue.s IL_0074 @@ -87,7 +87,7 @@ IL_0074: ldstr "local2" IL_0079: ldloc.1 IL_007a: ldc.i8 0xfedcba9876543211 - IL_0083: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0083: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0088: brtrue.s IL_008e @@ -116,7 +116,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -154,7 +154,7 @@ IL_0042: ldloc.0 IL_0043: ldsfld int32 LocallocTest::locallocSize IL_0048: ldc.i4 2000 - IL_004d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -193,7 +193,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -219,7 +219,7 @@ IL_0047: ldloc.0 IL_0048: ldsfld int32 LocallocTest::locallocSize IL_004d: ldc.i4 3000 - IL_0052: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind05_small.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind05_small.ilproj index a8888fb827c78..9799ef9c88515 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind05_small.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind05_small.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind06_dynamic.il b/src/tests/JIT/jit64/localloc/unwind/unwind06_dynamic.il index 9f71cfb6c0ce8..cda4b9860ba68 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind06_dynamic.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind06_dynamic.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind06_dynamic'{} .class private auto ansi beforefieldinit LocallocTest @@ -35,18 +35,18 @@ IL_000d: add IL_000e: stloc.1 IL_000f: ldc.i4.4 - IL_0010: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0010: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0015: mul IL_0016: localloc IL_0018: stloc.2 - IL_0019: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0019: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_001e: stsfld int32 LocallocTest::locallocSize .try { IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -65,7 +65,7 @@ IL_0044: ldloc.2 IL_0045: ldsfld int32 LocallocTest::locallocSize IL_004a: ldc.i4 1000 - IL_004f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -77,7 +77,7 @@ IL_005a: ldstr "local1" IL_005f: ldloc.0 IL_0060: ldc.i8 0xfedcba9876543210 - IL_0069: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0069: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_006e: brtrue.s IL_0074 @@ -89,7 +89,7 @@ IL_0074: ldstr "local2" IL_0079: ldloc.1 IL_007a: ldc.i8 0xfedcba9876543211 - IL_0083: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0083: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0088: brtrue.s IL_008e @@ -113,14 +113,14 @@ .locals (int32* intArray2, class LocallocTest testObj) IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -163,7 +163,7 @@ IL_0042: ldloc.0 IL_0043: ldsfld int32 LocallocTest::locallocSize IL_0048: ldc.i4 2000 - IL_004d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -192,14 +192,14 @@ .maxstack 4 .locals (int32* intArray3) IL_0000: ldc.i4.4 - IL_0001: ldsfld int32 [common]LocallocTesting.Global::stackAllocSize + IL_0001: ldsfld int32 [localloc_common]LocallocTesting.Global::stackAllocSize IL_0006: mul IL_0007: localloc IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -230,7 +230,7 @@ IL_0047: ldloc.0 IL_0048: ldsfld int32 LocallocTest::locallocSize IL_004d: ldc.i4 3000 - IL_0052: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind06_dynamic.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind06_dynamic.ilproj index 3074a76fafe0c..8eaac5321feb4 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind06_dynamic.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind06_dynamic.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind06_large.il b/src/tests/JIT/jit64/localloc/unwind/unwind06_large.il index d7120bf7a6e1f..9e7fa07827fce 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind06_large.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind06_large.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind06_large'{} .class private auto ansi beforefieldinit LocallocTest @@ -46,7 +46,7 @@ IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -65,7 +65,7 @@ IL_0044: ldloc.2 IL_0045: ldsfld int32 LocallocTest::locallocSize IL_004a: ldc.i4 1000 - IL_004f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -77,7 +77,7 @@ IL_005a: ldstr "local1" IL_005f: ldloc.0 IL_0060: ldc.i8 0xfedcba9876543210 - IL_0069: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0069: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_006e: brtrue.s IL_0074 @@ -89,7 +89,7 @@ IL_0074: ldstr "local2" IL_0079: ldloc.1 IL_007a: ldc.i8 0xfedcba9876543211 - IL_0083: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0083: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0088: brtrue.s IL_008e @@ -120,7 +120,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -163,7 +163,7 @@ IL_0042: ldloc.0 IL_0043: ldsfld int32 LocallocTest::locallocSize IL_0048: ldc.i4 2000 - IL_004d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -199,7 +199,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -230,7 +230,7 @@ IL_0047: ldloc.0 IL_0048: ldsfld int32 LocallocTest::locallocSize IL_004d: ldc.i4 3000 - IL_0052: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind06_large.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind06_large.ilproj index a94086f943e5f..163c62780fe88 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind06_large.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind06_large.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind06_small.il b/src/tests/JIT/jit64/localloc/unwind/unwind06_small.il index 6b4dc083d4f80..7e45024c3270e 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind06_small.il +++ b/src/tests/JIT/jit64/localloc/unwind/unwind06_small.il @@ -9,7 +9,7 @@ } .assembly extern xunit.core {} .assembly extern mscorlib{} -.assembly extern common{} +.assembly extern localloc_common{} .assembly 'unwind06_small'{} .class private auto ansi beforefieldinit LocallocTest @@ -44,7 +44,7 @@ IL_0023: ldloc.2 IL_0024: ldsfld int32 LocallocTest::locallocSize IL_0029: ldc.i4 1000 - IL_002e: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_002e: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) IL_0033: call void LocallocTest::unwindTest1() @@ -63,7 +63,7 @@ IL_0044: ldloc.2 IL_0045: ldsfld int32 LocallocTest::locallocSize IL_004a: ldc.i4 1000 - IL_004f: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004f: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -75,7 +75,7 @@ IL_005a: ldstr "local1" IL_005f: ldloc.0 IL_0060: ldc.i8 0xfedcba9876543210 - IL_0069: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0069: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_006e: brtrue.s IL_0074 @@ -87,7 +87,7 @@ IL_0074: ldstr "local2" IL_0079: ldloc.1 IL_007a: ldc.i8 0xfedcba9876543211 - IL_0083: call bool [common]LocallocTesting.Global::verifyLocal(string, + IL_0083: call bool [localloc_common]LocallocTesting.Global::verifyLocal(string, unsigned int64, unsigned int64) IL_0088: brtrue.s IL_008e @@ -116,7 +116,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 2000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -159,7 +159,7 @@ IL_0042: ldloc.0 IL_0043: ldsfld int32 LocallocTest::locallocSize IL_0048: ldc.i4 2000 - IL_004d: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_004d: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) @@ -193,7 +193,7 @@ IL_000a: ldloc.0 IL_000b: ldsfld int32 LocallocTest::locallocSize IL_0010: ldc.i4 3000 - IL_0015: call void [common]LocallocTesting.Global::initializeStack(int32*, + IL_0015: call void [localloc_common]LocallocTesting.Global::initializeStack(int32*, int32, int32) .try @@ -224,7 +224,7 @@ IL_0047: ldloc.0 IL_0048: ldsfld int32 LocallocTest::locallocSize IL_004d: ldc.i4 3000 - IL_0052: call bool [common]LocallocTesting.Global::verifyStack(string, + IL_0052: call bool [localloc_common]LocallocTesting.Global::verifyStack(string, int32*, int32, int32) diff --git a/src/tests/JIT/jit64/localloc/unwind/unwind06_small.ilproj b/src/tests/JIT/jit64/localloc/unwind/unwind06_small.ilproj index 960e103ba42c4..b83f3326454c1 100644 --- a/src/tests/JIT/jit64/localloc/unwind/unwind06_small.ilproj +++ b/src/tests/JIT/jit64/localloc/unwind/unwind06_small.ilproj @@ -11,6 +11,6 @@ - + diff --git a/src/tests/JIT/opt/IsKnownConstant/StringEquals.cs b/src/tests/JIT/opt/IsKnownConstant/StringEquals.cs new file mode 100644 index 0000000000000..4a109ae5d6548 --- /dev/null +++ b/src/tests/JIT/opt/IsKnownConstant/StringEquals.cs @@ -0,0 +1,99 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.CompilerServices; + +public class Program +{ + public static int Main() + { + AssertEquals(true, TestEquals1("")); + AssertEquals(false, TestEquals1(null)); + AssertEquals(false, TestEquals1("1")); + + AssertEquals(true, TestEquals2("")); + AssertEquals(false, TestEquals2(null)); + AssertEquals(false, TestEquals2("1")); + + AssertEquals(true, TestEquals3("")); + AssertEquals(false, TestEquals3(null)); + AssertEquals(false, TestEquals3("1")); + + AssertEquals(true, TestEquals4("")); + AssertEquals(false, TestEquals4(null)); + AssertEquals(false, TestEquals4("1")); + + AssertEquals(true, TestEquals5("")); + AssertEquals(false, TestEquals5(null)); + AssertEquals(false, TestEquals5("1")); + + AssertEquals(false, TestEquals6("")); + AssertEquals(true, TestEquals6(null)); + AssertEquals(false, TestEquals6("1")); + + AssertEquals(false, TestEquals7()); + AssertEquals(false, TestEquals8()); + + AssertEquals(true, TestEquals5("")); + AssertEquals(false, TestEquals5(null)); + AssertEquals(false, TestEquals5("1")); + + AssertEquals(true, TestStartWith("c")); + AssertEquals(false, TestStartWith("C")); + AssertThrowsNRE(() => TestStartWith(null)); + + return 100; + } + + private static void AssertEquals(bool expected, bool actual, [CallerLineNumber]int l = 0) + { + if (expected != actual) + throw new InvalidOperationException(); + } + + private static void AssertThrowsNRE(Action a) + { + try + { + a(); + } + catch (NullReferenceException) + { + return; + } + throw new InvalidOperationException(); + } + + private static string NullStr() => null; + private static string EmptyStr() => ""; + private static string NonEmptyStr() => "1"; + + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestEquals1(string str) => str == ""; + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestEquals2(string str) => str == string.Empty; + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestEquals3(string str) => "" == str; + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestEquals4(string str) => string.Empty == str; + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestEquals5(string str) => string.Empty == str; + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestEquals6(string str) => string.Equals(NullStr(), str); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestEquals7() => string.Equals(NullStr(), EmptyStr()); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestEquals8() => string.Equals(NullStr(), NonEmptyStr()); + + [MethodImpl(MethodImplOptions.NoInlining)] + private static bool TestStartWith(string str) => str.StartsWith('c'); +} diff --git a/src/tests/JIT/Methodical/NaN/arithm64_cs_r.csproj b/src/tests/JIT/opt/IsKnownConstant/StringEquals.csproj similarity index 51% rename from src/tests/JIT/Methodical/NaN/arithm64_cs_r.csproj rename to src/tests/JIT/opt/IsKnownConstant/StringEquals.csproj index 0a1a264667756..6946bed81bfd5 100644 --- a/src/tests/JIT/Methodical/NaN/arithm64_cs_r.csproj +++ b/src/tests/JIT/opt/IsKnownConstant/StringEquals.csproj @@ -1,12 +1,9 @@ Exe - - - None - False + True - + diff --git a/src/tests/Loader/classloader/explicitlayout/Regressions/empty/explicitStruct_empty.cs b/src/tests/Loader/classloader/explicitlayout/Regressions/empty/explicitStruct_empty.cs new file mode 100644 index 0000000000000..1de3b4442c7fb --- /dev/null +++ b/src/tests/Loader/classloader/explicitlayout/Regressions/empty/explicitStruct_empty.cs @@ -0,0 +1,60 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Xunit; + +[StructLayout(LayoutKind.Explicit)] +public struct S +{ +} + +[StructLayout(LayoutKind.Explicit)] +public struct S2 +{ +} + +[StructLayout(LayoutKind.Explicit)] +public class C +{ +} + +[StructLayout(LayoutKind.Explicit)] +public class C2 +{ +} + +public class Test_explicitStruct_empty +{ + // Mark as no-inlining so any test failures will show the right stack trace even after + // we consolidate test assemblies. + [Fact] + [MethodImpl(MethodImplOptions.NoInlining)] + public static void EmptyExplicitStructCanBeLoadedAndCreated() + { + S s = new S(); + } + + [Fact] + [MethodImpl(MethodImplOptions.NoInlining)] + public static void EmptyExplicitStructCanBeLoadedAndCreatedThroughReflection() + { + object s = Activator.CreateInstance(Type.GetType("S2")); + } + + [Fact] + [MethodImpl(MethodImplOptions.NoInlining)] + public static void EmptyExplicitClassCanBeLoadedAndCreated() + { + C c = new C(); + } + + [Fact] + [MethodImpl(MethodImplOptions.NoInlining)] + public static void EmptyExplicitClassCanBeLoadedAndCreatedThroughReflection() + { + object c = Activator.CreateInstance(Type.GetType("C2")); + } +} diff --git a/src/tests/Loader/classloader/explicitlayout/Regressions/empty/explicitStruct_empty.csproj b/src/tests/Loader/classloader/explicitlayout/Regressions/empty/explicitStruct_empty.csproj new file mode 100644 index 0000000000000..a304092ec069b --- /dev/null +++ b/src/tests/Loader/classloader/explicitlayout/Regressions/empty/explicitStruct_empty.csproj @@ -0,0 +1,5 @@ + + + + + diff --git a/src/tests/Regressions/coreclr/GitHub_61104/test61104.cs b/src/tests/Regressions/coreclr/GitHub_61104/test61104.cs new file mode 100644 index 0000000000000..2e01b96bf31d5 --- /dev/null +++ b/src/tests/Regressions/coreclr/GitHub_61104/test61104.cs @@ -0,0 +1,12 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +var type = Type.GetType("_测试数据记录仪_Iiİı_åäö_Controller_DataLogger1_log_all_", false); +var obj = Activator.CreateInstance(type!); +Console.WriteLine(obj?.GetType().Name); + +return 100; + +public class _测试数据记录仪_Iiİı_åäö_Controller_DataLogger1_log_all_ +{ +} diff --git a/src/tests/Regressions/coreclr/GitHub_61104/test61104.csproj b/src/tests/Regressions/coreclr/GitHub_61104/test61104.csproj new file mode 100644 index 0000000000000..b72e9a46cf95a --- /dev/null +++ b/src/tests/Regressions/coreclr/GitHub_61104/test61104.csproj @@ -0,0 +1,17 @@ + + + + Exe + enable + enable + 1 + + + true + + + + + + + diff --git a/src/tests/issues.targets b/src/tests/issues.targets index ae3c7c5034f4a..f6ffb0f93efa2 100644 --- a/src/tests/issues.targets +++ b/src/tests/issues.targets @@ -832,6 +832,9 @@ https://github.com/dotnet/runtime/issues/53560 + + https://github.com/dotnet/runtime/issues/63818 + https://github.com/dotnet/runtime/issues/56148 diff --git a/src/tests/nativeaot/SmokeTests/PInvoke/PInvoke.cs b/src/tests/nativeaot/SmokeTests/PInvoke/PInvoke.cs index 4e5375389455b..79fcc3928dd33 100644 --- a/src/tests/nativeaot/SmokeTests/PInvoke/PInvoke.cs +++ b/src/tests/nativeaot/SmokeTests/PInvoke/PInvoke.cs @@ -144,6 +144,28 @@ private static extern bool VerifySizeParamIndex( [DllImport("PInvokeNative", CallingConvention = CallingConvention.StdCall)] static extern bool ReversePInvoke_String(Delegate_String del); + [DllImport("PInvokeNative", EntryPoint="ReversePInvoke_String", CallingConvention = CallingConvention.StdCall)] + static extern bool ReversePInvoke_String_Delegate(Delegate del); + + [DllImport("PInvokeNative", EntryPoint="ReversePInvoke_String", CallingConvention = CallingConvention.StdCall)] + static extern bool ReversePInvoke_String_MulticastDelegate(MulticastDelegate del); + + struct FieldDelegate + { + public Delegate d; + } + + struct FieldMulticastDelegate + { + public MulticastDelegate d; + } + + [DllImport("PInvokeNative", EntryPoint="ReversePInvoke_DelegateField", CallingConvention = CallingConvention.StdCall)] + static extern bool ReversePInvoke_Field_Delegate(FieldDelegate del); + + [DllImport("PInvokeNative", EntryPoint="ReversePInvoke_DelegateField", CallingConvention = CallingConvention.StdCall)] + static extern bool ReversePInvoke_Field_MulticastDelegate(FieldMulticastDelegate del); + [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)] delegate bool Delegate_OutString([MarshalAs(0x30)] out string s); [DllImport("PInvokeNative", CallingConvention = CallingConvention.StdCall)] @@ -616,6 +638,16 @@ private static void TestDelegate() Delegate_String ds = new Delegate_String((new ClosedDelegateCLass()).GetString); ThrowIfNotEquals(true, ReversePInvoke_String(ds), "Delegate marshalling failed."); + ThrowIfNotEquals(true, ReversePInvoke_String_Delegate(ds), "Delegate marshalling failed."); + ThrowIfNotEquals(true, ReversePInvoke_String_MulticastDelegate(ds), "Delegate marshalling failed."); + + FieldDelegate fd; + fd.d = ds; + ThrowIfNotEquals(true, ReversePInvoke_Field_Delegate(fd), "Delegate marshalling failed."); + FieldMulticastDelegate fmd; + fmd.d = ds; + ThrowIfNotEquals(true, ReversePInvoke_Field_MulticastDelegate(fmd), "Delegate marshalling failed."); + Delegate_OutString dos = new Delegate_OutString((out string x) => { x = "Hello there!"; diff --git a/src/tests/nativeaot/SmokeTests/PInvoke/PInvokeNative.cpp b/src/tests/nativeaot/SmokeTests/PInvoke/PInvokeNative.cpp index 82736dabc0c92..f2e40e73538de 100644 --- a/src/tests/nativeaot/SmokeTests/PInvoke/PInvokeNative.cpp +++ b/src/tests/nativeaot/SmokeTests/PInvoke/PInvokeNative.cpp @@ -341,6 +341,17 @@ DLL_EXPORT bool __stdcall ReversePInvoke_String(StringFuncPtr fnPtr) return fnPtr(str); } +struct DelegateFieldStruct +{ + StringFuncPtr fnPtr; +}; + +DLL_EXPORT bool __stdcall ReversePInvoke_DelegateField(DelegateFieldStruct p) +{ + char str[] = "Hello World"; + return p.fnPtr(str); +} + typedef bool(__stdcall *OutStringFuncPtr) (char **); DLL_EXPORT bool __stdcall ReversePInvoke_OutString(OutStringFuncPtr fnPtr) { diff --git a/src/tests/profiler/native/gcprofiler/gcprofiler.cpp b/src/tests/profiler/native/gcprofiler/gcprofiler.cpp index 42666a2d8eac8..ed6312cd89c46 100644 --- a/src/tests/profiler/native/gcprofiler/gcprofiler.cpp +++ b/src/tests/profiler/native/gcprofiler/gcprofiler.cpp @@ -37,6 +37,10 @@ HRESULT GCProfiler::Shutdown() { printf("GCProfiler::Shutdown: FAIL: Expected GarbageCollectionFinished to be called\n"); } + else if (_allocatedByClassCalls == 0) + { + printf("GCProfiler::Shutdown: FAIL: Expected ObjectsAllocatedByClass to be called\n"); + } else if (_pohObjectsSeenRootReferences == 0 || _pohObjectsSeenObjectReferences == 0) { printf("GCProfiler::Shutdown: FAIL: no POH objects seen. root references=%d object references=%d\n", @@ -86,6 +90,20 @@ HRESULT GCProfiler::GarbageCollectionFinished() return S_OK; } +HRESULT GCProfiler::ObjectsAllocatedByClass(ULONG cClassCount, ClassID classIds[], ULONG cObjects[]) +{ + SHUTDOWNGUARD(); + + _allocatedByClassCalls++; + if (_gcStarts != _allocatedByClassCalls) + { + _failures++; + printf("GCProfiler::ObjectsAllocatedByClass: FAIL: Expected ObjectsAllocatedByClass Calls == GCStart. AllocatedByClassCalls=%d, GCStart=%d\n", (int)_allocatedByClassCalls, (int)_gcStarts); + } + + return S_OK; +} + HRESULT GCProfiler::ObjectReferences(ObjectID objectId, ClassID classId, ULONG cObjectRefs, ObjectID objectRefIds[]) { SHUTDOWNGUARD(); diff --git a/src/tests/profiler/native/gcprofiler/gcprofiler.h b/src/tests/profiler/native/gcprofiler/gcprofiler.h index ab519f6f53399..eebdb06853f7a 100644 --- a/src/tests/profiler/native/gcprofiler/gcprofiler.h +++ b/src/tests/profiler/native/gcprofiler/gcprofiler.h @@ -16,6 +16,7 @@ class GCProfiler : public Profiler GCProfiler() : Profiler(), _gcStarts(0), _gcFinishes(0), + _allocatedByClassCalls(0), _failures(0), _pohObjectsSeenRootReferences(0), _pohObjectsSeenObjectReferences(0), @@ -28,12 +29,14 @@ class GCProfiler : public Profiler virtual HRESULT STDMETHODCALLTYPE Shutdown(); virtual HRESULT STDMETHODCALLTYPE GarbageCollectionStarted(int cGenerations, BOOL generationCollected[], COR_PRF_GC_REASON reason); virtual HRESULT STDMETHODCALLTYPE GarbageCollectionFinished(); + virtual HRESULT STDMETHODCALLTYPE ObjectsAllocatedByClass(ULONG cClassCount, ClassID classIds[], ULONG cObjects[]); virtual HRESULT STDMETHODCALLTYPE ObjectReferences(ObjectID objectId, ClassID classId, ULONG cObjectRefs, ObjectID objectRefIds[]); virtual HRESULT STDMETHODCALLTYPE RootReferences(ULONG cRootRefs, ObjectID rootRefIds[]); private: std::atomic _gcStarts; std::atomic _gcFinishes; + std::atomic _allocatedByClassCalls; std::atomic _failures; std::atomic _pohObjectsSeenRootReferences; std::atomic _pohObjectsSeenObjectReferences; From 69ea51ecc425d5c7584d4e4885fc17556a6e82a4 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Thu, 20 Jan 2022 11:40:38 +0100 Subject: [PATCH 08/16] #51371 added pipeName case for running on macos --- .../Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index 13425342d094c..c42baf2730445 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -141,7 +141,7 @@ protected static string GetNamedPipeServerStreamName() return @"LOCAL\" + Guid.NewGuid().ToString("N"); } - if (PlatformDetection.IsWindows) + if (PlatformDetection.IsWindows || !PlatformDetection.IsNotRunningOnMacOS) { return Guid.NewGuid().ToString("N"); } From 869697316ae99af84770844655da5c1ec11a1e38 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Thu, 20 Jan 2022 17:57:39 +0100 Subject: [PATCH 09/16] #51371 removed extra spaces, adjusted IsCaseSensitiveProperty and other review comments changes --- .../System/IO/StreamConformanceTests.cs | 2 +- .../TestUtilities/System/IO/FileCleanupTestBase.cs | 7 ++++--- .../tests/TestUtilities/System/PlatformDetection.cs | 5 ++--- .../tests/Base/FileGetSetAttributes.cs | 2 +- .../tests/Directory/GetFileSystemEntries_str_str.cs | 5 ++--- .../System.IO.FileSystem/tests/File/Create.cs | 3 +-- .../System.IO.FileSystem/tests/File/Exists.cs | 2 +- .../src/System/IO/Pipes/NamedPipeClientStream.cs | 10 +--------- .../src/System/IO/Pipes/NamedPipeServerStream.Unix.cs | 4 +--- .../src/System/IO/Pipes/PipeStream.Unix.cs | 6 ++++++ .../src/System/IO/Pipes/PipeStream.Windows.cs | 6 ++++++ 11 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs b/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs index 1885c05fa206a..792e5387fd04a 100644 --- a/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs +++ b/src/libraries/Common/tests/StreamConformanceTests/System/IO/StreamConformanceTests.cs @@ -1595,7 +1595,7 @@ protected static bool Bidirectional(StreamPair streams) => streams.Stream1.CanRead && streams.Stream1.CanWrite && streams.Stream2.CanRead && streams.Stream2.CanWrite; - [Fact] + [Fact] public virtual async Task ArgumentValidation_ThrowsExpectedException() { using StreamPair streams = await CreateConnectedStreamsAsync(); diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index c42baf2730445..b0a07fe93df57 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -23,7 +23,7 @@ public abstract partial class FileCleanupTestBase : IDisposable /// Initialize the test class base. This creates the associated test directory. protected FileCleanupTestBase(string tempDirectory = null) { - tempDirectory ??= PlatformDetection.IsNotRunningOnMacOS ? Path.GetTempPath() : "/tmp/"; + tempDirectory ??= PlatformDetection.IsCaseSensitiveOS ? Path.GetTempPath() : "/tmp/"; // Use a unique test directory per test class. The test directory lives in the user's temp directory, // and includes both the name of the test class and a random string. The test class name is included @@ -108,7 +108,8 @@ protected string GetTestFileName(int? index = null, [CallerMemberName] string me const int maxLength = 260 - 5; // Windows MAX_PATH minus a bit - int excessLength = testFilePath.Length - maxLength; + int excessLength = testFilePath.Length - maxLength; + if (excessLength > 0) { // The path will be too long for Windows -- can we @@ -141,7 +142,7 @@ protected static string GetNamedPipeServerStreamName() return @"LOCAL\" + Guid.NewGuid().ToString("N"); } - if (PlatformDetection.IsWindows || !PlatformDetection.IsNotRunningOnMacOS) + if (PlatformDetection.IsWindows || !PlatformDetection.IsCaseSensitiveOS) { return Guid.NewGuid().ToString("N"); } diff --git a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs index a2a2e9634489b..8d5d1dedce192 100644 --- a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs +++ b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs @@ -60,7 +60,8 @@ public static partial class PlatformDetection public static bool IsNotWindows => !IsWindows; public static bool IsCaseInsensitiveOS => IsWindows || IsOSX || IsMacCatalyst; - public static bool IsCaseSensitiveOS => !IsCaseInsensitiveOS; + public static bool IsCaseSensitiveOS => !IsCaseInsensitiveOS && !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") + && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator"); public static bool IsThreadingSupported => !IsBrowser; public static bool IsBinaryFormatterSupported => IsNotMobile && !IsNativeAot; @@ -77,8 +78,6 @@ public static partial class PlatformDetection public static bool IsUsingLimitedCultures => !IsNotMobile; public static bool IsNotUsingLimitedCultures => IsNotMobile; - public static bool IsNotRunningOnMacOS => !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") - && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator") && !IsMacCatalyst; public static bool IsLinqExpressionsBuiltWithIsInterpretingOnly => s_LinqExpressionsBuiltWithIsInterpretingOnly.Value; public static bool IsNotLinqExpressionsBuiltWithIsInterpretingOnly => !IsLinqExpressionsBuiltWithIsInterpretingOnly; diff --git a/src/libraries/System.IO.FileSystem/tests/Base/FileGetSetAttributes.cs b/src/libraries/System.IO.FileSystem/tests/Base/FileGetSetAttributes.cs index bb26bf9127585..18fc5106f9be7 100644 --- a/src/libraries/System.IO.FileSystem/tests/Base/FileGetSetAttributes.cs +++ b/src/libraries/System.IO.FileSystem/tests/Base/FileGetSetAttributes.cs @@ -62,7 +62,7 @@ public void SettingInvalidAttributes_Unix(FileAttributes attributes) AssertSettingInvalidAttributes(path, attributes); } - [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotRunningOnMacOS))] + [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsCaseSensitiveOS))] [InlineData(FileAttributes.Hidden)] [PlatformSpecific(TestPlatforms.AnyUnix & ~(TestPlatforms.OSX | TestPlatforms.FreeBSD))] public void SettingInvalidAttributes_UnixExceptOSXAndFreeBSD(FileAttributes attributes) diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs b/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs index d8426618cf65c..3239a64240d2a 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs @@ -698,10 +698,9 @@ public void WindowsSearchPatternWhitespace() Assert.Empty(GetEntries(TestDirectory, "\t")); } - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotRunningOnMacOS))] - [PlatformSpecific(CaseSensitivePlatforms)] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsCaseSensitiveOS))] public void SearchPatternCaseSensitive() - { + { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testBase = GetTestFileName(); testDir.CreateSubdirectory(testBase + "aBBb"); diff --git a/src/libraries/System.IO.FileSystem/tests/File/Create.cs b/src/libraries/System.IO.FileSystem/tests/File/Create.cs index f55947be2b16d..d5aafe7db3e1f 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Create.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Create.cs @@ -219,8 +219,7 @@ public void LongFileName() Assert.False(File.Exists(path)); } - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotRunningOnMacOS))] - [PlatformSpecific(CaseSensitivePlatforms)] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsCaseSensitiveOS))] public void CaseSensitive() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); diff --git a/src/libraries/System.IO.FileSystem/tests/File/Exists.cs b/src/libraries/System.IO.FileSystem/tests/File/Exists.cs index 97a3d03e017f2..811df24f9e741 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Exists.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Exists.cs @@ -112,7 +112,7 @@ public void PathAlreadyExistsAsDirectory() } [Fact] - public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow() + public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow() { Assert.All((IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath())), (path) => { diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs index d4b15e912d992..d027d11988724 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs @@ -89,15 +89,7 @@ public NamedPipeClientStream(string serverName, string pipeName, PipeDirection d { IsCurrentUserOnly = true; } - if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") - || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) - { - _normalizedPipePath = $"/tmp/{pipeName}"; - } - else - { - _normalizedPipePath = GetPipePath(serverName, pipeName); - } + _normalizedPipePath = GetPipePath(serverName, pipeName); _direction = direction; _inheritability = inheritability; _impersonationLevel = impersonationLevel; diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs index 2db15594a52e5..4744afa610486 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs @@ -41,10 +41,8 @@ private void Create(string pipeName, PipeDirection direction, int maxNumberOfSer // We don't have a good way to enforce maxNumberOfServerInstances across processes; we only factor it in // for streams created in this process. Between processes, we behave similarly to maxNumberOfServerInstances == 1, // in that the second process to come along and create a stream will find the pipe already in existence and will fail. - var pipePath = !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") - && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator") ? GetPipePath(".", pipeName) : $"/tmp/{pipeName}"; _instance = SharedServer.Get( - pipePath, + GetPipePath(".", pipeName), (maxNumberOfServerInstances == MaxAllowedServerInstances) ? int.MaxValue : maxNumberOfServerInstances); _direction = direction; diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs index f4f0caca1c562..71f17edeacb54 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs @@ -196,6 +196,12 @@ internal static string GetPipePath(string serverName, string pipeName) throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } + if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") + || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) + { + return $"/tmp/{pipeName}"; + } + // Since pipes are stored as files in the system we support either an absolute path to a file name // or a file name. The support of absolute path was added to allow working around the limited // length available for the pipe name when concatenated with the temp path, while being diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs index 1a1134c7f1503..bfd6f18611236 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs @@ -232,6 +232,12 @@ public override void EndWrite(IAsyncResult asyncResult) internal static string GetPipePath(string serverName, string pipeName) { + if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") + || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) + { + return $"/tmp/{pipeName}"; + } + string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName); if (string.Equals(normalizedPipePath, @"\\.\pipe\" + AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) { From 507d23950c2cea2ccb19190fde6b1db752c354bc Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Fri, 21 Jan 2022 08:34:07 +0100 Subject: [PATCH 10/16] #51371 removed extra spaces --- .../tests/TestUtilities/System/IO/FileCleanupTestBase.cs | 2 +- .../src/System/IO/Pipes/NamedPipeClientStream.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index b0a07fe93df57..1df037cad7d7c 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -109,7 +109,7 @@ protected string GetTestFileName(int? index = null, [CallerMemberName] string me const int maxLength = 260 - 5; // Windows MAX_PATH minus a bit int excessLength = testFilePath.Length - maxLength; - + if (excessLength > 0) { // The path will be too long for Windows -- can we diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs index d027d11988724..0c9fbc21f5b1e 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs @@ -79,7 +79,7 @@ public NamedPipeClientStream(string serverName, string pipeName, PipeDirection d } if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation) { - throw new ArgumentOutOfRangeException(nameof(impersonationLevel), SR.ArgumentOutOfRange_ImpersonationInvalid); + throw new ArgumentOutOfRangeException(nameof(impersonationLevel), SR.ArgumentOutOfRange_ImpersonationInvalid); } if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) { @@ -89,6 +89,7 @@ public NamedPipeClientStream(string serverName, string pipeName, PipeDirection d { IsCurrentUserOnly = true; } + _normalizedPipePath = GetPipePath(serverName, pipeName); _direction = direction; _inheritability = inheritability; From 61540879bba29599aaa0c13f70377727a33b987a Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Fri, 21 Jan 2022 11:18:55 +0100 Subject: [PATCH 11/16] #51371 removed pipePath change in windows file --- .../src/System/IO/Pipes/PipeStream.Windows.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs index bfd6f18611236..9b692742a9db6 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs @@ -232,11 +232,6 @@ public override void EndWrite(IAsyncResult asyncResult) internal static string GetPipePath(string serverName, string pipeName) { - if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") - || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) - { - return $"/tmp/{pipeName}"; - } string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName); if (string.Equals(normalizedPipePath, @"\\.\pipe\" + AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) From d989e861739b3c67cb3bbf2f1b36213d79901422 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Fri, 21 Jan 2022 12:12:52 +0100 Subject: [PATCH 12/16] #51371 Done minor changes --- .../Common/tests/TestUtilities/System/PlatformDetection.cs | 2 +- .../tests/Directory/GetFileSystemEntries_str_str.cs | 1 - src/libraries/System.IO.FileSystem/tests/File/Create.cs | 2 -- .../src/System/IO/Pipes/NamedPipeClientStream.cs | 1 - .../System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs | 1 - 5 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs index 8d5d1dedce192..e0314c4969d43 100644 --- a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs +++ b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs @@ -61,7 +61,7 @@ public static partial class PlatformDetection public static bool IsCaseInsensitiveOS => IsWindows || IsOSX || IsMacCatalyst; public static bool IsCaseSensitiveOS => !IsCaseInsensitiveOS && !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") - && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator"); + && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator"); public static bool IsThreadingSupported => !IsBrowser; public static bool IsBinaryFormatterSupported => IsNotMobile && !IsNativeAot; diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs b/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs index 3239a64240d2a..e439db9369f42 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs @@ -4,7 +4,6 @@ using System.Runtime.InteropServices; using Xunit; using System.Linq; -using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Tests { diff --git a/src/libraries/System.IO.FileSystem/tests/File/Create.cs b/src/libraries/System.IO.FileSystem/tests/File/Create.cs index d5aafe7db3e1f..69e9042ae1b54 100644 --- a/src/libraries/System.IO.FileSystem/tests/File/Create.cs +++ b/src/libraries/System.IO.FileSystem/tests/File/Create.cs @@ -2,9 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; -using System.Runtime.InteropServices; using Xunit; -using Microsoft.DotNet.XUnitExtensions; namespace System.IO.Tests { diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs index 0c9fbc21f5b1e..a03b5f1eaa524 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs @@ -7,7 +7,6 @@ using System.Threading; using System.Threading.Tasks; using System.Diagnostics; -using System.Runtime.InteropServices; namespace System.IO.Pipes { diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs index 9b692742a9db6..1a1134c7f1503 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs @@ -232,7 +232,6 @@ public override void EndWrite(IAsyncResult asyncResult) internal static string GetPipePath(string serverName, string pipeName) { - string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName); if (string.Equals(normalizedPipePath, @"\\.\pipe\" + AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) { From d4570759e36b9c7e1311d503e9ad2999730243e9 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Mon, 24 Jan 2022 13:03:30 +0100 Subject: [PATCH 13/16] #51371 extended maxdirectory for not windows --- .../tests/TestUtilities/System/IO/FileCleanupTestBase.cs | 2 +- .../System.IO.FileSystem/tests/Directory/GetFiles.cs | 6 +++--- .../System.IO.FileSystem/tests/PortedCommon/IOInputs.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index 1df037cad7d7c..be4ce55627359 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -23,7 +23,7 @@ public abstract partial class FileCleanupTestBase : IDisposable /// Initialize the test class base. This creates the associated test directory. protected FileCleanupTestBase(string tempDirectory = null) { - tempDirectory ??= PlatformDetection.IsCaseSensitiveOS ? Path.GetTempPath() : "/tmp/"; + tempDirectory ??= Path.GetTempPath(); // Use a unique test directory per test class. The test directory lives in the user's temp directory, // and includes both the name of the test class and a random string. The test class name is included diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs b/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs index e25787c813662..0bed6292626aa 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs @@ -46,9 +46,9 @@ public void EnumerateFilesOverLegacyMaxPath() { // We want to test that directories under the legacy MAX_PATH (260 characters, including the null) can iterate files // even if the full path is over 260. - - string directory = IOServices.GetPath(GetTestFilePath(), 250); - Assert.Equal(250, directory.Length); + var length = OperatingSystem.IsWindows() ? 250 : 1010; + string directory = IOServices.GetPath(GetTestFilePath(), length); + Assert.Equal(length, directory.Length); Assert.True(Directory.CreateDirectory(directory).Exists); for (int i = 0; i < 6; i++) diff --git a/src/libraries/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs b/src/libraries/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs index 677a027a732ea..aef992ea86e4e 100644 --- a/src/libraries/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs +++ b/src/libraries/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs @@ -23,7 +23,7 @@ internal static class IOInputs // Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move. // Does not include the trailing \0. // We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction. - public static readonly int MaxDirectory = 247; + public static readonly int MaxDirectory = OperatingSystem.IsWindows() ? 247 : 1016; public const int MaxComponent = 255; From bdc06e919d431fa1fa51f1979a432a97b2e60217 Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Tue, 25 Jan 2022 16:53:12 +0100 Subject: [PATCH 14/16] #51371 in case of windows don't change parameter IsCaseSensitiveOS --- .../Common/tests/TestUtilities/System/PlatformDetection.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs index e0314c4969d43..5057bc2fa7645 100644 --- a/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs +++ b/src/libraries/Common/tests/TestUtilities/System/PlatformDetection.cs @@ -60,9 +60,14 @@ public static partial class PlatformDetection public static bool IsNotWindows => !IsWindows; public static bool IsCaseInsensitiveOS => IsWindows || IsOSX || IsMacCatalyst; + +#if NETCOREAPP public static bool IsCaseSensitiveOS => !IsCaseInsensitiveOS && !RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") && !RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator"); - +#else + public static bool IsCaseSensitiveOS => !IsCaseInsensitiveOS; +#endif + public static bool IsThreadingSupported => !IsBrowser; public static bool IsBinaryFormatterSupported => IsNotMobile && !IsNativeAot; public static bool IsSymLinkSupported => !IsiOS && !IstvOS; From eddd2ca13640b5e98627d428073e4e01c5a5f6dd Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Tue, 25 Jan 2022 21:22:42 +0100 Subject: [PATCH 15/16] #51371 changing maxdirectory for nonwindows --- src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs | 2 +- .../System.IO.FileSystem/tests/PortedCommon/IOInputs.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs b/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs index 0bed6292626aa..f214f08899bcd 100644 --- a/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs +++ b/src/libraries/System.IO.FileSystem/tests/Directory/GetFiles.cs @@ -46,7 +46,7 @@ public void EnumerateFilesOverLegacyMaxPath() { // We want to test that directories under the legacy MAX_PATH (260 characters, including the null) can iterate files // even if the full path is over 260. - var length = OperatingSystem.IsWindows() ? 250 : 1010; + var length = OperatingSystem.IsWindows() ? 250 : 258; string directory = IOServices.GetPath(GetTestFilePath(), length); Assert.Equal(length, directory.Length); Assert.True(Directory.CreateDirectory(directory).Exists); diff --git a/src/libraries/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs b/src/libraries/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs index aef992ea86e4e..7187dc7339c9a 100644 --- a/src/libraries/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs +++ b/src/libraries/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs @@ -23,7 +23,7 @@ internal static class IOInputs // Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move. // Does not include the trailing \0. // We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction. - public static readonly int MaxDirectory = OperatingSystem.IsWindows() ? 247 : 1016; + public static readonly int MaxDirectory = OperatingSystem.IsWindows() ? 247 : 258; public const int MaxComponent = 255; From 2501ef2a4a8cfe703623f80008b8e22affad431f Mon Sep 17 00:00:00 2001 From: Meri Khamoyan Date: Wed, 26 Jan 2022 21:47:46 +0100 Subject: [PATCH 16/16] #51371 removed from Pipestream the change and edited path in FileCleanupTestBase.cs --- .../tests/TestUtilities/System/IO/FileCleanupTestBase.cs | 7 ++++++- .../System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs | 6 ------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index be4ce55627359..8f14f24f97f93 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -142,11 +142,16 @@ protected static string GetNamedPipeServerStreamName() return @"LOCAL\" + Guid.NewGuid().ToString("N"); } - if (PlatformDetection.IsWindows || !PlatformDetection.IsCaseSensitiveOS) + if (PlatformDetection.IsWindows) { return Guid.NewGuid().ToString("N"); } + if (!PlatformDetection.IsCaseSensitiveOS) + { + return $"/tmp/{Guid.NewGuid().ToString("N")}"; + } + const int MinUdsPathLength = 104; // required min is 92, but every platform we currently target is at least 104 const int MinAvailableForSufficientRandomness = 5; // we want enough randomness in the name to avoid conflicts between concurrent tests string prefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_"); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs index 71f17edeacb54..f4f0caca1c562 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs @@ -196,12 +196,6 @@ internal static string GetPipePath(string serverName, string pipeName) throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } - if (RuntimeInformation.RuntimeIdentifier.StartsWith("iossimulator") - || RuntimeInformation.RuntimeIdentifier.StartsWith("tvossimulator")) - { - return $"/tmp/{pipeName}"; - } - // Since pipes are stored as files in the system we support either an absolute path to a file name // or a file name. The support of absolute path was added to allow working around the limited // length available for the pipe name when concatenated with the temp path, while being