repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/runtime
66,022
Add Android 32 to RID graph
Supports Android 12L, which will be stable most likely by summer or earlier.
steveisok
2022-03-01T19:37:08Z
2022-03-11T21:09:58Z
a883caa0803778084167b978281c34db8e753246
36a435cf12309f5119c2f5ce103af7fa28150d72
Add Android 32 to RID graph. Supports Android 12L, which will be stable most likely by summer or earlier.
./src/tests/JIT/jit64/valuetypes/nullable/castclass/enum/castclass-enum002.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass-enum002.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass-enum002.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,022
Add Android 32 to RID graph
Supports Android 12L, which will be stable most likely by summer or earlier.
steveisok
2022-03-01T19:37:08Z
2022-03-11T21:09:58Z
a883caa0803778084167b978281c34db8e753246
36a435cf12309f5119c2f5ce103af7fa28150d72
Add Android 32 to RID graph. Supports Android 12L, which will be stable most likely by summer or earlier.
./src/tests/JIT/Regression/JitBlue/GitHub_17329/GitHub_17329.cs
// 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; // Having an UnsafeValueTypeAttribute on a struct causes incoming arguments to be // spilled into shadow copies and the struct promotion optimization does not // currently handle this properly. // [UnsafeValueTypeAttribute] struct DangerousBuffer { public long a; public long b; public long c; } struct Point1 { long x; public Point1(long _x) { x = _x; } public void Increase(ref Point1 s, long amount) { x = s.x + amount; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public long Value() { return x; } } class TestCase { static public long[] arr; unsafe static long Test(int size, Point1 a, Point1 b, Point1 c) { // Mutate the values stored in a, b and c // So if these have a shadow copy we will notice // a.Increase(ref a, arr[0]); b.Increase(ref b, arr[1]); c.Increase(ref c, arr[2]); DangerousBuffer db = new DangerousBuffer(); db.a = -1; db.b = -2; db.c = -3; long* x1 = stackalloc long[size]; long sum = 0; if (size >= 3) { x1[0] = a.Value(); x1[1] = b.Value(); x1[2] = c.Value(); for (int i = 0; i < size; i++) { sum += x1[i]; } } return sum; } static int Main() { long testResult = 0; int mainResult = 0; Point1 p1 = new Point1(1); Point1 p2 = new Point1(3); Point1 p3 = new Point1(5); arr = new long[3]; arr[0] = 9; arr[1] = 10; arr[2] = 11; testResult = Test(3, p1, p2, p3); if (testResult != 39) { Console.WriteLine("FAILED!"); mainResult = -1; } else { Console.WriteLine("passed"); mainResult = 100; } return mainResult; } }
// 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; // Having an UnsafeValueTypeAttribute on a struct causes incoming arguments to be // spilled into shadow copies and the struct promotion optimization does not // currently handle this properly. // [UnsafeValueTypeAttribute] struct DangerousBuffer { public long a; public long b; public long c; } struct Point1 { long x; public Point1(long _x) { x = _x; } public void Increase(ref Point1 s, long amount) { x = s.x + amount; } [MethodImplAttribute(MethodImplOptions.NoInlining)] public long Value() { return x; } } class TestCase { static public long[] arr; unsafe static long Test(int size, Point1 a, Point1 b, Point1 c) { // Mutate the values stored in a, b and c // So if these have a shadow copy we will notice // a.Increase(ref a, arr[0]); b.Increase(ref b, arr[1]); c.Increase(ref c, arr[2]); DangerousBuffer db = new DangerousBuffer(); db.a = -1; db.b = -2; db.c = -3; long* x1 = stackalloc long[size]; long sum = 0; if (size >= 3) { x1[0] = a.Value(); x1[1] = b.Value(); x1[2] = c.Value(); for (int i = 0; i < size; i++) { sum += x1[i]; } } return sum; } static int Main() { long testResult = 0; int mainResult = 0; Point1 p1 = new Point1(1); Point1 p2 = new Point1(3); Point1 p3 = new Point1(5); arr = new long[3]; arr[0] = 9; arr[1] = 10; arr[2] = 11; testResult = Test(3, p1, p2, p3); if (testResult != 39) { Console.WriteLine("FAILED!"); mainResult = -1; } else { Console.WriteLine("passed"); mainResult = 100; } return mainResult; } }
-1
dotnet/runtime
66,022
Add Android 32 to RID graph
Supports Android 12L, which will be stable most likely by summer or earlier.
steveisok
2022-03-01T19:37:08Z
2022-03-11T21:09:58Z
a883caa0803778084167b978281c34db8e753246
36a435cf12309f5119c2f5ce103af7fa28150d72
Add Android 32 to RID graph. Supports Android 12L, which will be stable most likely by summer or earlier.
./src/installer/tests/Directory.Build.props
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props, $(MSBuildThisFileDirectory)..))" /> <PropertyGroup> <TestDir>$(InstallerProjectRoot)tests\</TestDir> <TestAssetsDir>$(TestDir)Assets\</TestAssetsDir> <TestStabilizedLegacyPackagesDir>$(ArtifactsObjDir)TestStabilizedPackages\</TestStabilizedLegacyPackagesDir> <TestRestorePackagesPath>$(ArtifactsObjDir)TestPackageCache\</TestRestorePackagesPath> <TestRestoreNuGetConfigFile>$(ArtifactsObjDir)TestNuGetConfig\NuGet.config</TestRestoreNuGetConfigFile> <InternalNupkgCacheDir>$(ArtifactsObjDir)ExtraNupkgsForTestRestore\</InternalNupkgCacheDir> <TestArchitectures>$(TargetArchitecture)</TestArchitectures> <TestInfraTargetFramework>$(NetCoreAppToolCurrent)</TestInfraTargetFramework> <TestRunnerAdditionalArguments>-notrait category=failing</TestRunnerAdditionalArguments> <RunAnalyzers>false</RunAnalyzers> </PropertyGroup> </Project>
<Project> <Import Project="$([MSBuild]::GetPathOfFileAbove(Directory.Build.props, $(MSBuildThisFileDirectory)..))" /> <PropertyGroup> <TestDir>$(InstallerProjectRoot)tests\</TestDir> <TestAssetsDir>$(TestDir)Assets\</TestAssetsDir> <TestStabilizedLegacyPackagesDir>$(ArtifactsObjDir)TestStabilizedPackages\</TestStabilizedLegacyPackagesDir> <TestRestorePackagesPath>$(ArtifactsObjDir)TestPackageCache\</TestRestorePackagesPath> <TestRestoreNuGetConfigFile>$(ArtifactsObjDir)TestNuGetConfig\NuGet.config</TestRestoreNuGetConfigFile> <InternalNupkgCacheDir>$(ArtifactsObjDir)ExtraNupkgsForTestRestore\</InternalNupkgCacheDir> <TestArchitectures>$(TargetArchitecture)</TestArchitectures> <TestInfraTargetFramework>$(NetCoreAppToolCurrent)</TestInfraTargetFramework> <TestRunnerAdditionalArguments>-notrait category=failing</TestRunnerAdditionalArguments> <RunAnalyzers>false</RunAnalyzers> </PropertyGroup> </Project>
-1
dotnet/runtime
66,022
Add Android 32 to RID graph
Supports Android 12L, which will be stable most likely by summer or earlier.
steveisok
2022-03-01T19:37:08Z
2022-03-11T21:09:58Z
a883caa0803778084167b978281c34db8e753246
36a435cf12309f5119c2f5ce103af7fa28150d72
Add Android 32 to RID graph. Supports Android 12L, which will be stable most likely by summer or earlier.
./docs/design/coreclr/botr/stackwalking.md
Stackwalking in the CLR === Author: Rudi Martin ([@Rudi-Martin](https://github.com/Rudi-Martin)) - 2008 The CLR makes heavy use of a technique known as stack walking (or stack crawling). This involves iterating the sequence of call frames for a particular thread, from the most recent (the thread's current function) back down to the base of the stack. The runtime uses stack walks for a number of purposes: - The runtime walks the stacks of all threads during garbage collection, looking for managed roots (local variables holding object references in the frames of managed methods that need to be reported to the GC to keep the objects alive and possibly track their movement if the GC decides to compact the heap). - On some platforms the stack walker is used during the processing of exceptions (looking for handlers in the first pass and unwinding the stack in the second). - The debugger uses the functionality when generating managed stack traces. - Various miscellaneous methods, usually those close to some public managed API, perform a stack walk to pick up information about their caller (such as the method, class or assembly of that caller). # The Stack Model Here we define some common terms and describe the typical layout of a thread's stack. Logically, a stack is divided up into some number of _frames_. Each frame represents some function (managed or unmanaged) that is either currently executing or has called into some other function and is waiting for it to return. A frame contains state required by the specific invocation of its associated function. Typically this includes space for local variables, pushed arguments for a call to another function, saved caller registers etc. The exact definition of a frame varies from platform to platform and on many platforms there isn't a hard definition of a frame format that all functions adhere to (x86 is an example of this). Instead the compiler is often free to optimize the exact format of frames. On such systems it is not possible to guarantee that a stackwalk will return 100% correct or complete results (for debugging purposes, debug symbols such as pdbs are used to fill in the gaps so that debuggers can generate more accurate stack traces). This is not a problem for the CLR, however, since we do not require a fully generalized stack walk. Instead we are only interested in those frames that are managed (i.e. represent a managed method) or, to some extent, frames coming from unmanaged code used to implement part of the runtime itself. In particular there is no guarantee about fidelity of 3rd party unmanaged frames other than to note where such frames transition into or out of the runtime itself (i.e. one of the frame types we do care about). Because we control the format of the frames we're interested in (we'll delve into the details of this later) we can ensure that those frames are crawlable with 100% fidelity. The only additional requirement is a mechanism to link disjoint groups of runtime frames together such that we can skip over any intervening unmanaged (and otherwise uncrawlable) frames. The following diagram illustrates a stack containing all the frames types (note that this document uses a convention where stacks grow towards the top of the page): ![image](images/stack.png) # Making Frames Crawlable ## Managed Frames Because the runtime owns and controls the JIT (Just-in-Time compiler) it can arrange for managed methods to always leave a crawlable frame. One solution here would be to utilize a rigid frame format for all methods (e.g. the x86 EBP frame format). In practice, however, this can be inefficient, especially for small leaf methods (such as typical property accessors). Since methods are typically called more times than their frames are crawled (stack crawls are relatively rare in the runtime, at least with respect to the rate at which methods are typically called) it makes sense to trade method call performance for some additional crawl time processing. As a result the JIT generates additional metadata for each method it compiles that includes sufficient information for the stack crawler to decode a stack frame belonging to that method. This metadata can be found via a hash-table lookup with an instruction pointer somewhere within the method as the key. The JIT utilizes compression techniques in order to minimize the impact of this additional per-method metadata. Given initial values for a few important registers (e.g. EIP, ESP and EBP on x86 based systems) the stack crawler can locate a managed method and its associated JIT metadata and use this information to roll back the register values to those current in the method's caller. In this fashion a sequence of managed method frames can be traversed from the most recent to the oldest caller. This operation is sometimes referred to as a _virtual unwind_ (virtual because we're not actually updating the real values of ESP etc., leaving the stack intact). ## Runtime Unmanaged Frames The runtime is partially implemented in unmanaged code (e.g. coreclr.dll). Most of this code is special in that it operates as _manually managed_ code. That is, it obeys many of the rules and protocols of managed code but in an explicitly controlled fashion. For instance such code can explicitly enable or disable GC pre-emptive mode and needs to manage its use of object references accordingly. Another area where this careful interaction with managed code comes into play is during stackwalks. Since the majority of the runtime's unmanaged code is written in C++ we don't have the same control over method frame format as managed code. At the same time there are many instances where runtime unmanaged frames contain information that is important during a stack walk. These include cases where unmanaged functions hold object references in local variables (which must be reported during garbage collections) and exception processing. Rather than attempt to make each unmanaged frame crawable, unmanaged functions with interesting data to report to stack crawls bundle up the information into a data structure called a Frame. The choice of name is unfortunate as it can lead to ambiguity in stack related discussions. This document will always refer to the data structure variant as a capitalized Frame. Frame is actually the abstract base class of an entire hierarchy of Frame types. Frame is sub-typed in order to express different types of information that might be interesting to a stack walk. But how does the stack walker find these Frames and how do they relate to the frames utilized by managed methods? Each Frame is part of a singly linked list, having a next pointer to the next oldest Frame on this thread's stack (or null if the Frame is the oldest). The CLR Thread structure holds a pointer to the newest Frame. Unmanaged runtime code can push or pop Frames as needed by manipulating the Thread structure and Frame list. In this fashion the stack walker can iterate unmanaged Frames in newest to oldest order (the same order in which managed frames are iterated). But managed and unmanaged methods can be interleaved, and it would be wrong to process all managed frames followed by unmanaged Frames or vice versa since that would not accurately represent the real calling sequence. To solve this problem Frames are further restricted in that they must be allocated on the stack in the frame of the method that pushes them onto the Frame list. Since the stack walker knows the stack bounds of each managed frame it can perform simple pointer comparisons to determine whether a given Frame is older or newer than a given managed frame. Essentially the stack walker, having decoded the current frame, always has two possible choices for the next (older) frame: the next managed frame determined via a virtual unwind of the register set or the next oldest Frame on the Thread's Frame list. It can decide which is appropriate by determining which occupies stack space nearer the stack top. The actual calculation involved is platform dependent but usually devolves to one or two pointer comparisons. When managed code calls into the unmanaged runtime one of several forms of transition Frame is often pushed by the unmanaged target method. This is needed both to record the register state of the calling managed method (so that the stack walker can resume virtual unwinding of managed frames once it has finished enumerating the unmanaged Frames) and in many cases because managed object references are passed as arguments to the unmanaged method and must be reported to the GC in the event of a garbage collection. A full description of the available Frame types and their uses is beyond the scope of the document. Further details can be found in the [frames.h](https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/frames.h) header file. # Stackwalker Interface The full stack walk interface is exposed to runtime unmanaged code only (a simplified subset is available to managed code via the System.Diagnostics.StackTrace class). The typical entrypoint is via the StackWalkFramesEx() method on the runtime Thread class. The caller of this method provides three main inputs: 1. Some context indicating the starting point of the walk. This is either an initial register set (for instance if you've suspended the target thread and can call GetThreadContext() on it) or an initial Frame (in cases where you know the code in question is in runtime unmanaged code). Although most stack walks are made from the top of the stack it's possible to start lower down if you can determine the correct starting context. 2. A function pointer and associated context. The function provided is called by the stack walker for each interesting frame (in order from the newest to the oldest). The context value provided is passed to each invocation of the callback so that it can record or build up state during the walk. 3. Flags indicating what sort of frames should trigger a callback. This allows the caller to specify that only pure managed method frames should be reported for instance. For a full list see [threads.h](https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/threads.h) (just above the declaration of StackWalkFramesEx()). StackWalkFramesEx() returns an enum value that indicates whether the walk terminated normally (got to the stack base and ran out of methods to report), was aborted by one of the callbacks (the callbacks return an enum of the same type to the stack walk to control this) or suffered some other miscellaneous error. Aside from the context value passed to StackWalkFramesEx(), stack callback functions are passed one other piece of context: the CrawlFrame. This class is defined in [stackwalk.h](https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/stackwalk.h) and contains all sorts of context gathered as the stack walk proceeds. For instance the CrawlFrame indicates the MethodDesc* for managed frames and the Frame* for unmanaged Frames. It also provides the current register set inferred by virtually unwinding frames up to that point. # Stackwalk Implementation Details Further low-level details of the stack walk implementation are currently outside the scope of this document. If you have knowledge of these and would care to share that knowledge please feel free to update this document.
Stackwalking in the CLR === Author: Rudi Martin ([@Rudi-Martin](https://github.com/Rudi-Martin)) - 2008 The CLR makes heavy use of a technique known as stack walking (or stack crawling). This involves iterating the sequence of call frames for a particular thread, from the most recent (the thread's current function) back down to the base of the stack. The runtime uses stack walks for a number of purposes: - The runtime walks the stacks of all threads during garbage collection, looking for managed roots (local variables holding object references in the frames of managed methods that need to be reported to the GC to keep the objects alive and possibly track their movement if the GC decides to compact the heap). - On some platforms the stack walker is used during the processing of exceptions (looking for handlers in the first pass and unwinding the stack in the second). - The debugger uses the functionality when generating managed stack traces. - Various miscellaneous methods, usually those close to some public managed API, perform a stack walk to pick up information about their caller (such as the method, class or assembly of that caller). # The Stack Model Here we define some common terms and describe the typical layout of a thread's stack. Logically, a stack is divided up into some number of _frames_. Each frame represents some function (managed or unmanaged) that is either currently executing or has called into some other function and is waiting for it to return. A frame contains state required by the specific invocation of its associated function. Typically this includes space for local variables, pushed arguments for a call to another function, saved caller registers etc. The exact definition of a frame varies from platform to platform and on many platforms there isn't a hard definition of a frame format that all functions adhere to (x86 is an example of this). Instead the compiler is often free to optimize the exact format of frames. On such systems it is not possible to guarantee that a stackwalk will return 100% correct or complete results (for debugging purposes, debug symbols such as pdbs are used to fill in the gaps so that debuggers can generate more accurate stack traces). This is not a problem for the CLR, however, since we do not require a fully generalized stack walk. Instead we are only interested in those frames that are managed (i.e. represent a managed method) or, to some extent, frames coming from unmanaged code used to implement part of the runtime itself. In particular there is no guarantee about fidelity of 3rd party unmanaged frames other than to note where such frames transition into or out of the runtime itself (i.e. one of the frame types we do care about). Because we control the format of the frames we're interested in (we'll delve into the details of this later) we can ensure that those frames are crawlable with 100% fidelity. The only additional requirement is a mechanism to link disjoint groups of runtime frames together such that we can skip over any intervening unmanaged (and otherwise uncrawlable) frames. The following diagram illustrates a stack containing all the frames types (note that this document uses a convention where stacks grow towards the top of the page): ![image](images/stack.png) # Making Frames Crawlable ## Managed Frames Because the runtime owns and controls the JIT (Just-in-Time compiler) it can arrange for managed methods to always leave a crawlable frame. One solution here would be to utilize a rigid frame format for all methods (e.g. the x86 EBP frame format). In practice, however, this can be inefficient, especially for small leaf methods (such as typical property accessors). Since methods are typically called more times than their frames are crawled (stack crawls are relatively rare in the runtime, at least with respect to the rate at which methods are typically called) it makes sense to trade method call performance for some additional crawl time processing. As a result the JIT generates additional metadata for each method it compiles that includes sufficient information for the stack crawler to decode a stack frame belonging to that method. This metadata can be found via a hash-table lookup with an instruction pointer somewhere within the method as the key. The JIT utilizes compression techniques in order to minimize the impact of this additional per-method metadata. Given initial values for a few important registers (e.g. EIP, ESP and EBP on x86 based systems) the stack crawler can locate a managed method and its associated JIT metadata and use this information to roll back the register values to those current in the method's caller. In this fashion a sequence of managed method frames can be traversed from the most recent to the oldest caller. This operation is sometimes referred to as a _virtual unwind_ (virtual because we're not actually updating the real values of ESP etc., leaving the stack intact). ## Runtime Unmanaged Frames The runtime is partially implemented in unmanaged code (e.g. coreclr.dll). Most of this code is special in that it operates as _manually managed_ code. That is, it obeys many of the rules and protocols of managed code but in an explicitly controlled fashion. For instance such code can explicitly enable or disable GC pre-emptive mode and needs to manage its use of object references accordingly. Another area where this careful interaction with managed code comes into play is during stackwalks. Since the majority of the runtime's unmanaged code is written in C++ we don't have the same control over method frame format as managed code. At the same time there are many instances where runtime unmanaged frames contain information that is important during a stack walk. These include cases where unmanaged functions hold object references in local variables (which must be reported during garbage collections) and exception processing. Rather than attempt to make each unmanaged frame crawable, unmanaged functions with interesting data to report to stack crawls bundle up the information into a data structure called a Frame. The choice of name is unfortunate as it can lead to ambiguity in stack related discussions. This document will always refer to the data structure variant as a capitalized Frame. Frame is actually the abstract base class of an entire hierarchy of Frame types. Frame is sub-typed in order to express different types of information that might be interesting to a stack walk. But how does the stack walker find these Frames and how do they relate to the frames utilized by managed methods? Each Frame is part of a singly linked list, having a next pointer to the next oldest Frame on this thread's stack (or null if the Frame is the oldest). The CLR Thread structure holds a pointer to the newest Frame. Unmanaged runtime code can push or pop Frames as needed by manipulating the Thread structure and Frame list. In this fashion the stack walker can iterate unmanaged Frames in newest to oldest order (the same order in which managed frames are iterated). But managed and unmanaged methods can be interleaved, and it would be wrong to process all managed frames followed by unmanaged Frames or vice versa since that would not accurately represent the real calling sequence. To solve this problem Frames are further restricted in that they must be allocated on the stack in the frame of the method that pushes them onto the Frame list. Since the stack walker knows the stack bounds of each managed frame it can perform simple pointer comparisons to determine whether a given Frame is older or newer than a given managed frame. Essentially the stack walker, having decoded the current frame, always has two possible choices for the next (older) frame: the next managed frame determined via a virtual unwind of the register set or the next oldest Frame on the Thread's Frame list. It can decide which is appropriate by determining which occupies stack space nearer the stack top. The actual calculation involved is platform dependent but usually devolves to one or two pointer comparisons. When managed code calls into the unmanaged runtime one of several forms of transition Frame is often pushed by the unmanaged target method. This is needed both to record the register state of the calling managed method (so that the stack walker can resume virtual unwinding of managed frames once it has finished enumerating the unmanaged Frames) and in many cases because managed object references are passed as arguments to the unmanaged method and must be reported to the GC in the event of a garbage collection. A full description of the available Frame types and their uses is beyond the scope of the document. Further details can be found in the [frames.h](https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/frames.h) header file. # Stackwalker Interface The full stack walk interface is exposed to runtime unmanaged code only (a simplified subset is available to managed code via the System.Diagnostics.StackTrace class). The typical entrypoint is via the StackWalkFramesEx() method on the runtime Thread class. The caller of this method provides three main inputs: 1. Some context indicating the starting point of the walk. This is either an initial register set (for instance if you've suspended the target thread and can call GetThreadContext() on it) or an initial Frame (in cases where you know the code in question is in runtime unmanaged code). Although most stack walks are made from the top of the stack it's possible to start lower down if you can determine the correct starting context. 2. A function pointer and associated context. The function provided is called by the stack walker for each interesting frame (in order from the newest to the oldest). The context value provided is passed to each invocation of the callback so that it can record or build up state during the walk. 3. Flags indicating what sort of frames should trigger a callback. This allows the caller to specify that only pure managed method frames should be reported for instance. For a full list see [threads.h](https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/threads.h) (just above the declaration of StackWalkFramesEx()). StackWalkFramesEx() returns an enum value that indicates whether the walk terminated normally (got to the stack base and ran out of methods to report), was aborted by one of the callbacks (the callbacks return an enum of the same type to the stack walk to control this) or suffered some other miscellaneous error. Aside from the context value passed to StackWalkFramesEx(), stack callback functions are passed one other piece of context: the CrawlFrame. This class is defined in [stackwalk.h](https://github.com/dotnet/runtime/blob/main/src/coreclr/vm/stackwalk.h) and contains all sorts of context gathered as the stack walk proceeds. For instance the CrawlFrame indicates the MethodDesc* for managed frames and the Frame* for unmanaged Frames. It also provides the current register set inferred by virtually unwinding frames up to that point. # Stackwalk Implementation Details Further low-level details of the stack walk implementation are currently outside the scope of this document. If you have knowledge of these and would care to share that knowledge please feel free to update this document.
-1
dotnet/runtime
66,022
Add Android 32 to RID graph
Supports Android 12L, which will be stable most likely by summer or earlier.
steveisok
2022-03-01T19:37:08Z
2022-03-11T21:09:58Z
a883caa0803778084167b978281c34db8e753246
36a435cf12309f5119c2f5ce103af7fa28150d72
Add Android 32 to RID graph. Supports Android 12L, which will be stable most likely by summer or earlier.
./src/libraries/System.Text.Encodings.Web/src/Polyfills/System.Text.Rune.netstandard20.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text.Encodings.Web; using System.Diagnostics.CodeAnalysis; // Contains a polyfill implementation of System.Text.Rune that works on netstandard2.0. // Implementation copied from: // https://github.com/dotnet/runtime/blob/177d6f1a0bfdc853ae9ffeef4be99ff984c4f5dd/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs namespace System.Text { internal readonly struct Rune : IEquatable<Rune> { private const int MaxUtf16CharsPerRune = 2; // supplementary plane code points are encoded as 2 UTF-16 code units private const char HighSurrogateStart = '\ud800'; private const char LowSurrogateStart = '\udc00'; private const int HighSurrogateRange = 0x3FF; private readonly uint _value; /// <summary> /// Creates a <see cref="Rune"/> from the provided Unicode scalar value. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="value"/> does not represent a value Unicode scalar value. /// </exception> public Rune(uint value) { if (!UnicodeUtility.IsValidUnicodeScalar(value)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } _value = value; } /// <summary> /// Creates a <see cref="Rune"/> from the provided Unicode scalar value. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="value"/> does not represent a value Unicode scalar value. /// </exception> public Rune(int value) : this((uint)value) { } // non-validating ctor private Rune(uint scalarValue, bool unused) { UnicodeDebug.AssertIsValidScalar(scalarValue); _value = scalarValue; } /// <summary> /// Returns true if and only if this scalar value is ASCII ([ U+0000..U+007F ]) /// and therefore representable by a single UTF-8 code unit. /// </summary> public bool IsAscii => UnicodeUtility.IsAsciiCodePoint(_value); /// <summary> /// Returns true if and only if this scalar value is within the BMP ([ U+0000..U+FFFF ]) /// and therefore representable by a single UTF-16 code unit. /// </summary> public bool IsBmp => UnicodeUtility.IsBmpCodePoint(_value); public static bool operator ==(Rune left, Rune right) => left._value == right._value; public static bool operator !=(Rune left, Rune right) => left._value != right._value; public static bool IsControl(Rune value) { // Per the Unicode stability policy, the set of control characters // is forever fixed at [ U+0000..U+001F ], [ U+007F..U+009F ]. No // characters will ever be added to or removed from the "control characters" // group. See https://www.unicode.org/policies/stability_policy.html. // Logic below depends on Rune.Value never being -1 (since Rune is a validating type) // 00..1F (+1) => 01..20 (&~80) => 01..20 // 7F..9F (+1) => 80..A0 (&~80) => 00..20 return ((value._value + 1) & ~0x80u) <= 0x20u; } /// <summary> /// A <see cref="Rune"/> instance that represents the Unicode replacement character U+FFFD. /// </summary> public static Rune ReplacementChar => UnsafeCreate(UnicodeUtility.ReplacementChar); /// <summary> /// Returns the length in code units (<see cref="char"/>) of the /// UTF-16 sequence required to represent this scalar value. /// </summary> /// <remarks> /// The return value will be 1 or 2. /// </remarks> public int Utf16SequenceLength { get { int codeUnitCount = UnicodeUtility.GetUtf16SequenceLength(_value); Debug.Assert(codeUnitCount > 0 && codeUnitCount <= MaxUtf16CharsPerRune); return codeUnitCount; } } /// <summary> /// Returns the Unicode scalar value as an integer. /// </summary> public int Value => (int)_value; /// <summary> /// Decodes the <see cref="Rune"/> at the beginning of the provided UTF-16 source buffer. /// </summary> /// <returns> /// <para> /// If the source buffer begins with a valid UTF-16 encoded scalar value, returns <see cref="OperationStatus.Done"/>, /// and outs via <paramref name="result"/> the decoded <see cref="Rune"/> and via <paramref name="charsConsumed"/> the /// number of <see langword="char"/>s used in the input buffer to encode the <see cref="Rune"/>. /// </para> /// <para> /// If the source buffer is empty or contains only a standalone UTF-16 high surrogate character, returns <see cref="OperationStatus.NeedMoreData"/>, /// and outs via <paramref name="result"/> <see cref="ReplacementChar"/> and via <paramref name="charsConsumed"/> the length of the input buffer. /// </para> /// <para> /// If the source buffer begins with an ill-formed UTF-16 encoded scalar value, returns <see cref="OperationStatus.InvalidData"/>, /// and outs via <paramref name="result"/> <see cref="ReplacementChar"/> and via <paramref name="charsConsumed"/> the number of /// <see langword="char"/>s used in the input buffer to encode the ill-formed sequence. /// </para> /// </returns> /// <remarks> /// The general calling convention is to call this method in a loop, slicing the <paramref name="source"/> buffer by /// <paramref name="charsConsumed"/> elements on each iteration of the loop. On each iteration of the loop <paramref name="result"/> /// will contain the real scalar value if successfully decoded, or it will contain <see cref="ReplacementChar"/> if /// the data could not be successfully decoded. This pattern provides convenient automatic U+FFFD substitution of /// invalid sequences while iterating through the loop. /// </remarks> public static OperationStatus DecodeFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed) { if (!source.IsEmpty) { // First, check for the common case of a BMP scalar value. // If this is correct, return immediately. char firstChar = source[0]; if (TryCreate(firstChar, out result)) { charsConsumed = 1; return OperationStatus.Done; } // First thing we saw was a UTF-16 surrogate code point. // Let's optimistically assume for now it's a high surrogate and hope // that combining it with the next char yields useful results. if (1 < (uint)source.Length) { char secondChar = source[1]; if (TryCreate(firstChar, secondChar, out result)) { // Success! Formed a supplementary scalar value. charsConsumed = 2; return OperationStatus.Done; } else { // Either the first character was a low surrogate, or the second // character was not a low surrogate. This is an error. goto InvalidData; } } else if (!char.IsHighSurrogate(firstChar)) { // Quick check to make sure we're not going to report NeedMoreData for // a single-element buffer where the data is a standalone low surrogate // character. Since no additional data will ever make this valid, we'll // report an error immediately. goto InvalidData; } } // If we got to this point, the input buffer was empty, or the buffer // was a single element in length and that element was a high surrogate char. charsConsumed = source.Length; result = ReplacementChar; return OperationStatus.NeedMoreData; InvalidData: charsConsumed = 1; // maximal invalid subsequence for UTF-16 is always a single code unit in length result = ReplacementChar; return OperationStatus.InvalidData; } /// <summary> /// Decodes the <see cref="Rune"/> at the beginning of the provided UTF-8 source buffer. /// </summary> /// <returns> /// <para> /// If the source buffer begins with a valid UTF-8 encoded scalar value, returns <see cref="OperationStatus.Done"/>, /// and outs via <paramref name="result"/> the decoded <see cref="Rune"/> and via <paramref name="bytesConsumed"/> the /// number of <see langword="byte"/>s used in the input buffer to encode the <see cref="Rune"/>. /// </para> /// <para> /// If the source buffer is empty or contains only a partial UTF-8 subsequence, returns <see cref="OperationStatus.NeedMoreData"/>, /// and outs via <paramref name="result"/> <see cref="ReplacementChar"/> and via <paramref name="bytesConsumed"/> the length of the input buffer. /// </para> /// <para> /// If the source buffer begins with an ill-formed UTF-8 encoded scalar value, returns <see cref="OperationStatus.InvalidData"/>, /// and outs via <paramref name="result"/> <see cref="ReplacementChar"/> and via <paramref name="bytesConsumed"/> the number of /// <see langword="char"/>s used in the input buffer to encode the ill-formed sequence. /// </para> /// </returns> /// <remarks> /// The general calling convention is to call this method in a loop, slicing the <paramref name="source"/> buffer by /// <paramref name="bytesConsumed"/> elements on each iteration of the loop. On each iteration of the loop <paramref name="result"/> /// will contain the real scalar value if successfully decoded, or it will contain <see cref="ReplacementChar"/> if /// the data could not be successfully decoded. This pattern provides convenient automatic U+FFFD substitution of /// invalid sequences while iterating through the loop. /// </remarks> public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> source, out Rune result, out int bytesConsumed) { // This method follows the Unicode Standard's recommendation for detecting // the maximal subpart of an ill-formed subsequence. See The Unicode Standard, // Ch. 3.9 for more details. In summary, when reporting an invalid subsequence, // it tries to consume as many code units as possible as long as those code // units constitute the beginning of a longer well-formed subsequence per Table 3-7. int index = 0; // Try reading input[0]. if ((uint)index >= (uint)source.Length) { goto NeedsMoreData; } uint tempValue = source[index]; if (!UnicodeUtility.IsAsciiCodePoint(tempValue)) { goto NotAscii; } Finish: bytesConsumed = index + 1; Debug.Assert(1 <= bytesConsumed && bytesConsumed <= 4); // Valid subsequences are always length [1..4] result = UnsafeCreate(tempValue); return OperationStatus.Done; NotAscii: // Per Table 3-7, the beginning of a multibyte sequence must be a code unit in // the range [C2..F4]. If it's outside of that range, it's either a standalone // continuation byte, or it's an overlong two-byte sequence, or it's an out-of-range // four-byte sequence. if (!UnicodeUtility.IsInRangeInclusive(tempValue, 0xC2, 0xF4)) { goto FirstByteInvalid; } tempValue = (tempValue - 0xC2) << 6; // Try reading input[1]. index++; if ((uint)index >= (uint)source.Length) { goto NeedsMoreData; } // Continuation bytes are of the form [10xxxxxx], which means that their two's // complement representation is in the range [-65..-128]. This allows us to // perform a single comparison to see if a byte is a continuation byte. int thisByteSignExtended = (sbyte)source[index]; if (thisByteSignExtended >= -64) { goto Invalid; } tempValue += (uint)thisByteSignExtended; tempValue += 0x80; // remove the continuation byte marker tempValue += (0xC2 - 0xC0) << 6; // remove the leading byte marker if (tempValue < 0x0800) { Debug.Assert(UnicodeUtility.IsInRangeInclusive(tempValue, 0x0080, 0x07FF)); goto Finish; // this is a valid 2-byte sequence } // This appears to be a 3- or 4-byte sequence. Since per Table 3-7 we now have // enough information (from just two code units) to detect overlong or surrogate // sequences, we need to perform these checks now. if (!UnicodeUtility.IsInRangeInclusive(tempValue, ((0xE0 - 0xC0) << 6) + (0xA0 - 0x80), ((0xF4 - 0xC0) << 6) + (0x8F - 0x80))) { // The first two bytes were not in the range [[E0 A0]..[F4 8F]]. // This is an overlong 3-byte sequence or an out-of-range 4-byte sequence. goto Invalid; } if (UnicodeUtility.IsInRangeInclusive(tempValue, ((0xED - 0xC0) << 6) + (0xA0 - 0x80), ((0xED - 0xC0) << 6) + (0xBF - 0x80))) { // This is a UTF-16 surrogate code point, which is invalid in UTF-8. goto Invalid; } if (UnicodeUtility.IsInRangeInclusive(tempValue, ((0xF0 - 0xC0) << 6) + (0x80 - 0x80), ((0xF0 - 0xC0) << 6) + (0x8F - 0x80))) { // This is an overlong 4-byte sequence. goto Invalid; } // The first two bytes were just fine. We don't need to perform any other checks // on the remaining bytes other than to see that they're valid continuation bytes. // Try reading input[2]. index++; if ((uint)index >= (uint)source.Length) { goto NeedsMoreData; } thisByteSignExtended = (sbyte)source[index]; if (thisByteSignExtended >= -64) { goto Invalid; // this byte is not a UTF-8 continuation byte } tempValue <<= 6; tempValue += (uint)thisByteSignExtended; tempValue += 0x80; // remove the continuation byte marker tempValue -= (0xE0 - 0xC0) << 12; // remove the leading byte marker if (tempValue <= 0xFFFF) { Debug.Assert(UnicodeUtility.IsInRangeInclusive(tempValue, 0x0800, 0xFFFF)); goto Finish; // this is a valid 3-byte sequence } // Try reading input[3]. index++; if ((uint)index >= (uint)source.Length) { goto NeedsMoreData; } thisByteSignExtended = (sbyte)source[index]; if (thisByteSignExtended >= -64) { goto Invalid; // this byte is not a UTF-8 continuation byte } tempValue <<= 6; tempValue += (uint)thisByteSignExtended; tempValue += 0x80; // remove the continuation byte marker tempValue -= (0xF0 - 0xE0) << 18; // remove the leading byte marker UnicodeDebug.AssertIsValidSupplementaryPlaneScalar(tempValue); goto Finish; // this is a valid 4-byte sequence FirstByteInvalid: index = 1; // Invalid subsequences are always at least length 1. Invalid: Debug.Assert(1 <= index && index <= 3); // Invalid subsequences are always length 1..3 bytesConsumed = index; result = ReplacementChar; return OperationStatus.InvalidData; NeedsMoreData: Debug.Assert(0 <= index && index <= 3); // Incomplete subsequences are always length 0..3 bytesConsumed = index; result = ReplacementChar; return OperationStatus.NeedMoreData; } public override bool Equals([NotNullWhen(true)] object? obj) => (obj is Rune other) && Equals(other); public bool Equals(Rune other) => this == other; public override int GetHashCode() => Value; /// <summary> /// Attempts to create a <see cref="Rune"/> from the provided input value. /// </summary> public static bool TryCreate(char ch, out Rune result) { uint extendedValue = ch; if (!UnicodeUtility.IsSurrogateCodePoint(extendedValue)) { result = UnsafeCreate(extendedValue); return true; } else { result = default; return false; } } /// <summary> /// Attempts to create a <see cref="Rune"/> from the provided UTF-16 surrogate pair. /// Returns <see langword="false"/> if the input values don't represent a well-formed UTF-16surrogate pair. /// </summary> public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result) { // First, extend both to 32 bits, then calculate the offset of // each candidate surrogate char from the start of its range. uint highSurrogateOffset = (uint)highSurrogate - HighSurrogateStart; uint lowSurrogateOffset = (uint)lowSurrogate - LowSurrogateStart; // This is a single comparison which allows us to check both for validity at once since // both the high surrogate range and the low surrogate range are the same length. // If the comparison fails, we call to a helper method to throw the correct exception message. if ((highSurrogateOffset | lowSurrogateOffset) <= HighSurrogateRange) { // The 0x40u << 10 below is to account for uuuuu = wwww + 1 in the surrogate encoding. result = UnsafeCreate((highSurrogateOffset << 10) + ((uint)lowSurrogate - LowSurrogateStart) + (0x40u << 10)); return true; } else { // Didn't have a high surrogate followed by a low surrogate. result = default; return false; } } /// <summary> /// Encodes this <see cref="Rune"/> to a UTF-16 destination buffer. /// </summary> /// <param name="destination">The buffer to which to write this value as UTF-16.</param> /// <param name="charsWritten"> /// The number of <see cref="char"/>s written to <paramref name="destination"/>, /// or 0 if the destination buffer is not large enough to contain the output.</param> /// <returns>True if the value was written to the buffer; otherwise, false.</returns> public bool TryEncodeToUtf16(Span<char> destination, out int charsWritten) { if (destination.Length >= 1) { if (IsBmp) { destination[0] = (char)_value; charsWritten = 1; return true; } else if (destination.Length >= 2) { UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out destination[0], out destination[1]); charsWritten = 2; return true; } } // Destination buffer not large enough charsWritten = default; return false; } /// <summary> /// Encodes this <see cref="Rune"/> to a destination buffer as UTF-8 bytes. /// </summary> /// <param name="destination">The buffer to which to write this value as UTF-8.</param> /// <param name="bytesWritten"> /// The number of <see cref="byte"/>s written to <paramref name="destination"/>, /// or 0 if the destination buffer is not large enough to contain the output.</param> /// <returns>True if the value was written to the buffer; otherwise, false.</returns> public bool TryEncodeToUtf8(Span<byte> destination, out int bytesWritten) { // The bit patterns below come from the Unicode Standard, Table 3-6. if (destination.Length >= 1) { if (IsAscii) { destination[0] = (byte)_value; bytesWritten = 1; return true; } if (destination.Length >= 2) { if (_value <= 0x7FFu) { // Scalar 00000yyy yyxxxxxx -> bytes [ 110yyyyy 10xxxxxx ] destination[0] = (byte)((_value + (0b110u << 11)) >> 6); destination[1] = (byte)((_value & 0x3Fu) + 0x80u); bytesWritten = 2; return true; } if (destination.Length >= 3) { if (_value <= 0xFFFFu) { // Scalar zzzzyyyy yyxxxxxx -> bytes [ 1110zzzz 10yyyyyy 10xxxxxx ] destination[0] = (byte)((_value + (0b1110 << 16)) >> 12); destination[1] = (byte)(((_value & (0x3Fu << 6)) >> 6) + 0x80u); destination[2] = (byte)((_value & 0x3Fu) + 0x80u); bytesWritten = 3; return true; } if (destination.Length >= 4) { // Scalar 000uuuuu zzzzyyyy yyxxxxxx -> bytes [ 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx ] destination[0] = (byte)((_value + (0b11110 << 21)) >> 18); destination[1] = (byte)(((_value & (0x3Fu << 12)) >> 12) + 0x80u); destination[2] = (byte)(((_value & (0x3Fu << 6)) >> 6) + 0x80u); destination[3] = (byte)((_value & 0x3Fu) + 0x80u); bytesWritten = 4; return true; } } } } // Destination buffer not large enough bytesWritten = default; return false; } /// <summary> /// Creates a <see cref="Rune"/> without performing validation on the input. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Rune UnsafeCreate(uint scalarValue) => new Rune(scalarValue, false); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text.Encodings.Web; using System.Diagnostics.CodeAnalysis; // Contains a polyfill implementation of System.Text.Rune that works on netstandard2.0. // Implementation copied from: // https://github.com/dotnet/runtime/blob/177d6f1a0bfdc853ae9ffeef4be99ff984c4f5dd/src/libraries/System.Private.CoreLib/src/System/Text/Rune.cs namespace System.Text { internal readonly struct Rune : IEquatable<Rune> { private const int MaxUtf16CharsPerRune = 2; // supplementary plane code points are encoded as 2 UTF-16 code units private const char HighSurrogateStart = '\ud800'; private const char LowSurrogateStart = '\udc00'; private const int HighSurrogateRange = 0x3FF; private readonly uint _value; /// <summary> /// Creates a <see cref="Rune"/> from the provided Unicode scalar value. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="value"/> does not represent a value Unicode scalar value. /// </exception> public Rune(uint value) { if (!UnicodeUtility.IsValidUnicodeScalar(value)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } _value = value; } /// <summary> /// Creates a <see cref="Rune"/> from the provided Unicode scalar value. /// </summary> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="value"/> does not represent a value Unicode scalar value. /// </exception> public Rune(int value) : this((uint)value) { } // non-validating ctor private Rune(uint scalarValue, bool unused) { UnicodeDebug.AssertIsValidScalar(scalarValue); _value = scalarValue; } /// <summary> /// Returns true if and only if this scalar value is ASCII ([ U+0000..U+007F ]) /// and therefore representable by a single UTF-8 code unit. /// </summary> public bool IsAscii => UnicodeUtility.IsAsciiCodePoint(_value); /// <summary> /// Returns true if and only if this scalar value is within the BMP ([ U+0000..U+FFFF ]) /// and therefore representable by a single UTF-16 code unit. /// </summary> public bool IsBmp => UnicodeUtility.IsBmpCodePoint(_value); public static bool operator ==(Rune left, Rune right) => left._value == right._value; public static bool operator !=(Rune left, Rune right) => left._value != right._value; public static bool IsControl(Rune value) { // Per the Unicode stability policy, the set of control characters // is forever fixed at [ U+0000..U+001F ], [ U+007F..U+009F ]. No // characters will ever be added to or removed from the "control characters" // group. See https://www.unicode.org/policies/stability_policy.html. // Logic below depends on Rune.Value never being -1 (since Rune is a validating type) // 00..1F (+1) => 01..20 (&~80) => 01..20 // 7F..9F (+1) => 80..A0 (&~80) => 00..20 return ((value._value + 1) & ~0x80u) <= 0x20u; } /// <summary> /// A <see cref="Rune"/> instance that represents the Unicode replacement character U+FFFD. /// </summary> public static Rune ReplacementChar => UnsafeCreate(UnicodeUtility.ReplacementChar); /// <summary> /// Returns the length in code units (<see cref="char"/>) of the /// UTF-16 sequence required to represent this scalar value. /// </summary> /// <remarks> /// The return value will be 1 or 2. /// </remarks> public int Utf16SequenceLength { get { int codeUnitCount = UnicodeUtility.GetUtf16SequenceLength(_value); Debug.Assert(codeUnitCount > 0 && codeUnitCount <= MaxUtf16CharsPerRune); return codeUnitCount; } } /// <summary> /// Returns the Unicode scalar value as an integer. /// </summary> public int Value => (int)_value; /// <summary> /// Decodes the <see cref="Rune"/> at the beginning of the provided UTF-16 source buffer. /// </summary> /// <returns> /// <para> /// If the source buffer begins with a valid UTF-16 encoded scalar value, returns <see cref="OperationStatus.Done"/>, /// and outs via <paramref name="result"/> the decoded <see cref="Rune"/> and via <paramref name="charsConsumed"/> the /// number of <see langword="char"/>s used in the input buffer to encode the <see cref="Rune"/>. /// </para> /// <para> /// If the source buffer is empty or contains only a standalone UTF-16 high surrogate character, returns <see cref="OperationStatus.NeedMoreData"/>, /// and outs via <paramref name="result"/> <see cref="ReplacementChar"/> and via <paramref name="charsConsumed"/> the length of the input buffer. /// </para> /// <para> /// If the source buffer begins with an ill-formed UTF-16 encoded scalar value, returns <see cref="OperationStatus.InvalidData"/>, /// and outs via <paramref name="result"/> <see cref="ReplacementChar"/> and via <paramref name="charsConsumed"/> the number of /// <see langword="char"/>s used in the input buffer to encode the ill-formed sequence. /// </para> /// </returns> /// <remarks> /// The general calling convention is to call this method in a loop, slicing the <paramref name="source"/> buffer by /// <paramref name="charsConsumed"/> elements on each iteration of the loop. On each iteration of the loop <paramref name="result"/> /// will contain the real scalar value if successfully decoded, or it will contain <see cref="ReplacementChar"/> if /// the data could not be successfully decoded. This pattern provides convenient automatic U+FFFD substitution of /// invalid sequences while iterating through the loop. /// </remarks> public static OperationStatus DecodeFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed) { if (!source.IsEmpty) { // First, check for the common case of a BMP scalar value. // If this is correct, return immediately. char firstChar = source[0]; if (TryCreate(firstChar, out result)) { charsConsumed = 1; return OperationStatus.Done; } // First thing we saw was a UTF-16 surrogate code point. // Let's optimistically assume for now it's a high surrogate and hope // that combining it with the next char yields useful results. if (1 < (uint)source.Length) { char secondChar = source[1]; if (TryCreate(firstChar, secondChar, out result)) { // Success! Formed a supplementary scalar value. charsConsumed = 2; return OperationStatus.Done; } else { // Either the first character was a low surrogate, or the second // character was not a low surrogate. This is an error. goto InvalidData; } } else if (!char.IsHighSurrogate(firstChar)) { // Quick check to make sure we're not going to report NeedMoreData for // a single-element buffer where the data is a standalone low surrogate // character. Since no additional data will ever make this valid, we'll // report an error immediately. goto InvalidData; } } // If we got to this point, the input buffer was empty, or the buffer // was a single element in length and that element was a high surrogate char. charsConsumed = source.Length; result = ReplacementChar; return OperationStatus.NeedMoreData; InvalidData: charsConsumed = 1; // maximal invalid subsequence for UTF-16 is always a single code unit in length result = ReplacementChar; return OperationStatus.InvalidData; } /// <summary> /// Decodes the <see cref="Rune"/> at the beginning of the provided UTF-8 source buffer. /// </summary> /// <returns> /// <para> /// If the source buffer begins with a valid UTF-8 encoded scalar value, returns <see cref="OperationStatus.Done"/>, /// and outs via <paramref name="result"/> the decoded <see cref="Rune"/> and via <paramref name="bytesConsumed"/> the /// number of <see langword="byte"/>s used in the input buffer to encode the <see cref="Rune"/>. /// </para> /// <para> /// If the source buffer is empty or contains only a partial UTF-8 subsequence, returns <see cref="OperationStatus.NeedMoreData"/>, /// and outs via <paramref name="result"/> <see cref="ReplacementChar"/> and via <paramref name="bytesConsumed"/> the length of the input buffer. /// </para> /// <para> /// If the source buffer begins with an ill-formed UTF-8 encoded scalar value, returns <see cref="OperationStatus.InvalidData"/>, /// and outs via <paramref name="result"/> <see cref="ReplacementChar"/> and via <paramref name="bytesConsumed"/> the number of /// <see langword="char"/>s used in the input buffer to encode the ill-formed sequence. /// </para> /// </returns> /// <remarks> /// The general calling convention is to call this method in a loop, slicing the <paramref name="source"/> buffer by /// <paramref name="bytesConsumed"/> elements on each iteration of the loop. On each iteration of the loop <paramref name="result"/> /// will contain the real scalar value if successfully decoded, or it will contain <see cref="ReplacementChar"/> if /// the data could not be successfully decoded. This pattern provides convenient automatic U+FFFD substitution of /// invalid sequences while iterating through the loop. /// </remarks> public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> source, out Rune result, out int bytesConsumed) { // This method follows the Unicode Standard's recommendation for detecting // the maximal subpart of an ill-formed subsequence. See The Unicode Standard, // Ch. 3.9 for more details. In summary, when reporting an invalid subsequence, // it tries to consume as many code units as possible as long as those code // units constitute the beginning of a longer well-formed subsequence per Table 3-7. int index = 0; // Try reading input[0]. if ((uint)index >= (uint)source.Length) { goto NeedsMoreData; } uint tempValue = source[index]; if (!UnicodeUtility.IsAsciiCodePoint(tempValue)) { goto NotAscii; } Finish: bytesConsumed = index + 1; Debug.Assert(1 <= bytesConsumed && bytesConsumed <= 4); // Valid subsequences are always length [1..4] result = UnsafeCreate(tempValue); return OperationStatus.Done; NotAscii: // Per Table 3-7, the beginning of a multibyte sequence must be a code unit in // the range [C2..F4]. If it's outside of that range, it's either a standalone // continuation byte, or it's an overlong two-byte sequence, or it's an out-of-range // four-byte sequence. if (!UnicodeUtility.IsInRangeInclusive(tempValue, 0xC2, 0xF4)) { goto FirstByteInvalid; } tempValue = (tempValue - 0xC2) << 6; // Try reading input[1]. index++; if ((uint)index >= (uint)source.Length) { goto NeedsMoreData; } // Continuation bytes are of the form [10xxxxxx], which means that their two's // complement representation is in the range [-65..-128]. This allows us to // perform a single comparison to see if a byte is a continuation byte. int thisByteSignExtended = (sbyte)source[index]; if (thisByteSignExtended >= -64) { goto Invalid; } tempValue += (uint)thisByteSignExtended; tempValue += 0x80; // remove the continuation byte marker tempValue += (0xC2 - 0xC0) << 6; // remove the leading byte marker if (tempValue < 0x0800) { Debug.Assert(UnicodeUtility.IsInRangeInclusive(tempValue, 0x0080, 0x07FF)); goto Finish; // this is a valid 2-byte sequence } // This appears to be a 3- or 4-byte sequence. Since per Table 3-7 we now have // enough information (from just two code units) to detect overlong or surrogate // sequences, we need to perform these checks now. if (!UnicodeUtility.IsInRangeInclusive(tempValue, ((0xE0 - 0xC0) << 6) + (0xA0 - 0x80), ((0xF4 - 0xC0) << 6) + (0x8F - 0x80))) { // The first two bytes were not in the range [[E0 A0]..[F4 8F]]. // This is an overlong 3-byte sequence or an out-of-range 4-byte sequence. goto Invalid; } if (UnicodeUtility.IsInRangeInclusive(tempValue, ((0xED - 0xC0) << 6) + (0xA0 - 0x80), ((0xED - 0xC0) << 6) + (0xBF - 0x80))) { // This is a UTF-16 surrogate code point, which is invalid in UTF-8. goto Invalid; } if (UnicodeUtility.IsInRangeInclusive(tempValue, ((0xF0 - 0xC0) << 6) + (0x80 - 0x80), ((0xF0 - 0xC0) << 6) + (0x8F - 0x80))) { // This is an overlong 4-byte sequence. goto Invalid; } // The first two bytes were just fine. We don't need to perform any other checks // on the remaining bytes other than to see that they're valid continuation bytes. // Try reading input[2]. index++; if ((uint)index >= (uint)source.Length) { goto NeedsMoreData; } thisByteSignExtended = (sbyte)source[index]; if (thisByteSignExtended >= -64) { goto Invalid; // this byte is not a UTF-8 continuation byte } tempValue <<= 6; tempValue += (uint)thisByteSignExtended; tempValue += 0x80; // remove the continuation byte marker tempValue -= (0xE0 - 0xC0) << 12; // remove the leading byte marker if (tempValue <= 0xFFFF) { Debug.Assert(UnicodeUtility.IsInRangeInclusive(tempValue, 0x0800, 0xFFFF)); goto Finish; // this is a valid 3-byte sequence } // Try reading input[3]. index++; if ((uint)index >= (uint)source.Length) { goto NeedsMoreData; } thisByteSignExtended = (sbyte)source[index]; if (thisByteSignExtended >= -64) { goto Invalid; // this byte is not a UTF-8 continuation byte } tempValue <<= 6; tempValue += (uint)thisByteSignExtended; tempValue += 0x80; // remove the continuation byte marker tempValue -= (0xF0 - 0xE0) << 18; // remove the leading byte marker UnicodeDebug.AssertIsValidSupplementaryPlaneScalar(tempValue); goto Finish; // this is a valid 4-byte sequence FirstByteInvalid: index = 1; // Invalid subsequences are always at least length 1. Invalid: Debug.Assert(1 <= index && index <= 3); // Invalid subsequences are always length 1..3 bytesConsumed = index; result = ReplacementChar; return OperationStatus.InvalidData; NeedsMoreData: Debug.Assert(0 <= index && index <= 3); // Incomplete subsequences are always length 0..3 bytesConsumed = index; result = ReplacementChar; return OperationStatus.NeedMoreData; } public override bool Equals([NotNullWhen(true)] object? obj) => (obj is Rune other) && Equals(other); public bool Equals(Rune other) => this == other; public override int GetHashCode() => Value; /// <summary> /// Attempts to create a <see cref="Rune"/> from the provided input value. /// </summary> public static bool TryCreate(char ch, out Rune result) { uint extendedValue = ch; if (!UnicodeUtility.IsSurrogateCodePoint(extendedValue)) { result = UnsafeCreate(extendedValue); return true; } else { result = default; return false; } } /// <summary> /// Attempts to create a <see cref="Rune"/> from the provided UTF-16 surrogate pair. /// Returns <see langword="false"/> if the input values don't represent a well-formed UTF-16surrogate pair. /// </summary> public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result) { // First, extend both to 32 bits, then calculate the offset of // each candidate surrogate char from the start of its range. uint highSurrogateOffset = (uint)highSurrogate - HighSurrogateStart; uint lowSurrogateOffset = (uint)lowSurrogate - LowSurrogateStart; // This is a single comparison which allows us to check both for validity at once since // both the high surrogate range and the low surrogate range are the same length. // If the comparison fails, we call to a helper method to throw the correct exception message. if ((highSurrogateOffset | lowSurrogateOffset) <= HighSurrogateRange) { // The 0x40u << 10 below is to account for uuuuu = wwww + 1 in the surrogate encoding. result = UnsafeCreate((highSurrogateOffset << 10) + ((uint)lowSurrogate - LowSurrogateStart) + (0x40u << 10)); return true; } else { // Didn't have a high surrogate followed by a low surrogate. result = default; return false; } } /// <summary> /// Encodes this <see cref="Rune"/> to a UTF-16 destination buffer. /// </summary> /// <param name="destination">The buffer to which to write this value as UTF-16.</param> /// <param name="charsWritten"> /// The number of <see cref="char"/>s written to <paramref name="destination"/>, /// or 0 if the destination buffer is not large enough to contain the output.</param> /// <returns>True if the value was written to the buffer; otherwise, false.</returns> public bool TryEncodeToUtf16(Span<char> destination, out int charsWritten) { if (destination.Length >= 1) { if (IsBmp) { destination[0] = (char)_value; charsWritten = 1; return true; } else if (destination.Length >= 2) { UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out destination[0], out destination[1]); charsWritten = 2; return true; } } // Destination buffer not large enough charsWritten = default; return false; } /// <summary> /// Encodes this <see cref="Rune"/> to a destination buffer as UTF-8 bytes. /// </summary> /// <param name="destination">The buffer to which to write this value as UTF-8.</param> /// <param name="bytesWritten"> /// The number of <see cref="byte"/>s written to <paramref name="destination"/>, /// or 0 if the destination buffer is not large enough to contain the output.</param> /// <returns>True if the value was written to the buffer; otherwise, false.</returns> public bool TryEncodeToUtf8(Span<byte> destination, out int bytesWritten) { // The bit patterns below come from the Unicode Standard, Table 3-6. if (destination.Length >= 1) { if (IsAscii) { destination[0] = (byte)_value; bytesWritten = 1; return true; } if (destination.Length >= 2) { if (_value <= 0x7FFu) { // Scalar 00000yyy yyxxxxxx -> bytes [ 110yyyyy 10xxxxxx ] destination[0] = (byte)((_value + (0b110u << 11)) >> 6); destination[1] = (byte)((_value & 0x3Fu) + 0x80u); bytesWritten = 2; return true; } if (destination.Length >= 3) { if (_value <= 0xFFFFu) { // Scalar zzzzyyyy yyxxxxxx -> bytes [ 1110zzzz 10yyyyyy 10xxxxxx ] destination[0] = (byte)((_value + (0b1110 << 16)) >> 12); destination[1] = (byte)(((_value & (0x3Fu << 6)) >> 6) + 0x80u); destination[2] = (byte)((_value & 0x3Fu) + 0x80u); bytesWritten = 3; return true; } if (destination.Length >= 4) { // Scalar 000uuuuu zzzzyyyy yyxxxxxx -> bytes [ 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx ] destination[0] = (byte)((_value + (0b11110 << 21)) >> 18); destination[1] = (byte)(((_value & (0x3Fu << 12)) >> 12) + 0x80u); destination[2] = (byte)(((_value & (0x3Fu << 6)) >> 6) + 0x80u); destination[3] = (byte)((_value & 0x3Fu) + 0x80u); bytesWritten = 4; return true; } } } } // Destination buffer not large enough bytesWritten = default; return false; } /// <summary> /// Creates a <see cref="Rune"/> without performing validation on the input. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Rune UnsafeCreate(uint scalarValue) => new Rune(scalarValue, false); } }
-1
dotnet/runtime
66,022
Add Android 32 to RID graph
Supports Android 12L, which will be stable most likely by summer or earlier.
steveisok
2022-03-01T19:37:08Z
2022-03-11T21:09:58Z
a883caa0803778084167b978281c34db8e753246
36a435cf12309f5119c2f5ce103af7fa28150d72
Add Android 32 to RID graph. Supports Android 12L, which will be stable most likely by summer or earlier.
./src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; internal abstract class CompiledAction : Action { internal abstract void Compile(Compiler compiler); internal virtual bool CompileAttribute(Compiler compiler) { return false; } public void CompileAttributes(Compiler compiler) { NavigatorInput input = compiler.Input; string element = input.LocalName; if (input.MoveToFirstAttribute()) { do { if (input.NamespaceURI.Length != 0) continue; try { if (CompileAttribute(compiler) == false) { throw XsltException.Create(SR.Xslt_InvalidAttribute, input.LocalName, element); } } catch { if (!compiler.ForwardCompatibility) { throw; } else { // In ForwardCompatibility mode we ignoreing all unknown or incorrect attributes // If it's mandatory attribute we'll notice it absence later. } } } while (input.MoveToNextAttribute()); input.ToParent(); } } // For perf reason we precalculating AVTs at compile time. // If we can do this we set original AVT to null internal static string? PrecalculateAvt(ref Avt? avt) { string? result = null; if (avt != null && avt.IsConstant) { result = avt.Evaluate(null, null); avt = null; } return result; } public void CheckEmpty(Compiler compiler) { // Really EMPTY means no content at all, but the sake of compatibility with MSXML we allow whitespace string elementName = compiler.Input.Name; if (compiler.Recurse()) { do { // Note: <![CDATA[ ]]> will be reported as XPathNodeType.Text XPathNodeType nodeType = compiler.Input.NodeType; if ( nodeType != XPathNodeType.Whitespace && nodeType != XPathNodeType.Comment && nodeType != XPathNodeType.ProcessingInstruction ) { throw XsltException.Create(SR.Xslt_NotEmptyContents, elementName); } } while (compiler.Advance()); compiler.ToParent(); } } public void CheckRequiredAttribute(Compiler compiler, object? attrValue, string attrName) { CheckRequiredAttribute(compiler, attrValue != null, attrName); } public void CheckRequiredAttribute(Compiler compiler, bool attr, string attrName) { if (!attr) { throw XsltException.Create(SR.Xslt_MissingAttribute, attrName); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Xml.Xsl.XsltOld { using System; using System.Diagnostics; using System.Xml; using System.Xml.XPath; internal abstract class CompiledAction : Action { internal abstract void Compile(Compiler compiler); internal virtual bool CompileAttribute(Compiler compiler) { return false; } public void CompileAttributes(Compiler compiler) { NavigatorInput input = compiler.Input; string element = input.LocalName; if (input.MoveToFirstAttribute()) { do { if (input.NamespaceURI.Length != 0) continue; try { if (CompileAttribute(compiler) == false) { throw XsltException.Create(SR.Xslt_InvalidAttribute, input.LocalName, element); } } catch { if (!compiler.ForwardCompatibility) { throw; } else { // In ForwardCompatibility mode we ignoreing all unknown or incorrect attributes // If it's mandatory attribute we'll notice it absence later. } } } while (input.MoveToNextAttribute()); input.ToParent(); } } // For perf reason we precalculating AVTs at compile time. // If we can do this we set original AVT to null internal static string? PrecalculateAvt(ref Avt? avt) { string? result = null; if (avt != null && avt.IsConstant) { result = avt.Evaluate(null, null); avt = null; } return result; } public void CheckEmpty(Compiler compiler) { // Really EMPTY means no content at all, but the sake of compatibility with MSXML we allow whitespace string elementName = compiler.Input.Name; if (compiler.Recurse()) { do { // Note: <![CDATA[ ]]> will be reported as XPathNodeType.Text XPathNodeType nodeType = compiler.Input.NodeType; if ( nodeType != XPathNodeType.Whitespace && nodeType != XPathNodeType.Comment && nodeType != XPathNodeType.ProcessingInstruction ) { throw XsltException.Create(SR.Xslt_NotEmptyContents, elementName); } } while (compiler.Advance()); compiler.ToParent(); } } public void CheckRequiredAttribute(Compiler compiler, object? attrValue, string attrName) { CheckRequiredAttribute(compiler, attrValue != null, attrName); } public void CheckRequiredAttribute(Compiler compiler, bool attr, string attrName) { if (!attr) { throw XsltException.Create(SR.Xslt_MissingAttribute, attrName); } } } }
-1
dotnet/runtime
66,022
Add Android 32 to RID graph
Supports Android 12L, which will be stable most likely by summer or earlier.
steveisok
2022-03-01T19:37:08Z
2022-03-11T21:09:58Z
a883caa0803778084167b978281c34db8e753246
36a435cf12309f5119c2f5ce103af7fa28150d72
Add Android 32 to RID graph. Supports Android 12L, which will be stable most likely by summer or earlier.
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/nmtokens_restriction_single_default_value.xsd
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:attribute name="testatr" default="a"> <xs:simpleType> <xs:restriction base="xs:NMTOKENS"> <xs:enumeration value="a"/> <xs:enumeration value="b"/> <xs:enumeration value="c"/> <xs:enumeration value="d"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:schema>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:attribute name="testatr" default="a"> <xs:simpleType> <xs:restriction base="xs:NMTOKENS"> <xs:enumeration value="a"/> <xs:enumeration value="b"/> <xs:enumeration value="c"/> <xs:enumeration value="d"/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:schema>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Net.Quic/src/Resources/Strings.resx
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="net_quic_addressfamily_notsupported" xml:space="preserve"> <value>Only IPv4 or IPv6 are supported</value> </data> <data name="net_quic_connectionaborted" xml:space="preserve"> <value>Connection aborted by peer ({0}).</value> </data> <data name="net_quic_operationaborted" xml:space="preserve"> <value>Operation aborted.</value> </data> <data name="net_quic_reading_notallowed" xml:space="preserve"> <value>Reading is not allowed on stream.</value> </data> <data name="net_quic_sending_aborted" xml:space="preserve"> <value>Sending has already been aborted on the stream</value> </data> <data name="net_quic_streamaborted" xml:space="preserve"> <value>Stream aborted by peer ({0}).</value> </data> <data name="SystemNetQuic_PlatformNotSupported" xml:space="preserve"> <value>System.Net.Quic is not supported on this platform.</value> </data> <data name="net_quic_unsupported_address_family" xml:space="preserve"> <value>Unsupported address family of '{0}' for remote endpoint.</value> </data> <data name="net_quic_writing_notallowed" xml:space="preserve"> <value>Writing is not allowed on stream.</value> </data> <data name="net_quic_timeout_use_gt_zero" xml:space="preserve"> <value>Timeout can only be set to 'System.Threading.Timeout.Infinite' or a value &gt; 0.</value> </data> <data name="net_quic_timeout" xml:space="preserve"> <value>Connection timed out.</value> </data> <data name="net_quic_ssl_option" xml:space="preserve"> <value>'{0}' is not supported by System.Net.Quic.</value> </data> <data name="net_quic_cert_custom_validation" xml:space="preserve"> <value>The remote certificate was rejected by the provided RemoteCertificateValidationCallback.</value> </data> <data name="net_quic_cert_chain_validation" xml:space="preserve"> <value>The remote certificate is invalid because of errors in the certificate chain: {0}</value> </data> <data name="net_quic_not_connected" xml:space="preserve"> <value>Connection is not connected.</value> </data> <data name="net_ssl_app_protocols_invalid" xml:space="preserve"> <value>The application protocol list is invalid.</value> </data> </root>
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="net_quic_addressfamily_notsupported" xml:space="preserve"> <value>Only IPv4 or IPv6 are supported</value> </data> <data name="net_quic_connectionaborted" xml:space="preserve"> <value>Connection aborted by peer ({0}).</value> </data> <data name="net_quic_operationaborted" xml:space="preserve"> <value>Operation aborted.</value> </data> <data name="net_quic_reading_notallowed" xml:space="preserve"> <value>Reading is not allowed on stream.</value> </data> <data name="net_quic_sending_aborted" xml:space="preserve"> <value>Sending has already been aborted on the stream</value> </data> <data name="net_quic_streamaborted" xml:space="preserve"> <value>Stream aborted by peer ({0}).</value> </data> <data name="SystemNetQuic_PlatformNotSupported" xml:space="preserve"> <value>System.Net.Quic is not supported on this platform.</value> </data> <data name="net_quic_unsupported_address_family" xml:space="preserve"> <value>Unsupported address family of '{0}' for remote endpoint.</value> </data> <data name="net_quic_writing_notallowed" xml:space="preserve"> <value>Writing is not allowed on stream.</value> </data> <data name="net_quic_timeout_use_gt_zero" xml:space="preserve"> <value>Timeout can only be set to 'System.Threading.Timeout.Infinite' or a value &gt; 0.</value> </data> <data name="net_quic_timeout" xml:space="preserve"> <value>Connection timed out.</value> </data> <data name="net_quic_ssl_option" xml:space="preserve"> <value>'{0}' is not supported by System.Net.Quic.</value> </data> <data name="net_quic_cert_custom_validation" xml:space="preserve"> <value>The remote certificate was rejected by the provided RemoteCertificateValidationCallback.</value> </data> <data name="net_quic_cert_chain_validation" xml:space="preserve"> <value>The remote certificate is invalid because of errors in the certificate chain: {0}</value> </data> <data name="net_quic_not_connected" xml:space="preserve"> <value>Connection is not connected.</value> </data> <data name="net_ssl_app_protocols_invalid" xml:space="preserve"> <value>The application protocol list is invalid.</value> </data> <data name="net_quic_tls_version_notsupported" xml:space="preserve"> <value>Could not use a TLS version required by Quic. TLS 1.3 may have been disabled in the registry.</value> </data> </root>
1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Net.Quic/src/System.Net.Quic.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Linux;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-FreeBSD;$(NetCoreAppCurrent)</TargetFrameworks> <Nullable>enable</Nullable> </PropertyGroup> <!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. --> <PropertyGroup> <TargetPlatformIdentifier>$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)'))</TargetPlatformIdentifier> <DefineConstants Condition="'$(TargetPlatformIdentifier)' == 'FreeBSD' or '$(TargetPlatformIdentifier)' == 'OSX'">$(DefineConstants);SOCKADDR_HAS_LENGTH</DefineConstants> <GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetPlatformIdentifier)' == ''">SR.SystemNetQuic_PlatformNotSupported</GeneratePlatformNotSupportedAssemblyMessage> <ApiExclusionListPath Condition="'$(TargetPlatformIdentifier)' == ''">ExcludeApiList.PNSE.txt</ApiExclusionListPath> </PropertyGroup> <!-- Source files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' != ''"> <Compile Include="System\Net\Quic\NetEventSource.Quic.cs" /> <Compile Include="System\Net\Quic\QuicClientConnectionOptions.cs" /> <Compile Include="System\Net\Quic\QuicConnection.cs" /> <Compile Include="System\Net\Quic\QuicConnectionAbortedException.cs" /> <Compile Include="System\Net\Quic\QuicException.cs" /> <Compile Include="System\Net\Quic\QuicImplementationProviders.cs" /> <Compile Include="System\Net\Quic\QuicListener.cs" /> <Compile Include="System\Net\Quic\QuicListenerOptions.cs" /> <Compile Include="System\Net\Quic\QuicOperationAbortedException.cs" /> <Compile Include="System\Net\Quic\QuicOptions.cs" /> <Compile Include="System\Net\Quic\QuicStream.cs" /> <Compile Include="System\Net\Quic\QuicStreamAbortedException.cs" /> <Compile Include="System\Net\Quic\Implementations\*.cs" /> <Compile Include="System\Net\Quic\Implementations\Mock\*.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\*.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Internal\*.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicAlpnHelper.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicEnums.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicNativeMethods.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusHelper.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicTraceHelper.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicConfigurationHandle.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicConnectionHandle.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicListenerHandle.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicRegistrationHandle.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicStreamHandle.cs" /> <Compile Include="$(CommonPath)DisableRuntimeMarshalling.cs"> <Link>Common\DisableRuntimeMarshalling.cs</Link> </Compile> <!-- System.Net common --> <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs" Link="Common\System\Threading\Tasks\TaskToApm.cs" /> <Compile Include="$(CommonPath)System\Net\ArrayBuffer.cs" Link="Common\System\Net\ArrayBuffer.cs" /> <Compile Include="$(CommonPath)System\Net\MultiArrayBuffer.cs" Link="Common\System\Net\MultiArrayBuffer.cs" /> <Compile Include="$(CommonPath)System\Net\Logging\NetEventSource.Common.cs" Link="Common\System\Net\Logging\NetEventSource.Common.cs" /> <Compile Include="$(CommonPath)System\Net\StreamBuffer.cs" Link="Common\System\Net\StreamBuffer.cs" /> </ItemGroup> <!-- Unsupported platforms --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == ''"> <Compile Include="System\Net\Quic\QuicImplementationProviders.Unsupported.cs" /> </ItemGroup> <!-- Windows specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs" Link="Common\Interop\Windows\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CERT_CONTEXT.cs" Link="Common\Interop\Windows\Crypt32\Interop.CERT_CONTEXT.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CERT_INFO.cs" Link="Common\Interop\Windows\Crypt32\Interop.CERT_INFO.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CERT_PUBLIC_KEY_INFO.cs" Link="Common\Interop\Windows\Crypt32\Interop.CERT_PUBLIC_KEY_INFO.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CRYPT_ALGORITHM_IDENTIFIER.cs" Link="Common\Interop\Windows\Crypt32\Interop.Interop.CRYPT_ALGORITHM_IDENTIFIER.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CRYPT_BIT_BLOB.cs" Link="Common\Interop\Windows\Crypt32\Interop.Interop.CRYPT_BIT_BLOB.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.DATA_BLOB.cs" Link="Common\Interop\Windows\Crypt32\Interop.DATA_BLOB.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.certificates.cs" Link="Common\Interop\Windows\Crypt32\Interop.certificates.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.certificates_types.cs" Link="Common\Interop\Windows\Crypt32\Interop.certificates_types.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs" Link="Common\Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.MsgEncodingType.cs" Link="Common\Interop\Windows\Crypt32\Interop.Interop.MsgEncodingType.cs" /> <Compile Include="$(CommonPath)System\Net\Security\CertificateValidation.Windows.cs" Link="Common\System\Net\Security\CertificateValidation.Windows.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.Windows.cs" /> </ItemGroup> <!-- Unix (OSX + Linux) specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Linux' or '$(TargetPlatformIdentifier)' == 'OSX' or '$(TargetPlatformIdentifier)' == 'FreeBSD'"> <Compile Include="$(CommonPath)Interop\Unix\Interop.Libraries.cs" Link="Common\Interop\Unix\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.ASN1.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.ASN1.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.BIO.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.BIO.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.ERR.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.ERR.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.Initialization.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.Initialization.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.Crypto.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.Crypto.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.Ssl.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.Ssl.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.SslCtx.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.SslCtx.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.SslCtxOptions.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.SslCtxOptions.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.SetProtocolOptions.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.SetProtocolOptions.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509Name.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509Name.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509Ext.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509Ext.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509Stack.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509Stack.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509StoreCtx.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509StoreCtx.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Net.Security.Native\Interop.Initialization.cs" Link="Common\Interop\Unix\System.Net.Security.Native\Interop.Initialization.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeX509Handles.Unix.cs" Link="Common\Microsoft\Win32\SafeHandles\SafeX509Handles.Unix.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\X509ExtensionSafeHandles.Unix.cs" Link="Common\Microsoft\Win32\SafeHandles\X509ExtensionSafeHandles.Unix.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeInteriorHandle.cs" Link="Common\Microsoft\Win32\SafeHandles\SafeInteriorHandle.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeBioHandle.Unix.cs" Link="Common\Microsoft\Win32\SafeHandles\SafeBioHandle.Unix.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\Asn1SafeHandles.Unix.cs" Link="Common\Microsoft\Win32\SafeHandles\Asn1SafeHandles.Unix.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeHandleCache.cs" Link="Common\Microsoft\Win32\SafeHandles\SafeHandleCache.cs" /> </ItemGroup> <!-- Linux specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Linux'"> <Compile Include="$(CommonPath)Interop\Linux\Interop.Libraries.cs" Link="Common\Interop\Linux\Interop.Libraries.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.Linux.cs" /> <Compile Include="$(CommonPath)System\Net\Security\CertificateValidation.Unix.cs" Link="Common\System\Net\Security\CertificateValidation.Unix.cs" /> </ItemGroup> <!-- FreeBSD specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'FreeBSD' "> <Compile Include="$(CommonPath)System\Net\Security\CertificateValidation.Unix.cs" Link="Common\System\Net\Security\CertificateValidation.Unix.cs" /> <Compile Include="$(CommonPath)Interop\FreeBSD\Interop.Libraries.cs" Link="Common\Interop\FreeBSD\Interop.Libraries.cs" /> <!-- Assume similarity with OSX for now --> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.OSX.cs" /> </ItemGroup> <!-- OSX specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'OSX'"> <Compile Include="$(CommonPath)System\Net\Security\CertificateValidation.OSX.cs" Link="Common\System\Net\Security\CertificateValidation.OSX.cs" /> <Compile Include="$(CommonPath)Interop\OSX\Interop.Libraries.cs" Link="Common\Interop\OSX\Interop.Libraries.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.OSX.cs" /> </ItemGroup> <!-- Project references --> <ItemGroup> <PackageReference Include="System.Net.MsQuic.Transport" Version="$(SystemNetMsQuicTransportVersion)" PrivateAssets="all" GeneratePathProperty="true" Condition="'$(DotNetBuildFromSource)' != 'true'" /> </ItemGroup> <ItemGroup> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" /> <Reference Include="System.Collections.NonGeneric" /> <Reference Include="System.Console" Condition="'$(Configuration)' == 'Debug'" /> <Reference Include="System.Diagnostics.Tracing" /> <Reference Include="System.Memory" /> <Reference Include="System.Net.Primitives" /> <Reference Include="System.Net.Security" /> <Reference Include="System.Net.Sockets" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.CompilerServices.Unsafe" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Security.Cryptography" /> <Reference Include="System.Security.Cryptography.X509Certificates" /> <Reference Include="System.Threading" /> <Reference Include="System.Threading.Channels" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Linux' or '$(TargetPlatformIdentifier)' == 'OSX' or '$(TargetPlatformIdentifier)' == 'FreeBSD'"> <Reference Include="System.Diagnostics.StackTrace" Condition="'$(Configuration)' == 'Debug'" /> <Reference Include="System.Security.Cryptography.OpenSsl" /> </ItemGroup> <!-- Support for deploying msquic --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows' and ('$(TargetArchitecture)' == 'x64' or '$(TargetArchitecture)' == 'x86') and '$(DotNetBuildFromSource)' != 'true'"> <BinPlaceDir Include="$(MicrosoftNetCoreAppRuntimePackNativeDir)" ItemName="NativeBinPlaceItem" /> <BinPlaceDir Include="$(NetCoreAppCurrentTestHostSharedFrameworkPath)" ItemName="NativeBinPlaceItem" /> <BinPlaceDir Include="$(LibrariesAllBinArtifactsPath)" ItemName="NativeBinPlaceItem" /> <BinPlaceDir Include="$(LibrariesNativeArtifactsPath)" ItemName="NativeBinPlaceItem" /> <NativeBinPlaceItem Include="$(PkgSystem_Net_MsQuic_Transport)\runtimes\win10-$(TargetArchitecture)\native\*" /> </ItemGroup> <ItemGroup> <Content Include="libmsquic.dylib" Condition="Exists('libmsquic.dylib')"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </Content> <Content Include="libmsquic.so" Condition="Exists('libmsquic.so')"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </Content> <Content Include="libmsquic.lttng.so" Condition="Exists('libmsquic.lttng.so')"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </Content> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Linux;$(NetCoreAppCurrent)-OSX;$(NetCoreAppCurrent)-FreeBSD;$(NetCoreAppCurrent)</TargetFrameworks> <Nullable>enable</Nullable> </PropertyGroup> <!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. --> <PropertyGroup> <TargetPlatformIdentifier>$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)'))</TargetPlatformIdentifier> <DefineConstants Condition="'$(TargetPlatformIdentifier)' == 'FreeBSD' or '$(TargetPlatformIdentifier)' == 'OSX'">$(DefineConstants);SOCKADDR_HAS_LENGTH</DefineConstants> <DefineConstants Condition="'$(TargetPlatformIdentifier)' == 'windows'">$(DefineConstants);TARGET_WINDOWS</DefineConstants> <GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetPlatformIdentifier)' == ''">SR.SystemNetQuic_PlatformNotSupported</GeneratePlatformNotSupportedAssemblyMessage> <ApiExclusionListPath Condition="'$(TargetPlatformIdentifier)' == ''">ExcludeApiList.PNSE.txt</ApiExclusionListPath> </PropertyGroup> <!-- Source files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' != ''"> <Compile Include="System\Net\Quic\NetEventSource.Quic.cs" /> <Compile Include="System\Net\Quic\QuicClientConnectionOptions.cs" /> <Compile Include="System\Net\Quic\QuicConnection.cs" /> <Compile Include="System\Net\Quic\QuicConnectionAbortedException.cs" /> <Compile Include="System\Net\Quic\QuicException.cs" /> <Compile Include="System\Net\Quic\QuicImplementationProviders.cs" /> <Compile Include="System\Net\Quic\QuicListener.cs" /> <Compile Include="System\Net\Quic\QuicListenerOptions.cs" /> <Compile Include="System\Net\Quic\QuicOperationAbortedException.cs" /> <Compile Include="System\Net\Quic\QuicOptions.cs" /> <Compile Include="System\Net\Quic\QuicStream.cs" /> <Compile Include="System\Net\Quic\QuicStreamAbortedException.cs" /> <Compile Include="System\Net\Quic\Implementations\*.cs" /> <Compile Include="System\Net\Quic\Implementations\Mock\*.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\*.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Internal\*.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicAlpnHelper.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicEnums.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicNativeMethods.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusHelper.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicTraceHelper.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicConfigurationHandle.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicConnectionHandle.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicListenerHandle.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicRegistrationHandle.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\SafeMsQuicStreamHandle.cs" /> <Compile Include="$(CommonPath)DisableRuntimeMarshalling.cs"> <Link>Common\DisableRuntimeMarshalling.cs</Link> </Compile> <!-- System.Net common --> <Compile Include="$(CommonPath)System\Threading\Tasks\TaskToApm.cs" Link="Common\System\Threading\Tasks\TaskToApm.cs" /> <Compile Include="$(CommonPath)System\Net\ArrayBuffer.cs" Link="Common\System\Net\ArrayBuffer.cs" /> <Compile Include="$(CommonPath)System\Net\MultiArrayBuffer.cs" Link="Common\System\Net\MultiArrayBuffer.cs" /> <Compile Include="$(CommonPath)System\Net\Logging\NetEventSource.Common.cs" Link="Common\System\Net\Logging\NetEventSource.Common.cs" /> <Compile Include="$(CommonPath)System\Net\StreamBuffer.cs" Link="Common\System\Net\StreamBuffer.cs" /> </ItemGroup> <!-- Unsupported platforms --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == ''"> <Compile Include="System\Net\Quic\QuicImplementationProviders.Unsupported.cs" /> </ItemGroup> <!-- Windows specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs" Link="Common\Interop\Windows\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CERT_CONTEXT.cs" Link="Common\Interop\Windows\Crypt32\Interop.CERT_CONTEXT.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CERT_INFO.cs" Link="Common\Interop\Windows\Crypt32\Interop.CERT_INFO.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CERT_PUBLIC_KEY_INFO.cs" Link="Common\Interop\Windows\Crypt32\Interop.CERT_PUBLIC_KEY_INFO.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CRYPT_ALGORITHM_IDENTIFIER.cs" Link="Common\Interop\Windows\Crypt32\Interop.Interop.CRYPT_ALGORITHM_IDENTIFIER.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CRYPT_BIT_BLOB.cs" Link="Common\Interop\Windows\Crypt32\Interop.Interop.CRYPT_BIT_BLOB.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.DATA_BLOB.cs" Link="Common\Interop\Windows\Crypt32\Interop.DATA_BLOB.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.certificates.cs" Link="Common\Interop\Windows\Crypt32\Interop.certificates.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.certificates_types.cs" Link="Common\Interop\Windows\Crypt32\Interop.certificates_types.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs" Link="Common\Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs" /> <Compile Include="$(CommonPath)Interop\Windows\Crypt32\Interop.MsgEncodingType.cs" Link="Common\Interop\Windows\Crypt32\Interop.Interop.MsgEncodingType.cs" /> <Compile Include="$(CommonPath)Interop\Windows\SChannel\Interop.SECURITY_STATUS.cs" Link="Common\Interop\Windows\SChannel\Interop.SECURITY_STATUS.cs" /> <Compile Include="$(CommonPath)System\Net\Security\CertificateValidation.Windows.cs" Link="Common\System\Net\Security\CertificateValidation.Windows.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.Windows.cs" /> </ItemGroup> <!-- Unix (OSX + Linux) specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Linux' or '$(TargetPlatformIdentifier)' == 'OSX' or '$(TargetPlatformIdentifier)' == 'FreeBSD'"> <Compile Include="$(CommonPath)Interop\Unix\Interop.Libraries.cs" Link="Common\Interop\Unix\Interop.Libraries.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.ASN1.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.ASN1.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.BIO.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.BIO.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.ERR.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.ERR.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.Initialization.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.Initialization.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.Crypto.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.Crypto.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.OpenSslVersion.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.Ssl.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.Ssl.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.SslCtx.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.SslCtx.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.SslCtxOptions.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.SslCtxOptions.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.SetProtocolOptions.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.SetProtocolOptions.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509Name.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509Name.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509Ext.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509Ext.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509Stack.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509Stack.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Security.Cryptography.Native\Interop.X509StoreCtx.cs" Link="Common\Interop\Unix\System.Security.Cryptography.Native\Interop.X509StoreCtx.cs" /> <Compile Include="$(CommonPath)Interop\Unix\System.Net.Security.Native\Interop.Initialization.cs" Link="Common\Interop\Unix\System.Net.Security.Native\Interop.Initialization.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeX509Handles.Unix.cs" Link="Common\Microsoft\Win32\SafeHandles\SafeX509Handles.Unix.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\X509ExtensionSafeHandles.Unix.cs" Link="Common\Microsoft\Win32\SafeHandles\X509ExtensionSafeHandles.Unix.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeInteriorHandle.cs" Link="Common\Microsoft\Win32\SafeHandles\SafeInteriorHandle.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeBioHandle.Unix.cs" Link="Common\Microsoft\Win32\SafeHandles\SafeBioHandle.Unix.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\Asn1SafeHandles.Unix.cs" Link="Common\Microsoft\Win32\SafeHandles\Asn1SafeHandles.Unix.cs" /> <Compile Include="$(CommonPath)Microsoft\Win32\SafeHandles\SafeHandleCache.cs" Link="Common\Microsoft\Win32\SafeHandles\SafeHandleCache.cs" /> </ItemGroup> <!-- Linux specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Linux'"> <Compile Include="$(CommonPath)Interop\Linux\Interop.Libraries.cs" Link="Common\Interop\Linux\Interop.Libraries.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.Linux.cs" /> <Compile Include="$(CommonPath)System\Net\Security\CertificateValidation.Unix.cs" Link="Common\System\Net\Security\CertificateValidation.Unix.cs" /> </ItemGroup> <!-- FreeBSD specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'FreeBSD' "> <Compile Include="$(CommonPath)System\Net\Security\CertificateValidation.Unix.cs" Link="Common\System\Net\Security\CertificateValidation.Unix.cs" /> <Compile Include="$(CommonPath)Interop\FreeBSD\Interop.Libraries.cs" Link="Common\Interop\FreeBSD\Interop.Libraries.cs" /> <!-- Assume similarity with OSX for now --> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.OSX.cs" /> </ItemGroup> <!-- OSX specific files --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'OSX'"> <Compile Include="$(CommonPath)System\Net\Security\CertificateValidation.OSX.cs" Link="Common\System\Net\Security\CertificateValidation.OSX.cs" /> <Compile Include="$(CommonPath)Interop\OSX\Interop.Libraries.cs" Link="Common\Interop\OSX\Interop.Libraries.cs" /> <Compile Include="System\Net\Quic\Implementations\MsQuic\Interop\MsQuicStatusCodes.OSX.cs" /> </ItemGroup> <!-- Project references --> <ItemGroup> <PackageReference Include="System.Net.MsQuic.Transport" Version="$(SystemNetMsQuicTransportVersion)" PrivateAssets="all" GeneratePathProperty="true" Condition="'$(DotNetBuildFromSource)' != 'true'" /> </ItemGroup> <ItemGroup> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" /> <Reference Include="System.Collections.NonGeneric" /> <Reference Include="System.Console" Condition="'$(Configuration)' == 'Debug'" /> <Reference Include="System.Diagnostics.Tracing" /> <Reference Include="System.Memory" /> <Reference Include="System.Net.Primitives" /> <Reference Include="System.Net.Security" /> <Reference Include="System.Net.Sockets" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.CompilerServices.Unsafe" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Security.Cryptography" /> <Reference Include="System.Security.Cryptography.X509Certificates" /> <Reference Include="System.Threading" /> <Reference Include="System.Threading.Channels" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows'"> <Reference Include="Microsoft.Win32.Registry" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Linux' or '$(TargetPlatformIdentifier)' == 'OSX' or '$(TargetPlatformIdentifier)' == 'FreeBSD'"> <Reference Include="System.Diagnostics.StackTrace" Condition="'$(Configuration)' == 'Debug'" /> <Reference Include="System.Security.Cryptography.OpenSsl" /> </ItemGroup> <!-- Support for deploying msquic --> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'windows' and ('$(TargetArchitecture)' == 'x64' or '$(TargetArchitecture)' == 'x86') and '$(DotNetBuildFromSource)' != 'true'"> <BinPlaceDir Include="$(MicrosoftNetCoreAppRuntimePackNativeDir)" ItemName="NativeBinPlaceItem" /> <BinPlaceDir Include="$(NetCoreAppCurrentTestHostSharedFrameworkPath)" ItemName="NativeBinPlaceItem" /> <BinPlaceDir Include="$(LibrariesAllBinArtifactsPath)" ItemName="NativeBinPlaceItem" /> <BinPlaceDir Include="$(LibrariesNativeArtifactsPath)" ItemName="NativeBinPlaceItem" /> <NativeBinPlaceItem Include="$(PkgSystem_Net_MsQuic_Transport)\runtimes\win10-$(TargetArchitecture)\native\*" /> </ItemGroup> <ItemGroup> <Content Include="libmsquic.dylib" Condition="Exists('libmsquic.dylib')"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </Content> <Content Include="libmsquic.so" Condition="Exists('libmsquic.so')"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </Content> <Content Include="libmsquic.lttng.so" Condition="Exists('libmsquic.lttng.so')"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </Content> </ItemGroup> </Project>
1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Internal/MsQuicApi.cs
// 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.CodeAnalysis; using System.Runtime.InteropServices; using static System.Net.Quic.Implementations.MsQuic.Internal.MsQuicNativeMethods; namespace System.Net.Quic.Implementations.MsQuic.Internal { internal unsafe sealed class MsQuicApi { private static readonly Version MinWindowsVersion = new Version(10, 0, 20145, 1000); public SafeMsQuicRegistrationHandle Registration { get; } // This is workaround for a bug in ILTrimmer. // Without these DynamicDependency attributes, .ctor() will be removed from the safe handles. // Remove once fixed: https://github.com/mono/linker/issues/1660 [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicRegistrationHandle))] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicConfigurationHandle))] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicListenerHandle))] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicConnectionHandle))] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicStreamHandle))] private MsQuicApi(NativeApi* vtable) { uint status; SetParamDelegate = new SetParamDelegate(new DelegateHelper(vtable->SetParam).SetParam); GetParamDelegate = new GetParamDelegate(new DelegateHelper(vtable->GetParam).GetParam); SetCallbackHandlerDelegate = new SetCallbackHandlerDelegate(new DelegateHelper(vtable->SetCallbackHandler).SetCallbackHandler); RegistrationOpenDelegate = new RegistrationOpenDelegate(new DelegateHelper(vtable->RegistrationOpen).RegistrationOpen); RegistrationCloseDelegate = Marshal.GetDelegateForFunctionPointer<RegistrationCloseDelegate>( vtable->RegistrationClose); ConfigurationOpenDelegate = new ConfigurationOpenDelegate(new DelegateHelper(vtable->ConfigurationOpen).ConfigurationOpen); ConfigurationCloseDelegate = Marshal.GetDelegateForFunctionPointer<ConfigurationCloseDelegate>( vtable->ConfigurationClose); ConfigurationLoadCredentialDelegate = new ConfigurationLoadCredentialDelegate(new DelegateHelper(vtable->ConfigurationLoadCredential).ConfigurationLoadCredential); ListenerOpenDelegate = new ListenerOpenDelegate(new DelegateHelper(vtable->ListenerOpen).ListenerOpen); ListenerCloseDelegate = Marshal.GetDelegateForFunctionPointer<ListenerCloseDelegate>( vtable->ListenerClose); ListenerStartDelegate = new ListenerStartDelegate(new DelegateHelper(vtable->ListenerStart).ListenerStart); ListenerStopDelegate = new ListenerStopDelegate(new DelegateHelper(vtable->ListenerStop).ListenerStop); ConnectionOpenDelegate = new ConnectionOpenDelegate(new DelegateHelper(vtable->ConnectionOpen).ConnectionOpen); ConnectionCloseDelegate = Marshal.GetDelegateForFunctionPointer<ConnectionCloseDelegate>( vtable->ConnectionClose); ConnectionSetConfigurationDelegate = new ConnectionSetConfigurationDelegate(new DelegateHelper(vtable->ConnectionSetConfiguration).ConnectionSetConfiguration); ConnectionShutdownDelegate = new ConnectionShutdownDelegate(new DelegateHelper(vtable->ConnectionShutdown).ConnectionShutdown); ConnectionStartDelegate = new ConnectionStartDelegate(new DelegateHelper(vtable->ConnectionStart).ConnectionStart); StreamOpenDelegate = new StreamOpenDelegate(new DelegateHelper(vtable->StreamOpen).StreamOpen); StreamCloseDelegate = Marshal.GetDelegateForFunctionPointer<StreamCloseDelegate>( vtable->StreamClose); StreamStartDelegate = new StreamStartDelegate(new DelegateHelper(vtable->StreamStart).StreamStart); StreamShutdownDelegate = new StreamShutdownDelegate(new DelegateHelper(vtable->StreamShutdown).StreamShutdown); StreamSendDelegate = new StreamSendDelegate(new DelegateHelper(vtable->StreamSend).StreamSend); StreamReceiveCompleteDelegate = new StreamReceiveCompleteDelegate(new DelegateHelper(vtable->StreamReceiveComplete).StreamReceiveComplete); StreamReceiveSetEnabledDelegate = new StreamReceiveSetEnabledDelegate(new DelegateHelper(vtable->StreamReceiveSetEnabled).StreamReceiveSetEnabled); var cfg = new RegistrationConfig { AppName = ".NET", ExecutionProfile = QUIC_EXECUTION_PROFILE.QUIC_EXECUTION_PROFILE_LOW_LATENCY }; status = RegistrationOpenDelegate(ref cfg, out SafeMsQuicRegistrationHandle handle); QuicExceptionHelpers.ThrowIfFailed(status, "RegistrationOpen failed."); Registration = handle; } internal static MsQuicApi Api { get; } = null!; internal static bool IsQuicSupported { get; } private const int MsQuicVersion = 1; static MsQuicApi() { if (OperatingSystem.IsWindows() && !IsWindowsVersionSupported()) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(null, $"Current Windows version ({Environment.OSVersion}) is not supported by QUIC. Minimal supported version is {MinWindowsVersion}"); } return; } if (NativeLibrary.TryLoad(Interop.Libraries.MsQuic, typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out IntPtr msQuicHandle) || NativeLibrary.TryLoad($"{Interop.Libraries.MsQuic}.{MsQuicVersion}", typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle)) { try { if (NativeLibrary.TryGetExport(msQuicHandle, "MsQuicOpenVersion", out IntPtr msQuicOpenVersionAddress)) { NativeApi* vtable; delegate* unmanaged[Cdecl]<uint, NativeApi**, uint> msQuicOpenVersion = (delegate* unmanaged[Cdecl]<uint, NativeApi**, uint>)msQuicOpenVersionAddress; uint status = msQuicOpenVersion(MsQuicVersion, &vtable); if (MsQuicStatusHelper.SuccessfulStatusCode(status)) { IsQuicSupported = true; Api = new MsQuicApi(vtable); } } } finally { if (!IsQuicSupported) { NativeLibrary.Free(msQuicHandle); } } } } private static bool IsWindowsVersionSupported() => OperatingSystem.IsWindowsVersionAtLeast(MinWindowsVersion.Major, MinWindowsVersion.Minor, MinWindowsVersion.Build, MinWindowsVersion.Revision); // TODO: Consider updating all of these delegates to instead use function pointers. internal RegistrationOpenDelegate RegistrationOpenDelegate { get; } internal RegistrationCloseDelegate RegistrationCloseDelegate { get; } internal ConfigurationOpenDelegate ConfigurationOpenDelegate { get; } internal ConfigurationCloseDelegate ConfigurationCloseDelegate { get; } internal ConfigurationLoadCredentialDelegate ConfigurationLoadCredentialDelegate { get; } internal ListenerOpenDelegate ListenerOpenDelegate { get; } internal ListenerCloseDelegate ListenerCloseDelegate { get; } internal ListenerStartDelegate ListenerStartDelegate { get; } internal ListenerStopDelegate ListenerStopDelegate { get; } // TODO: missing SendResumptionTicket internal ConnectionOpenDelegate ConnectionOpenDelegate { get; } internal ConnectionCloseDelegate ConnectionCloseDelegate { get; } internal ConnectionShutdownDelegate ConnectionShutdownDelegate { get; } internal ConnectionStartDelegate ConnectionStartDelegate { get; } internal ConnectionSetConfigurationDelegate ConnectionSetConfigurationDelegate { get; } internal StreamOpenDelegate StreamOpenDelegate { get; } internal StreamCloseDelegate StreamCloseDelegate { get; } internal StreamStartDelegate StreamStartDelegate { get; } internal StreamShutdownDelegate StreamShutdownDelegate { get; } internal StreamSendDelegate StreamSendDelegate { get; } internal StreamReceiveCompleteDelegate StreamReceiveCompleteDelegate { get; } internal StreamReceiveSetEnabledDelegate StreamReceiveSetEnabledDelegate { get; } internal SetCallbackHandlerDelegate SetCallbackHandlerDelegate { get; } internal SetParamDelegate SetParamDelegate { get; } internal GetParamDelegate GetParamDelegate { get; } } }
// 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.CodeAnalysis; using System.Runtime.InteropServices; #if TARGET_WINDOWS using Microsoft.Win32; #endif using static System.Net.Quic.Implementations.MsQuic.Internal.MsQuicNativeMethods; namespace System.Net.Quic.Implementations.MsQuic.Internal { internal unsafe sealed class MsQuicApi { private static readonly Version MinWindowsVersion = new Version(10, 0, 20145, 1000); public SafeMsQuicRegistrationHandle Registration { get; } // This is workaround for a bug in ILTrimmer. // Without these DynamicDependency attributes, .ctor() will be removed from the safe handles. // Remove once fixed: https://github.com/mono/linker/issues/1660 [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicRegistrationHandle))] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicConfigurationHandle))] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicListenerHandle))] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicConnectionHandle))] [DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(SafeMsQuicStreamHandle))] private MsQuicApi(NativeApi* vtable) { uint status; SetParamDelegate = new SetParamDelegate(new DelegateHelper(vtable->SetParam).SetParam); GetParamDelegate = new GetParamDelegate(new DelegateHelper(vtable->GetParam).GetParam); SetCallbackHandlerDelegate = new SetCallbackHandlerDelegate(new DelegateHelper(vtable->SetCallbackHandler).SetCallbackHandler); RegistrationOpenDelegate = new RegistrationOpenDelegate(new DelegateHelper(vtable->RegistrationOpen).RegistrationOpen); RegistrationCloseDelegate = Marshal.GetDelegateForFunctionPointer<RegistrationCloseDelegate>( vtable->RegistrationClose); ConfigurationOpenDelegate = new ConfigurationOpenDelegate(new DelegateHelper(vtable->ConfigurationOpen).ConfigurationOpen); ConfigurationCloseDelegate = Marshal.GetDelegateForFunctionPointer<ConfigurationCloseDelegate>( vtable->ConfigurationClose); ConfigurationLoadCredentialDelegate = new ConfigurationLoadCredentialDelegate(new DelegateHelper(vtable->ConfigurationLoadCredential).ConfigurationLoadCredential); ListenerOpenDelegate = new ListenerOpenDelegate(new DelegateHelper(vtable->ListenerOpen).ListenerOpen); ListenerCloseDelegate = Marshal.GetDelegateForFunctionPointer<ListenerCloseDelegate>( vtable->ListenerClose); ListenerStartDelegate = new ListenerStartDelegate(new DelegateHelper(vtable->ListenerStart).ListenerStart); ListenerStopDelegate = new ListenerStopDelegate(new DelegateHelper(vtable->ListenerStop).ListenerStop); ConnectionOpenDelegate = new ConnectionOpenDelegate(new DelegateHelper(vtable->ConnectionOpen).ConnectionOpen); ConnectionCloseDelegate = Marshal.GetDelegateForFunctionPointer<ConnectionCloseDelegate>( vtable->ConnectionClose); ConnectionSetConfigurationDelegate = new ConnectionSetConfigurationDelegate(new DelegateHelper(vtable->ConnectionSetConfiguration).ConnectionSetConfiguration); ConnectionShutdownDelegate = new ConnectionShutdownDelegate(new DelegateHelper(vtable->ConnectionShutdown).ConnectionShutdown); ConnectionStartDelegate = new ConnectionStartDelegate(new DelegateHelper(vtable->ConnectionStart).ConnectionStart); StreamOpenDelegate = new StreamOpenDelegate(new DelegateHelper(vtable->StreamOpen).StreamOpen); StreamCloseDelegate = Marshal.GetDelegateForFunctionPointer<StreamCloseDelegate>( vtable->StreamClose); StreamStartDelegate = new StreamStartDelegate(new DelegateHelper(vtable->StreamStart).StreamStart); StreamShutdownDelegate = new StreamShutdownDelegate(new DelegateHelper(vtable->StreamShutdown).StreamShutdown); StreamSendDelegate = new StreamSendDelegate(new DelegateHelper(vtable->StreamSend).StreamSend); StreamReceiveCompleteDelegate = new StreamReceiveCompleteDelegate(new DelegateHelper(vtable->StreamReceiveComplete).StreamReceiveComplete); StreamReceiveSetEnabledDelegate = new StreamReceiveSetEnabledDelegate(new DelegateHelper(vtable->StreamReceiveSetEnabled).StreamReceiveSetEnabled); var cfg = new RegistrationConfig { AppName = ".NET", ExecutionProfile = QUIC_EXECUTION_PROFILE.QUIC_EXECUTION_PROFILE_LOW_LATENCY }; status = RegistrationOpenDelegate(ref cfg, out SafeMsQuicRegistrationHandle handle); QuicExceptionHelpers.ThrowIfFailed(status, "RegistrationOpen failed."); Registration = handle; } internal static MsQuicApi Api { get; } = null!; internal static bool IsQuicSupported { get; } private const int MsQuicVersion = 1; internal static bool Tls13MayBeDisabled { get; } static MsQuicApi() { if (OperatingSystem.IsWindows()) { if (!IsWindowsVersionSupported()) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Info(null, $"Current Windows version ({Environment.OSVersion}) is not supported by QUIC. Minimal supported version is {MinWindowsVersion}"); } return; } Tls13MayBeDisabled = IsTls13Disabled(); } if (NativeLibrary.TryLoad(Interop.Libraries.MsQuic, typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out IntPtr msQuicHandle) || NativeLibrary.TryLoad($"{Interop.Libraries.MsQuic}.{MsQuicVersion}", typeof(MsQuicApi).Assembly, DllImportSearchPath.AssemblyDirectory, out msQuicHandle)) { try { if (NativeLibrary.TryGetExport(msQuicHandle, "MsQuicOpenVersion", out IntPtr msQuicOpenVersionAddress)) { NativeApi* vtable; delegate* unmanaged[Cdecl]<uint, NativeApi**, uint> msQuicOpenVersion = (delegate* unmanaged[Cdecl]<uint, NativeApi**, uint>)msQuicOpenVersionAddress; uint status = msQuicOpenVersion(MsQuicVersion, &vtable); if (MsQuicStatusHelper.SuccessfulStatusCode(status)) { IsQuicSupported = true; Api = new MsQuicApi(vtable); } } } finally { if (!IsQuicSupported) { NativeLibrary.Free(msQuicHandle); } } } } private static bool IsWindowsVersionSupported() => OperatingSystem.IsWindowsVersionAtLeast(MinWindowsVersion.Major, MinWindowsVersion.Minor, MinWindowsVersion.Build, MinWindowsVersion.Revision); private static bool IsTls13Disabled() { #if TARGET_WINDOWS string[] SChannelTLS13RegKeys = { @"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.3\Client", @"SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.3\Server" }; foreach (var key in SChannelTLS13RegKeys) { using var regKey = Registry.LocalMachine.OpenSubKey(key); if (regKey is null) return false; if (regKey.GetValue("Enabled") is int enabled && enabled == 0) { return true; } } #endif return false; } // TODO: Consider updating all of these delegates to instead use function pointers. internal RegistrationOpenDelegate RegistrationOpenDelegate { get; } internal RegistrationCloseDelegate RegistrationCloseDelegate { get; } internal ConfigurationOpenDelegate ConfigurationOpenDelegate { get; } internal ConfigurationCloseDelegate ConfigurationCloseDelegate { get; } internal ConfigurationLoadCredentialDelegate ConfigurationLoadCredentialDelegate { get; } internal ListenerOpenDelegate ListenerOpenDelegate { get; } internal ListenerCloseDelegate ListenerCloseDelegate { get; } internal ListenerStartDelegate ListenerStartDelegate { get; } internal ListenerStopDelegate ListenerStopDelegate { get; } // TODO: missing SendResumptionTicket internal ConnectionOpenDelegate ConnectionOpenDelegate { get; } internal ConnectionCloseDelegate ConnectionCloseDelegate { get; } internal ConnectionShutdownDelegate ConnectionShutdownDelegate { get; } internal ConnectionStartDelegate ConnectionStartDelegate { get; } internal ConnectionSetConfigurationDelegate ConnectionSetConfigurationDelegate { get; } internal StreamOpenDelegate StreamOpenDelegate { get; } internal StreamCloseDelegate StreamCloseDelegate { get; } internal StreamStartDelegate StreamStartDelegate { get; } internal StreamShutdownDelegate StreamShutdownDelegate { get; } internal StreamSendDelegate StreamSendDelegate { get; } internal StreamReceiveCompleteDelegate StreamReceiveCompleteDelegate { get; } internal StreamReceiveSetEnabledDelegate StreamReceiveSetEnabledDelegate { get; } internal SetCallbackHandlerDelegate SetCallbackHandlerDelegate { get; } internal SetParamDelegate SetParamDelegate { get; } internal GetParamDelegate GetParamDelegate { get; } } }
1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/MsQuic/Interop/SafeMsQuicConfigurationHandle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Net.Security; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using static System.Net.Quic.Implementations.MsQuic.Internal.MsQuicNativeMethods; namespace System.Net.Quic.Implementations.MsQuic.Internal { internal sealed class SafeMsQuicConfigurationHandle : SafeHandle { private static readonly FieldInfo _contextCertificate = typeof(SslStreamCertificateContext).GetField("Certificate", BindingFlags.NonPublic | BindingFlags.Instance)!; private static readonly FieldInfo _contextChain = typeof(SslStreamCertificateContext).GetField("IntermediateCertificates", BindingFlags.NonPublic | BindingFlags.Instance)!; public override bool IsInvalid => handle == IntPtr.Zero; public SafeMsQuicConfigurationHandle() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { MsQuicApi.Api.ConfigurationCloseDelegate(handle); SetHandle(IntPtr.Zero); return true; } // TODO: consider moving the static code from here to keep all the handle classes small and simple. public static SafeMsQuicConfigurationHandle Create(QuicClientConnectionOptions options) { X509Certificate? certificate = null; if (options.ClientAuthenticationOptions != null) { if (options.ClientAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.CipherSuitesPolicy))); } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (options.ClientAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.EncryptionPolicy))); } #pragma warning restore SYSLIB0040 if (options.ClientAuthenticationOptions.ClientCertificates != null) { foreach (var cert in options.ClientAuthenticationOptions.ClientCertificates) { try { if (((X509Certificate2)cert).HasPrivateKey) { // Pick first certificate with private key. certificate = cert; break; } } catch { } } } } return Create(options, QUIC_CREDENTIAL_FLAGS.CLIENT, certificate: certificate, certificateContext: null, options.ClientAuthenticationOptions?.ApplicationProtocols); } public static SafeMsQuicConfigurationHandle Create(QuicOptions options, SslServerAuthenticationOptions? serverAuthenticationOptions, string? targetHost = null) { QUIC_CREDENTIAL_FLAGS flags = QUIC_CREDENTIAL_FLAGS.NONE; X509Certificate? certificate = serverAuthenticationOptions?.ServerCertificate; if (serverAuthenticationOptions != null) { if (serverAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.CipherSuitesPolicy))); } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (serverAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.EncryptionPolicy))); } #pragma warning restore SYSLIB0040 if (serverAuthenticationOptions.ClientCertificateRequired) { flags |= QUIC_CREDENTIAL_FLAGS.REQUIRE_CLIENT_AUTHENTICATION | QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (certificate == null && serverAuthenticationOptions?.ServerCertificateSelectionCallback != null && targetHost != null) { certificate = serverAuthenticationOptions.ServerCertificateSelectionCallback(options, targetHost); } } return Create(options, flags, certificate, serverAuthenticationOptions?.ServerCertificateContext, serverAuthenticationOptions?.ApplicationProtocols); } // TODO: this is called from MsQuicListener and when it fails it wreaks havoc in MsQuicListener finalizer. // Consider moving bigger logic like this outside of constructor call chains. private static unsafe SafeMsQuicConfigurationHandle Create(QuicOptions options, QUIC_CREDENTIAL_FLAGS flags, X509Certificate? certificate, SslStreamCertificateContext? certificateContext, List<SslApplicationProtocol>? alpnProtocols) { // TODO: some of these checks should be done by the QuicOptions type. if (alpnProtocols == null || alpnProtocols.Count == 0) { throw new Exception("At least one SslApplicationProtocol value must be present in SslClientAuthenticationOptions or SslServerAuthenticationOptions."); } if (options.MaxBidirectionalStreams > ushort.MaxValue) { throw new Exception("MaxBidirectionalStreams overflow."); } if (options.MaxBidirectionalStreams > ushort.MaxValue) { throw new Exception("MaxBidirectionalStreams overflow."); } if ((flags & QUIC_CREDENTIAL_FLAGS.CLIENT) == 0) { if (certificate == null && certificateContext == null) { throw new Exception("Server must provide certificate"); } } else { flags |= QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (!OperatingSystem.IsWindows()) { // Use certificate handles on Windows, fall-back to ASN1 otherwise. flags |= QUIC_CREDENTIAL_FLAGS.USE_PORTABLE_CERTIFICATES; } Debug.Assert(!MsQuicApi.Api.Registration.IsInvalid); var settings = new QuicSettings { IsSetFlags = QuicSettingsIsSetFlags.PeerBidiStreamCount | QuicSettingsIsSetFlags.PeerUnidiStreamCount, PeerBidiStreamCount = (ushort)options.MaxBidirectionalStreams, PeerUnidiStreamCount = (ushort)options.MaxUnidirectionalStreams }; if (options.IdleTimeout != Timeout.InfiniteTimeSpan) { if (options.IdleTimeout <= TimeSpan.Zero) throw new Exception("IdleTimeout must not be negative."); 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.IdleTimeoutMs = (ulong)options.IdleTimeout.TotalMilliseconds; } else { settings.IdleTimeoutMs = 0; } settings.IsSetFlags |= QuicSettingsIsSetFlags.IdleTimeoutMs; uint status; SafeMsQuicConfigurationHandle? configurationHandle; X509Certificate2[]? intermediates = null; MemoryHandle[]? handles = null; QuicBuffer[]? buffers = null; try { MsQuicAlpnHelper.Prepare(alpnProtocols, out handles, out buffers); status = MsQuicApi.Api.ConfigurationOpenDelegate(MsQuicApi.Api.Registration, (QuicBuffer*)Marshal.UnsafeAddrOfPinnedArrayElement(buffers, 0), (uint)alpnProtocols.Count, ref settings, (uint)sizeof(QuicSettings), context: IntPtr.Zero, out configurationHandle); } finally { MsQuicAlpnHelper.Return(ref handles, ref buffers); } QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationOpen failed."); try { CredentialConfig config = default; config.Flags = flags; // TODO: consider using LOAD_ASYNCHRONOUS with a callback. if (certificateContext != null) { certificate = (X509Certificate2?) _contextCertificate.GetValue(certificateContext); intermediates = (X509Certificate2[]?) _contextChain.GetValue(certificateContext); if (certificate == null || intermediates == null) { throw new ArgumentException(nameof(certificateContext)); } } if (certificate != null) { if (OperatingSystem.IsWindows()) { config.Type = QUIC_CREDENTIAL_TYPE.CONTEXT; config.Certificate = certificate.Handle; status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } else { CredentialConfigCertificatePkcs12 pkcs12Config; byte[] asn1; if (intermediates?.Length > 0) { X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(certificate); for (int i= 0; i < intermediates?.Length; i++) { collection.Add(intermediates[i]); } asn1 = collection.Export(X509ContentType.Pkcs12)!; } else { asn1 = certificate.Export(X509ContentType.Pkcs12); } fixed (void* ptr = asn1) { pkcs12Config.Asn1Blob = (IntPtr)ptr; pkcs12Config.Asn1BlobLength = (uint)asn1.Length; pkcs12Config.PrivateKeyPassword = IntPtr.Zero; config.Type = QUIC_CREDENTIAL_TYPE.PKCS12; config.Certificate = (IntPtr)(&pkcs12Config); status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } } } else { config.Type = QUIC_CREDENTIAL_TYPE.NONE; status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationLoadCredential failed."); } catch { configurationHandle.Dispose(); throw; } return configurationHandle; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Net.Security; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Threading; using static System.Net.Quic.Implementations.MsQuic.Internal.MsQuicNativeMethods; namespace System.Net.Quic.Implementations.MsQuic.Internal { internal sealed class SafeMsQuicConfigurationHandle : SafeHandle { private static readonly FieldInfo _contextCertificate = typeof(SslStreamCertificateContext).GetField("Certificate", BindingFlags.NonPublic | BindingFlags.Instance)!; private static readonly FieldInfo _contextChain = typeof(SslStreamCertificateContext).GetField("IntermediateCertificates", BindingFlags.NonPublic | BindingFlags.Instance)!; public override bool IsInvalid => handle == IntPtr.Zero; public SafeMsQuicConfigurationHandle() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { MsQuicApi.Api.ConfigurationCloseDelegate(handle); SetHandle(IntPtr.Zero); return true; } // TODO: consider moving the static code from here to keep all the handle classes small and simple. public static SafeMsQuicConfigurationHandle Create(QuicClientConnectionOptions options) { X509Certificate? certificate = null; if (options.ClientAuthenticationOptions != null) { if (options.ClientAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.CipherSuitesPolicy))); } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (options.ClientAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(options.ClientAuthenticationOptions.EncryptionPolicy))); } #pragma warning restore SYSLIB0040 if (options.ClientAuthenticationOptions.ClientCertificates != null) { foreach (var cert in options.ClientAuthenticationOptions.ClientCertificates) { try { if (((X509Certificate2)cert).HasPrivateKey) { // Pick first certificate with private key. certificate = cert; break; } } catch { } } } } return Create(options, QUIC_CREDENTIAL_FLAGS.CLIENT, certificate: certificate, certificateContext: null, options.ClientAuthenticationOptions?.ApplicationProtocols); } public static SafeMsQuicConfigurationHandle Create(QuicOptions options, SslServerAuthenticationOptions? serverAuthenticationOptions, string? targetHost = null) { QUIC_CREDENTIAL_FLAGS flags = QUIC_CREDENTIAL_FLAGS.NONE; X509Certificate? certificate = serverAuthenticationOptions?.ServerCertificate; if (serverAuthenticationOptions != null) { if (serverAuthenticationOptions.CipherSuitesPolicy != null) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.CipherSuitesPolicy))); } #pragma warning disable SYSLIB0040 // NoEncryption and AllowNoEncryption are obsolete if (serverAuthenticationOptions.EncryptionPolicy == EncryptionPolicy.NoEncryption) { throw new PlatformNotSupportedException(SR.Format(SR.net_quic_ssl_option, nameof(serverAuthenticationOptions.EncryptionPolicy))); } #pragma warning restore SYSLIB0040 if (serverAuthenticationOptions.ClientCertificateRequired) { flags |= QUIC_CREDENTIAL_FLAGS.REQUIRE_CLIENT_AUTHENTICATION | QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (certificate == null && serverAuthenticationOptions?.ServerCertificateSelectionCallback != null && targetHost != null) { certificate = serverAuthenticationOptions.ServerCertificateSelectionCallback(options, targetHost); } } return Create(options, flags, certificate, serverAuthenticationOptions?.ServerCertificateContext, serverAuthenticationOptions?.ApplicationProtocols); } // TODO: this is called from MsQuicListener and when it fails it wreaks havoc in MsQuicListener finalizer. // Consider moving bigger logic like this outside of constructor call chains. private static unsafe SafeMsQuicConfigurationHandle Create(QuicOptions options, QUIC_CREDENTIAL_FLAGS flags, X509Certificate? certificate, SslStreamCertificateContext? certificateContext, List<SslApplicationProtocol>? alpnProtocols) { // TODO: some of these checks should be done by the QuicOptions type. if (alpnProtocols == null || alpnProtocols.Count == 0) { throw new Exception("At least one SslApplicationProtocol value must be present in SslClientAuthenticationOptions or SslServerAuthenticationOptions."); } if (options.MaxBidirectionalStreams > ushort.MaxValue) { throw new Exception("MaxBidirectionalStreams overflow."); } if (options.MaxBidirectionalStreams > ushort.MaxValue) { throw new Exception("MaxBidirectionalStreams overflow."); } if ((flags & QUIC_CREDENTIAL_FLAGS.CLIENT) == 0) { if (certificate == null && certificateContext == null) { throw new Exception("Server must provide certificate"); } } else { flags |= QUIC_CREDENTIAL_FLAGS.INDICATE_CERTIFICATE_RECEIVED | QUIC_CREDENTIAL_FLAGS.NO_CERTIFICATE_VALIDATION; } if (!OperatingSystem.IsWindows()) { // Use certificate handles on Windows, fall-back to ASN1 otherwise. flags |= QUIC_CREDENTIAL_FLAGS.USE_PORTABLE_CERTIFICATES; } Debug.Assert(!MsQuicApi.Api.Registration.IsInvalid); var settings = new QuicSettings { IsSetFlags = QuicSettingsIsSetFlags.PeerBidiStreamCount | QuicSettingsIsSetFlags.PeerUnidiStreamCount, PeerBidiStreamCount = (ushort)options.MaxBidirectionalStreams, PeerUnidiStreamCount = (ushort)options.MaxUnidirectionalStreams }; if (options.IdleTimeout != Timeout.InfiniteTimeSpan) { if (options.IdleTimeout <= TimeSpan.Zero) throw new Exception("IdleTimeout must not be negative."); 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.IdleTimeoutMs = (ulong)options.IdleTimeout.TotalMilliseconds; } else { settings.IdleTimeoutMs = 0; } settings.IsSetFlags |= QuicSettingsIsSetFlags.IdleTimeoutMs; uint status; SafeMsQuicConfigurationHandle? configurationHandle; X509Certificate2[]? intermediates = null; MemoryHandle[]? handles = null; QuicBuffer[]? buffers = null; try { MsQuicAlpnHelper.Prepare(alpnProtocols, out handles, out buffers); status = MsQuicApi.Api.ConfigurationOpenDelegate(MsQuicApi.Api.Registration, (QuicBuffer*)Marshal.UnsafeAddrOfPinnedArrayElement(buffers, 0), (uint)alpnProtocols.Count, ref settings, (uint)sizeof(QuicSettings), context: IntPtr.Zero, out configurationHandle); } finally { MsQuicAlpnHelper.Return(ref handles, ref buffers); } QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationOpen failed."); try { CredentialConfig config = default; config.Flags = flags; // TODO: consider using LOAD_ASYNCHRONOUS with a callback. if (certificateContext != null) { certificate = (X509Certificate2?) _contextCertificate.GetValue(certificateContext); intermediates = (X509Certificate2[]?) _contextChain.GetValue(certificateContext); if (certificate == null || intermediates == null) { throw new ArgumentException(nameof(certificateContext)); } } if (certificate != null) { if (OperatingSystem.IsWindows()) { config.Type = QUIC_CREDENTIAL_TYPE.CONTEXT; config.Certificate = certificate.Handle; status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } else { CredentialConfigCertificatePkcs12 pkcs12Config; byte[] asn1; if (intermediates?.Length > 0) { X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Add(certificate); for (int i= 0; i < intermediates?.Length; i++) { collection.Add(intermediates[i]); } asn1 = collection.Export(X509ContentType.Pkcs12)!; } else { asn1 = certificate.Export(X509ContentType.Pkcs12); } fixed (void* ptr = asn1) { pkcs12Config.Asn1Blob = (IntPtr)ptr; pkcs12Config.Asn1BlobLength = (uint)asn1.Length; pkcs12Config.PrivateKeyPassword = IntPtr.Zero; config.Type = QUIC_CREDENTIAL_TYPE.PKCS12; config.Certificate = (IntPtr)(&pkcs12Config); status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } } } else { config.Type = QUIC_CREDENTIAL_TYPE.NONE; status = MsQuicApi.Api.ConfigurationLoadCredentialDelegate(configurationHandle, ref config); } #if TARGET_WINDOWS if ((Interop.SECURITY_STATUS)status == Interop.SECURITY_STATUS.AlgorithmMismatch && MsQuicApi.Tls13MayBeDisabled) { throw new QuicException(SR.net_ssl_app_protocols_invalid, null, (int)status); } #endif QuicExceptionHelpers.ThrowIfFailed(status, "ConfigurationLoadCredential failed."); } catch { configurationHandle.Dispose(); throw; } return configurationHandle; } } }
1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Drawing.Common/src/System/Drawing/Pen.Windows.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Drawing.Drawing2D; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { public partial class Pen { /// <summary> /// Gets or sets a custom cap style to use at the beginning of lines drawn with this <see cref='Pen'/>. /// </summary> public CustomLineCap CustomStartCap { get { IntPtr lineCap; int status = Gdip.GdipGetPenCustomStartCap(new HandleRef(this, NativePen), out lineCap); Gdip.CheckStatus(status); return CustomLineCap.CreateCustomLineCapObject(lineCap); } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenCustomStartCap(new HandleRef(this, NativePen), new HandleRef(value, (value == null) ? IntPtr.Zero : value.nativeCap)); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets a custom cap style to use at the end of lines drawn with this <see cref='Pen'/>. /// </summary> public CustomLineCap CustomEndCap { get { IntPtr lineCap; int status = Gdip.GdipGetPenCustomEndCap(new HandleRef(this, NativePen), out lineCap); Gdip.CheckStatus(status); return CustomLineCap.CreateCustomLineCapObject(lineCap); } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenCustomEndCap( new HandleRef(this, NativePen), new HandleRef(value, (value == null) ? IntPtr.Zero : value.nativeCap)); Gdip.CheckStatus(status); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Drawing.Drawing2D; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { public partial class Pen { /// <summary> /// Gets or sets a custom cap style to use at the beginning of lines drawn with this <see cref='Pen'/>. /// </summary> public CustomLineCap CustomStartCap { get { IntPtr lineCap; int status = Gdip.GdipGetPenCustomStartCap(new HandleRef(this, NativePen), out lineCap); Gdip.CheckStatus(status); return CustomLineCap.CreateCustomLineCapObject(lineCap); } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenCustomStartCap(new HandleRef(this, NativePen), new HandleRef(value, (value == null) ? IntPtr.Zero : value.nativeCap)); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets a custom cap style to use at the end of lines drawn with this <see cref='Pen'/>. /// </summary> public CustomLineCap CustomEndCap { get { IntPtr lineCap; int status = Gdip.GdipGetPenCustomEndCap(new HandleRef(this, NativePen), out lineCap); Gdip.CheckStatus(status); return CustomLineCap.CreateCustomLineCapObject(lineCap); } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenCustomEndCap( new HandleRef(this, NativePen), new HandleRef(value, (value == null) ? IntPtr.Zero : value.nativeCap)); Gdip.CheckStatus(status); } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/BuildWasmApps/Wasm.Build.Tests/ProcessExtensions.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace Wasm.Build.Tests { internal static class ProcessExtensions { #if NET451 private static readonly bool _isWindows = true; #else private static readonly bool _isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #endif private static readonly TimeSpan _defaultTimeout = TimeSpan.FromSeconds(30); public static void KillTree(this Process process) { process.KillTree(_defaultTimeout); } public static void KillTree(this Process process, TimeSpan timeout) { string stdout; if (_isWindows) { RunProcessAndWaitForExit( "taskkill", $"/T /F /PID {process.Id}", timeout, out stdout); } else { var children = new HashSet<int>(); GetAllChildIdsUnix(process.Id, children, timeout); foreach (var childId in children) { KillProcessUnix(childId, timeout); } KillProcessUnix(process.Id, timeout); } } private static void GetAllChildIdsUnix(int parentId, ISet<int> children, TimeSpan timeout) { string stdout; var exitCode = RunProcessAndWaitForExit( "pgrep", $"-P {parentId}", timeout, out stdout); if (exitCode == 0 && !string.IsNullOrEmpty(stdout)) { using (var reader = new StringReader(stdout)) { while (true) { var text = reader.ReadLine(); if (text == null) { return; } int id; if (int.TryParse(text, out id)) { children.Add(id); // Recursively get the children GetAllChildIdsUnix(id, children, timeout); } } } } } private static void KillProcessUnix(int processId, TimeSpan timeout) { string stdout; RunProcessAndWaitForExit( "kill", $"-TERM {processId}", timeout, out stdout); } private static int RunProcessAndWaitForExit(string fileName, string arguments, TimeSpan timeout, out string stdout) { var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false }; var process = Process.Start(startInfo); stdout = null; if (process.WaitForExit((int)timeout.TotalMilliseconds)) { stdout = process.StandardOutput.ReadToEnd(); } else { process.Kill(); } return process.ExitCode; } public static Task StartAndWaitForExitAsync(this Process subject) { var taskCompletionSource = new TaskCompletionSource<object>(); subject.EnableRaisingEvents = true; subject.Exited += (s, a) => { taskCompletionSource.SetResult(null); subject.Dispose(); }; subject.Start(); return taskCompletionSource.Task; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace Wasm.Build.Tests { internal static class ProcessExtensions { #if NET451 private static readonly bool _isWindows = true; #else private static readonly bool _isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #endif private static readonly TimeSpan _defaultTimeout = TimeSpan.FromSeconds(30); public static void KillTree(this Process process) { process.KillTree(_defaultTimeout); } public static void KillTree(this Process process, TimeSpan timeout) { string stdout; if (_isWindows) { RunProcessAndWaitForExit( "taskkill", $"/T /F /PID {process.Id}", timeout, out stdout); } else { var children = new HashSet<int>(); GetAllChildIdsUnix(process.Id, children, timeout); foreach (var childId in children) { KillProcessUnix(childId, timeout); } KillProcessUnix(process.Id, timeout); } } private static void GetAllChildIdsUnix(int parentId, ISet<int> children, TimeSpan timeout) { string stdout; var exitCode = RunProcessAndWaitForExit( "pgrep", $"-P {parentId}", timeout, out stdout); if (exitCode == 0 && !string.IsNullOrEmpty(stdout)) { using (var reader = new StringReader(stdout)) { while (true) { var text = reader.ReadLine(); if (text == null) { return; } int id; if (int.TryParse(text, out id)) { children.Add(id); // Recursively get the children GetAllChildIdsUnix(id, children, timeout); } } } } } private static void KillProcessUnix(int processId, TimeSpan timeout) { string stdout; RunProcessAndWaitForExit( "kill", $"-TERM {processId}", timeout, out stdout); } private static int RunProcessAndWaitForExit(string fileName, string arguments, TimeSpan timeout, out string stdout) { var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false }; var process = Process.Start(startInfo); stdout = null; if (process.WaitForExit((int)timeout.TotalMilliseconds)) { stdout = process.StandardOutput.ReadToEnd(); } else { process.Kill(); } return process.ExitCode; } public static Task StartAndWaitForExitAsync(this Process subject) { var taskCompletionSource = new TaskCompletionSource<object>(); subject.EnableRaisingEvents = true; subject.Exited += (s, a) => { taskCompletionSource.SetResult(null); subject.Dispose(); }; subject.Start(); return taskCompletionSource.Task; } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Private.CoreLib/src/System/StringComparison.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System { public enum StringComparison { CurrentCulture = 0, CurrentCultureIgnoreCase = 1, InvariantCulture = 2, InvariantCultureIgnoreCase = 3, Ordinal = 4, OrdinalIgnoreCase = 5, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System { public enum StringComparison { CurrentCulture = 0, CurrentCultureIgnoreCase = 1, InvariantCulture = 2, InvariantCultureIgnoreCase = 3, Ordinal = 4, OrdinalIgnoreCase = 5, } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/Methodical/MDArray/DataTypes/bool_cs_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="bool.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>None</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="bool.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/ByteConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text.Json.Serialization.Converters { internal sealed class ByteConverter : JsonConverter<byte> { public ByteConverter() { IsInternalConverterForNumberType = true; } public override byte Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetByte(); } public override void Write(Utf8JsonWriter writer, byte value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override byte ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetByteWithQuotes(); } internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, byte value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { writer.WritePropertyName(value); } internal override byte ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetByteWithQuotes(); } return reader.GetByte(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, byte value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue(value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text.Json.Serialization.Converters { internal sealed class ByteConverter : JsonConverter<byte> { public ByteConverter() { IsInternalConverterForNumberType = true; } public override byte Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetByte(); } public override void Write(Utf8JsonWriter writer, byte value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } internal override byte ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return reader.GetByteWithQuotes(); } internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, byte value, JsonSerializerOptions options, bool isWritingExtensionDataProperty) { writer.WritePropertyName(value); } internal override byte ReadNumberWithCustomHandling(ref Utf8JsonReader reader, JsonNumberHandling handling, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String && (JsonNumberHandling.AllowReadingFromString & handling) != 0) { return reader.GetByteWithQuotes(); } return reader.GetByte(); } internal override void WriteNumberWithCustomHandling(Utf8JsonWriter writer, byte value, JsonNumberHandling handling) { if ((JsonNumberHandling.WriteAsString & handling) != 0) { writer.WriteNumberValueAsString(value); } else { writer.WriteNumberValue(value); } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/Avx2_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- It takes a long time to complete (on a non-AVX machine) --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> <!-- https://github.com/dotnet/runtime/issues/12392 --> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="Add.Byte.cs" /> <Compile Include="Add.Int16.cs" /> <Compile Include="Add.Int32.cs" /> <Compile Include="Add.Int64.cs" /> <Compile Include="Add.SByte.cs" /> <Compile Include="Add.UInt16.cs" /> <Compile Include="Add.UInt32.cs" /> <Compile Include="Add.UInt64.cs" /> <Compile Include="AlignRight.SByte.5.cs" /> <Compile Include="AlignRight.SByte.27.cs" /> <Compile Include="AlignRight.SByte.228.cs" /> <Compile Include="AlignRight.SByte.250.cs" /> <Compile Include="AlignRight.Byte.5.cs" /> <Compile Include="AlignRight.Byte.27.cs" /> <Compile Include="AlignRight.Byte.228.cs" /> <Compile Include="AlignRight.Byte.250.cs" /> <Compile Include="AlignRight.Int16.0.cs" /> <Compile Include="AlignRight.Int16.2.cs" /> <Compile Include="AlignRight.UInt16.0.cs" /> <Compile Include="AlignRight.UInt16.2.cs" /> <Compile Include="AlignRight.Int32.0.cs" /> <Compile Include="AlignRight.Int32.4.cs" /> <Compile Include="AlignRight.UInt32.0.cs" /> <Compile Include="AlignRight.UInt32.4.cs" /> <Compile Include="AlignRight.Int64.0.cs" /> <Compile Include="AlignRight.Int64.8.cs" /> <Compile Include="AlignRight.UInt64.0.cs" /> <Compile Include="AlignRight.UInt64.8.cs" /> <Compile Include="And.Byte.cs" /> <Compile Include="And.Int16.cs" /> <Compile Include="And.Int32.cs" /> <Compile Include="And.Int64.cs" /> <Compile Include="And.SByte.cs" /> <Compile Include="And.UInt16.cs" /> <Compile Include="And.UInt32.cs" /> <Compile Include="And.UInt64.cs" /> <Compile Include="AndNot.Byte.cs" /> <Compile Include="AndNot.Int16.cs" /> <Compile Include="AndNot.Int32.cs" /> <Compile Include="AndNot.Int64.cs" /> <Compile Include="AndNot.SByte.cs" /> <Compile Include="AndNot.UInt16.cs" /> <Compile Include="AndNot.UInt32.cs" /> <Compile Include="AndNot.UInt64.cs" /> <Compile Include="Average.Byte.cs" /> <Compile Include="Average.UInt16.cs" /> <Compile Include="Blend.Int16.1.cs" /> <Compile Include="Blend.Int16.2.cs" /> <Compile Include="Blend.Int16.4.cs" /> <Compile Include="Blend.Int16.85.cs" /> <Compile Include="Blend.UInt16.1.cs" /> <Compile Include="Blend.UInt16.2.cs" /> <Compile Include="Blend.UInt16.4.cs" /> <Compile Include="Blend.UInt16.85.cs" /> <Compile Include="Blend.Int32.1.cs" /> <Compile Include="Blend.Int32.2.cs" /> <Compile Include="Blend.Int32.4.cs" /> <Compile Include="Blend.Int32.85.cs" /> <Compile Include="Blend.UInt32.1.cs" /> <Compile Include="Blend.UInt32.2.cs" /> <Compile Include="Blend.UInt32.4.cs" /> <Compile Include="Blend.UInt32.85.cs" /> <Compile Include="BlendVariable.Byte.cs" /> <Compile Include="BlendVariable.SByte.cs" /> <Compile Include="BlendVariable.Int16.cs" /> <Compile Include="BlendVariable.UInt16.cs" /> <Compile Include="BlendVariable.Int32.cs" /> <Compile Include="BlendVariable.UInt32.cs" /> <Compile Include="BlendVariable.Int64.cs" /> <Compile Include="BlendVariable.UInt64.cs" /> <Compile Include="BroadcastScalarToVector128.Byte.cs" /> <Compile Include="BroadcastScalarToVector128.SByte.cs" /> <Compile Include="BroadcastScalarToVector128.Int16.cs" /> <Compile Include="BroadcastScalarToVector128.UInt16.cs" /> <Compile Include="BroadcastScalarToVector128.Int32.cs" /> <Compile Include="BroadcastScalarToVector128.UInt32.cs" /> <Compile Include="BroadcastScalarToVector128.Int64.cs" /> <Compile Include="BroadcastScalarToVector128.UInt64.cs" /> <Compile Include="BroadcastScalarToVector128.Single.cs" /> <Compile Include="BroadcastScalarToVector128.Double.cs" /> <Compile Include="BroadcastScalarToVector256.Byte.cs" /> <Compile Include="BroadcastScalarToVector256.SByte.cs" /> <Compile Include="BroadcastScalarToVector256.Int16.cs" /> <Compile Include="BroadcastScalarToVector256.UInt16.cs" /> <Compile Include="BroadcastScalarToVector256.Int32.cs" /> <Compile Include="BroadcastScalarToVector256.UInt32.cs" /> <Compile Include="BroadcastScalarToVector256.Int64.cs" /> <Compile Include="BroadcastScalarToVector256.UInt64.cs" /> <Compile Include="BroadcastScalarToVector256.Single.cs" /> <Compile Include="BroadcastScalarToVector256.Double.cs" /> <Compile Include="CompareEqual.Byte.cs" /> <Compile Include="CompareEqual.Int16.cs" /> <Compile Include="CompareEqual.Int32.cs" /> <Compile Include="CompareEqual.Int64.cs" /> <Compile Include="CompareEqual.SByte.cs" /> <Compile Include="CompareEqual.UInt16.cs" /> <Compile Include="CompareEqual.UInt32.cs" /> <Compile Include="CompareEqual.UInt64.cs" /> <Compile Include="CompareGreaterThan.Int16.cs" /> <Compile Include="CompareGreaterThan.Int32.cs" /> <Compile Include="CompareGreaterThan.Int64.cs" /> <Compile Include="CompareGreaterThan.SByte.cs" /> <Compile Include="ConvertToInt32.Int32.cs" /> <Compile Include="ConvertToUInt32.UInt32.cs" /> <Compile Include="ExtractVector128.Byte.1.cs" /> <Compile Include="ExtractVector128.SByte.1.cs" /> <Compile Include="ExtractVector128.Int16.1.cs" /> <Compile Include="ExtractVector128.UInt16.1.cs" /> <Compile Include="ExtractVector128.Int32.1.cs" /> <Compile Include="ExtractVector128.UInt32.1.cs" /> <Compile Include="ExtractVector128.Int64.1.cs" /> <Compile Include="ExtractVector128.UInt64.1.cs" /> <Compile Include="InsertVector128.Byte.1.cs" /> <Compile Include="InsertVector128.SByte.1.cs" /> <Compile Include="InsertVector128.Int16.1.cs" /> <Compile Include="InsertVector128.UInt16.1.cs" /> <Compile Include="InsertVector128.Int32.1.cs" /> <Compile Include="InsertVector128.UInt32.1.cs" /> <Compile Include="InsertVector128.Int64.1.cs" /> <Compile Include="InsertVector128.UInt64.1.cs" /> <Compile Include="MaskLoad.Int32.cs" /> <Compile Include="MaskLoad.UInt32.cs" /> <Compile Include="MaskLoad.Int64.cs" /> <Compile Include="MaskLoad.UInt64.cs" /> <Compile Include="MaskStore.Int32.cs" /> <Compile Include="MaskStore.UInt32.cs" /> <Compile Include="MaskStore.Int64.cs" /> <Compile Include="MaskStore.UInt64.cs" /> <Compile Include="Max.Byte.cs" /> <Compile Include="Max.Int16.cs" /> <Compile Include="Max.Int32.cs" /> <Compile Include="Max.SByte.cs" /> <Compile Include="Max.UInt16.cs" /> <Compile Include="Max.UInt32.cs" /> <Compile Include="Min.Byte.cs" /> <Compile Include="Min.Int16.cs" /> <Compile Include="Min.Int32.cs" /> <Compile Include="Min.SByte.cs" /> <Compile Include="Min.UInt16.cs" /> <Compile Include="Min.UInt32.cs" /> <Compile Include="MultiplyAddAdjacent.Int16.cs" /> <Compile Include="MultiplyAddAdjacent.Int32.cs" /> <Compile Include="MultiplyHighRoundScale.Int16.cs" /> <Compile Include="MultiplyHigh.Int16.cs" /> <Compile Include="MultiplyHigh.UInt16.cs" /> <Compile Include="MultiplyLow.Int16.cs" /> <Compile Include="MultiplyLow.Int32.cs" /> <Compile Include="MultiplyLow.UInt16.cs" /> <Compile Include="MultiplyLow.UInt32.cs" /> <Compile Include="MultipleSumAbsoluteDifferences.UInt16.0.cs" /> <Compile Include="Or.Byte.cs" /> <Compile Include="Or.Int16.cs" /> <Compile Include="Or.Int32.cs" /> <Compile Include="Or.Int64.cs" /> <Compile Include="Or.SByte.cs" /> <Compile Include="Or.UInt16.cs" /> <Compile Include="Or.UInt32.cs" /> <Compile Include="Or.UInt64.cs" /> <Compile Include="PackUnsignedSaturate.UInt16.cs" /> <Compile Include="PackUnsignedSaturate.Byte.cs" /> <Compile Include="PackSignedSaturate.Int16.cs" /> <Compile Include="PackSignedSaturate.SByte.cs" /> <Compile Include="Permute2x128.Int32.2.cs" /> <Compile Include="Permute2x128.UInt32.2.cs" /> <Compile Include="Permute2x128.Int64.2.cs" /> <Compile Include="Permute2x128.UInt64.2.cs" /> <Compile Include="Permute4x64.Double.85.cs" /> <Compile Include="Permute4x64.Int64.85.cs" /> <Compile Include="Permute4x64.UInt64.85.cs" /> <Compile Include="PermuteVar8x32.Int32.cs" /> <Compile Include="PermuteVar8x32.UInt32.cs" /> <Compile Include="PermuteVar8x32.Single.cs" /> <Compile Include="ShiftLeftLogical.Int16.1.cs" /> <Compile Include="ShiftLeftLogical.UInt16.1.cs" /> <Compile Include="ShiftLeftLogical.Int32.1.cs" /> <Compile Include="ShiftLeftLogical.UInt32.1.cs" /> <Compile Include="ShiftLeftLogical.Int64.1.cs" /> <Compile Include="ShiftLeftLogical.UInt64.1.cs" /> <Compile Include="ShiftLeftLogical.Int16.16.cs" /> <Compile Include="ShiftLeftLogical.UInt16.16.cs" /> <Compile Include="ShiftLeftLogical.Int32.32.cs" /> <Compile Include="ShiftLeftLogical.UInt32.32.cs" /> <Compile Include="ShiftLeftLogical.Int64.64.cs" /> <Compile Include="ShiftLeftLogical.UInt64.64.cs" /> <Compile Include="ShiftRightLogical.Int16.1.cs" /> <Compile Include="ShiftRightLogical.UInt16.1.cs" /> <Compile Include="ShiftRightLogical.Int32.1.cs" /> <Compile Include="ShiftRightLogical.UInt32.1.cs" /> <Compile Include="ShiftRightLogical.Int64.1.cs" /> <Compile Include="ShiftRightLogical.UInt64.1.cs" /> <Compile Include="ShiftRightLogical.Int16.16.cs" /> <Compile Include="ShiftRightLogical.UInt16.16.cs" /> <Compile Include="ShiftRightLogical.Int32.32.cs" /> <Compile Include="ShiftRightLogical.UInt32.32.cs" /> <Compile Include="ShiftRightLogical.Int64.64.cs" /> <Compile Include="ShiftRightLogical.UInt64.64.cs" /> <Compile Include="ShiftRightArithmetic.Int16.1.cs" /> <Compile Include="ShiftRightArithmetic.Int32.1.cs" /> <Compile Include="ShiftRightArithmetic.Int16.16.cs" /> <Compile Include="ShiftRightArithmetic.Int32.32.cs" /> <Compile Include="ShiftRightArithmeticVariable.Int32.cs" /> <Compile Include="ShiftLeftLogical128BitLane.SByte.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.Byte.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.Int16.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.UInt16.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.Int32.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.UInt32.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.Int64.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.UInt64.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.SByte.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.Byte.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.Int16.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.UInt16.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.Int32.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.UInt32.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.Int64.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.UInt64.1.cs" /> <Compile Include="Sign.SByte.cs" /> <Compile Include="Sign.Int16.cs" /> <Compile Include="Sign.Int32.cs" /> <Compile Include="Shuffle.SByte.cs" /> <Compile Include="Shuffle.Byte.cs" /> <Compile Include="Shuffle.Int32.1.cs" /> <Compile Include="Shuffle.UInt32.1.cs" /> <Compile Include="ShuffleHigh.Int16.228.cs" /> <Compile Include="ShuffleHigh.UInt16.228.cs" /> <Compile Include="ShuffleLow.Int16.228.cs" /> <Compile Include="ShuffleLow.UInt16.228.cs" /> <Compile Include="SumAbsoluteDifferences.UInt16.cs" /> <Compile Include="Subtract.Byte.cs" /> <Compile Include="Subtract.Int16.cs" /> <Compile Include="Subtract.Int32.cs" /> <Compile Include="Subtract.Int64.cs" /> <Compile Include="Subtract.SByte.cs" /> <Compile Include="Subtract.UInt16.cs" /> <Compile Include="Subtract.UInt32.cs" /> <Compile Include="Subtract.UInt64.cs" /> <Compile Include="Xor.Byte.cs" /> <Compile Include="Xor.Int16.cs" /> <Compile Include="Xor.Int32.cs" /> <Compile Include="Xor.Int64.cs" /> <Compile Include="Xor.SByte.cs" /> <Compile Include="Xor.UInt16.cs" /> <Compile Include="Xor.UInt32.cs" /> <Compile Include="Xor.UInt64.cs" /> <Compile Include="Program.Avx2.cs" /> <Compile Include="..\Shared\Program.cs" /> <Compile Include="..\Shared\SimdScalarUnOpTest_DataTable.cs" /> <Compile Include="..\Shared\SimpleBinOpTest_DataTable.cs" /> <Compile Include="..\Shared\SimpleUnOpTest_DataTable.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- It takes a long time to complete (on a non-AVX machine) --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> <!-- https://github.com/dotnet/runtime/issues/12392 --> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize /> </PropertyGroup> <ItemGroup> <Compile Include="Add.Byte.cs" /> <Compile Include="Add.Int16.cs" /> <Compile Include="Add.Int32.cs" /> <Compile Include="Add.Int64.cs" /> <Compile Include="Add.SByte.cs" /> <Compile Include="Add.UInt16.cs" /> <Compile Include="Add.UInt32.cs" /> <Compile Include="Add.UInt64.cs" /> <Compile Include="AlignRight.SByte.5.cs" /> <Compile Include="AlignRight.SByte.27.cs" /> <Compile Include="AlignRight.SByte.228.cs" /> <Compile Include="AlignRight.SByte.250.cs" /> <Compile Include="AlignRight.Byte.5.cs" /> <Compile Include="AlignRight.Byte.27.cs" /> <Compile Include="AlignRight.Byte.228.cs" /> <Compile Include="AlignRight.Byte.250.cs" /> <Compile Include="AlignRight.Int16.0.cs" /> <Compile Include="AlignRight.Int16.2.cs" /> <Compile Include="AlignRight.UInt16.0.cs" /> <Compile Include="AlignRight.UInt16.2.cs" /> <Compile Include="AlignRight.Int32.0.cs" /> <Compile Include="AlignRight.Int32.4.cs" /> <Compile Include="AlignRight.UInt32.0.cs" /> <Compile Include="AlignRight.UInt32.4.cs" /> <Compile Include="AlignRight.Int64.0.cs" /> <Compile Include="AlignRight.Int64.8.cs" /> <Compile Include="AlignRight.UInt64.0.cs" /> <Compile Include="AlignRight.UInt64.8.cs" /> <Compile Include="And.Byte.cs" /> <Compile Include="And.Int16.cs" /> <Compile Include="And.Int32.cs" /> <Compile Include="And.Int64.cs" /> <Compile Include="And.SByte.cs" /> <Compile Include="And.UInt16.cs" /> <Compile Include="And.UInt32.cs" /> <Compile Include="And.UInt64.cs" /> <Compile Include="AndNot.Byte.cs" /> <Compile Include="AndNot.Int16.cs" /> <Compile Include="AndNot.Int32.cs" /> <Compile Include="AndNot.Int64.cs" /> <Compile Include="AndNot.SByte.cs" /> <Compile Include="AndNot.UInt16.cs" /> <Compile Include="AndNot.UInt32.cs" /> <Compile Include="AndNot.UInt64.cs" /> <Compile Include="Average.Byte.cs" /> <Compile Include="Average.UInt16.cs" /> <Compile Include="Blend.Int16.1.cs" /> <Compile Include="Blend.Int16.2.cs" /> <Compile Include="Blend.Int16.4.cs" /> <Compile Include="Blend.Int16.85.cs" /> <Compile Include="Blend.UInt16.1.cs" /> <Compile Include="Blend.UInt16.2.cs" /> <Compile Include="Blend.UInt16.4.cs" /> <Compile Include="Blend.UInt16.85.cs" /> <Compile Include="Blend.Int32.1.cs" /> <Compile Include="Blend.Int32.2.cs" /> <Compile Include="Blend.Int32.4.cs" /> <Compile Include="Blend.Int32.85.cs" /> <Compile Include="Blend.UInt32.1.cs" /> <Compile Include="Blend.UInt32.2.cs" /> <Compile Include="Blend.UInt32.4.cs" /> <Compile Include="Blend.UInt32.85.cs" /> <Compile Include="BlendVariable.Byte.cs" /> <Compile Include="BlendVariable.SByte.cs" /> <Compile Include="BlendVariable.Int16.cs" /> <Compile Include="BlendVariable.UInt16.cs" /> <Compile Include="BlendVariable.Int32.cs" /> <Compile Include="BlendVariable.UInt32.cs" /> <Compile Include="BlendVariable.Int64.cs" /> <Compile Include="BlendVariable.UInt64.cs" /> <Compile Include="BroadcastScalarToVector128.Byte.cs" /> <Compile Include="BroadcastScalarToVector128.SByte.cs" /> <Compile Include="BroadcastScalarToVector128.Int16.cs" /> <Compile Include="BroadcastScalarToVector128.UInt16.cs" /> <Compile Include="BroadcastScalarToVector128.Int32.cs" /> <Compile Include="BroadcastScalarToVector128.UInt32.cs" /> <Compile Include="BroadcastScalarToVector128.Int64.cs" /> <Compile Include="BroadcastScalarToVector128.UInt64.cs" /> <Compile Include="BroadcastScalarToVector128.Single.cs" /> <Compile Include="BroadcastScalarToVector128.Double.cs" /> <Compile Include="BroadcastScalarToVector256.Byte.cs" /> <Compile Include="BroadcastScalarToVector256.SByte.cs" /> <Compile Include="BroadcastScalarToVector256.Int16.cs" /> <Compile Include="BroadcastScalarToVector256.UInt16.cs" /> <Compile Include="BroadcastScalarToVector256.Int32.cs" /> <Compile Include="BroadcastScalarToVector256.UInt32.cs" /> <Compile Include="BroadcastScalarToVector256.Int64.cs" /> <Compile Include="BroadcastScalarToVector256.UInt64.cs" /> <Compile Include="BroadcastScalarToVector256.Single.cs" /> <Compile Include="BroadcastScalarToVector256.Double.cs" /> <Compile Include="CompareEqual.Byte.cs" /> <Compile Include="CompareEqual.Int16.cs" /> <Compile Include="CompareEqual.Int32.cs" /> <Compile Include="CompareEqual.Int64.cs" /> <Compile Include="CompareEqual.SByte.cs" /> <Compile Include="CompareEqual.UInt16.cs" /> <Compile Include="CompareEqual.UInt32.cs" /> <Compile Include="CompareEqual.UInt64.cs" /> <Compile Include="CompareGreaterThan.Int16.cs" /> <Compile Include="CompareGreaterThan.Int32.cs" /> <Compile Include="CompareGreaterThan.Int64.cs" /> <Compile Include="CompareGreaterThan.SByte.cs" /> <Compile Include="ConvertToInt32.Int32.cs" /> <Compile Include="ConvertToUInt32.UInt32.cs" /> <Compile Include="ExtractVector128.Byte.1.cs" /> <Compile Include="ExtractVector128.SByte.1.cs" /> <Compile Include="ExtractVector128.Int16.1.cs" /> <Compile Include="ExtractVector128.UInt16.1.cs" /> <Compile Include="ExtractVector128.Int32.1.cs" /> <Compile Include="ExtractVector128.UInt32.1.cs" /> <Compile Include="ExtractVector128.Int64.1.cs" /> <Compile Include="ExtractVector128.UInt64.1.cs" /> <Compile Include="InsertVector128.Byte.1.cs" /> <Compile Include="InsertVector128.SByte.1.cs" /> <Compile Include="InsertVector128.Int16.1.cs" /> <Compile Include="InsertVector128.UInt16.1.cs" /> <Compile Include="InsertVector128.Int32.1.cs" /> <Compile Include="InsertVector128.UInt32.1.cs" /> <Compile Include="InsertVector128.Int64.1.cs" /> <Compile Include="InsertVector128.UInt64.1.cs" /> <Compile Include="MaskLoad.Int32.cs" /> <Compile Include="MaskLoad.UInt32.cs" /> <Compile Include="MaskLoad.Int64.cs" /> <Compile Include="MaskLoad.UInt64.cs" /> <Compile Include="MaskStore.Int32.cs" /> <Compile Include="MaskStore.UInt32.cs" /> <Compile Include="MaskStore.Int64.cs" /> <Compile Include="MaskStore.UInt64.cs" /> <Compile Include="Max.Byte.cs" /> <Compile Include="Max.Int16.cs" /> <Compile Include="Max.Int32.cs" /> <Compile Include="Max.SByte.cs" /> <Compile Include="Max.UInt16.cs" /> <Compile Include="Max.UInt32.cs" /> <Compile Include="Min.Byte.cs" /> <Compile Include="Min.Int16.cs" /> <Compile Include="Min.Int32.cs" /> <Compile Include="Min.SByte.cs" /> <Compile Include="Min.UInt16.cs" /> <Compile Include="Min.UInt32.cs" /> <Compile Include="MultiplyAddAdjacent.Int16.cs" /> <Compile Include="MultiplyAddAdjacent.Int32.cs" /> <Compile Include="MultiplyHighRoundScale.Int16.cs" /> <Compile Include="MultiplyHigh.Int16.cs" /> <Compile Include="MultiplyHigh.UInt16.cs" /> <Compile Include="MultiplyLow.Int16.cs" /> <Compile Include="MultiplyLow.Int32.cs" /> <Compile Include="MultiplyLow.UInt16.cs" /> <Compile Include="MultiplyLow.UInt32.cs" /> <Compile Include="MultipleSumAbsoluteDifferences.UInt16.0.cs" /> <Compile Include="Or.Byte.cs" /> <Compile Include="Or.Int16.cs" /> <Compile Include="Or.Int32.cs" /> <Compile Include="Or.Int64.cs" /> <Compile Include="Or.SByte.cs" /> <Compile Include="Or.UInt16.cs" /> <Compile Include="Or.UInt32.cs" /> <Compile Include="Or.UInt64.cs" /> <Compile Include="PackUnsignedSaturate.UInt16.cs" /> <Compile Include="PackUnsignedSaturate.Byte.cs" /> <Compile Include="PackSignedSaturate.Int16.cs" /> <Compile Include="PackSignedSaturate.SByte.cs" /> <Compile Include="Permute2x128.Int32.2.cs" /> <Compile Include="Permute2x128.UInt32.2.cs" /> <Compile Include="Permute2x128.Int64.2.cs" /> <Compile Include="Permute2x128.UInt64.2.cs" /> <Compile Include="Permute4x64.Double.85.cs" /> <Compile Include="Permute4x64.Int64.85.cs" /> <Compile Include="Permute4x64.UInt64.85.cs" /> <Compile Include="PermuteVar8x32.Int32.cs" /> <Compile Include="PermuteVar8x32.UInt32.cs" /> <Compile Include="PermuteVar8x32.Single.cs" /> <Compile Include="ShiftLeftLogical.Int16.1.cs" /> <Compile Include="ShiftLeftLogical.UInt16.1.cs" /> <Compile Include="ShiftLeftLogical.Int32.1.cs" /> <Compile Include="ShiftLeftLogical.UInt32.1.cs" /> <Compile Include="ShiftLeftLogical.Int64.1.cs" /> <Compile Include="ShiftLeftLogical.UInt64.1.cs" /> <Compile Include="ShiftLeftLogical.Int16.16.cs" /> <Compile Include="ShiftLeftLogical.UInt16.16.cs" /> <Compile Include="ShiftLeftLogical.Int32.32.cs" /> <Compile Include="ShiftLeftLogical.UInt32.32.cs" /> <Compile Include="ShiftLeftLogical.Int64.64.cs" /> <Compile Include="ShiftLeftLogical.UInt64.64.cs" /> <Compile Include="ShiftRightLogical.Int16.1.cs" /> <Compile Include="ShiftRightLogical.UInt16.1.cs" /> <Compile Include="ShiftRightLogical.Int32.1.cs" /> <Compile Include="ShiftRightLogical.UInt32.1.cs" /> <Compile Include="ShiftRightLogical.Int64.1.cs" /> <Compile Include="ShiftRightLogical.UInt64.1.cs" /> <Compile Include="ShiftRightLogical.Int16.16.cs" /> <Compile Include="ShiftRightLogical.UInt16.16.cs" /> <Compile Include="ShiftRightLogical.Int32.32.cs" /> <Compile Include="ShiftRightLogical.UInt32.32.cs" /> <Compile Include="ShiftRightLogical.Int64.64.cs" /> <Compile Include="ShiftRightLogical.UInt64.64.cs" /> <Compile Include="ShiftRightArithmetic.Int16.1.cs" /> <Compile Include="ShiftRightArithmetic.Int32.1.cs" /> <Compile Include="ShiftRightArithmetic.Int16.16.cs" /> <Compile Include="ShiftRightArithmetic.Int32.32.cs" /> <Compile Include="ShiftRightArithmeticVariable.Int32.cs" /> <Compile Include="ShiftLeftLogical128BitLane.SByte.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.Byte.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.Int16.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.UInt16.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.Int32.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.UInt32.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.Int64.1.cs" /> <Compile Include="ShiftLeftLogical128BitLane.UInt64.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.SByte.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.Byte.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.Int16.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.UInt16.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.Int32.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.UInt32.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.Int64.1.cs" /> <Compile Include="ShiftRightLogical128BitLane.UInt64.1.cs" /> <Compile Include="Sign.SByte.cs" /> <Compile Include="Sign.Int16.cs" /> <Compile Include="Sign.Int32.cs" /> <Compile Include="Shuffle.SByte.cs" /> <Compile Include="Shuffle.Byte.cs" /> <Compile Include="Shuffle.Int32.1.cs" /> <Compile Include="Shuffle.UInt32.1.cs" /> <Compile Include="ShuffleHigh.Int16.228.cs" /> <Compile Include="ShuffleHigh.UInt16.228.cs" /> <Compile Include="ShuffleLow.Int16.228.cs" /> <Compile Include="ShuffleLow.UInt16.228.cs" /> <Compile Include="SumAbsoluteDifferences.UInt16.cs" /> <Compile Include="Subtract.Byte.cs" /> <Compile Include="Subtract.Int16.cs" /> <Compile Include="Subtract.Int32.cs" /> <Compile Include="Subtract.Int64.cs" /> <Compile Include="Subtract.SByte.cs" /> <Compile Include="Subtract.UInt16.cs" /> <Compile Include="Subtract.UInt32.cs" /> <Compile Include="Subtract.UInt64.cs" /> <Compile Include="Xor.Byte.cs" /> <Compile Include="Xor.Int16.cs" /> <Compile Include="Xor.Int32.cs" /> <Compile Include="Xor.Int64.cs" /> <Compile Include="Xor.SByte.cs" /> <Compile Include="Xor.UInt16.cs" /> <Compile Include="Xor.UInt32.cs" /> <Compile Include="Xor.UInt64.cs" /> <Compile Include="Program.Avx2.cs" /> <Compile Include="..\Shared\Program.cs" /> <Compile Include="..\Shared\SimdScalarUnOpTest_DataTable.cs" /> <Compile Include="..\Shared\SimpleBinOpTest_DataTable.cs" /> <Compile Include="..\Shared\SimpleUnOpTest_DataTable.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/GC/Scenarios/FinalNStruct/nstructresur.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="nstructresur.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="strmap.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <GCStressIncompatible>true</GCStressIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="nstructresur.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="strmap.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/InsertSelectedScalar.Vector64.Int32.1.Vector128.Int32.3.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3() { var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3 testClass) { var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)pFld1), 1, AdvSimd.LoadVector128((Int32*)pFld2), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly byte ElementIndex1 = 1; private static readonly byte ElementIndex2 = 3; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int32> _clsVar3; private Vector64<Int32> _fld1; private Vector128<Int32> _fld3; private DataTable _dataTable; static InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.InsertSelectedScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), 1, Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), 1, AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(byte), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), ElementIndex1, Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(byte), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), ElementIndex1, AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar( _clsVar1, 1, _clsVar3, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar3 = &_clsVar3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), 1, AdvSimd.LoadVector128((Int32*)(pClsVar3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)pFld1), 1, AdvSimd.LoadVector128((Int32*)pFld2), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)pFld1), 1, AdvSimd.LoadVector128((Int32*)pFld2), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), 1, AdvSimd.LoadVector128((Int32*)(&test._fld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<Int32>(Vector64<Int32>, {1}, Vector128<Int32>, {3}): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3() { var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld1; public Vector128<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3 testClass) { var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3 testClass) { fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)pFld1), 1, AdvSimd.LoadVector128((Int32*)pFld2), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly byte ElementIndex1 = 1; private static readonly byte ElementIndex2 = 3; private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector64<Int32> _clsVar1; private static Vector128<Int32> _clsVar3; private Vector64<Int32> _fld1; private Vector128<Int32> _fld3; private DataTable _dataTable; static InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.InsertSelectedScalar( Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), 1, Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), 1, AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(byte), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr), ElementIndex1, Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector64<Int32>), typeof(byte), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)), ElementIndex1, AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar( _clsVar1, 1, _clsVar3, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar3 = &_clsVar3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)(pClsVar1)), 1, AdvSimd.LoadVector128((Int32*)(pClsVar3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int32>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int32*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 1, op3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector64_Int32_1_Vector128_Int32_3(); fixed (Vector64<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)pFld1), 1, AdvSimd.LoadVector128((Int32*)pFld2), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 1, _fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)pFld1), 1, AdvSimd.LoadVector128((Int32*)pFld2), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 1, test._fld3, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector64((Int32*)(&test._fld1)), 1, AdvSimd.LoadVector128((Int32*)(&test._fld3)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> op1, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<Int32>(Vector64<Int32>, {1}, Vector128<Int32>, {3}): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/coreclr/tools/Common/TypeSystem/RuntimeDetermined/FunctionPointerType.RuntimeDetermined.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem { partial class FunctionPointerType { public override bool IsRuntimeDeterminedSubtype { get { if (_signature.ReturnType.IsRuntimeDeterminedSubtype) return true; for (int i = 0; i < _signature.Length; i++) if (_signature[i].IsRuntimeDeterminedSubtype) return true; return false; } } public override TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation) { Debug.Assert(false); return this; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem { partial class FunctionPointerType { public override bool IsRuntimeDeterminedSubtype { get { if (_signature.ReturnType.IsRuntimeDeterminedSubtype) return true; for (int i = 0; i < _signature.Length; i++) if (_signature[i].IsRuntimeDeterminedSubtype) return true; return false; } } public override TypeDesc GetNonRuntimeDeterminedTypeFromRuntimeDeterminedSubtypeViaSubstitution(Instantiation typeInstantiation, Instantiation methodInstantiation) { Debug.Assert(false); return this; } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Composition.Hosting/src/System.Composition.Hosting.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <IsTrimmable>false</IsTrimmable> <IsPackable>true</IsPackable> <StrongNameKeyId>Microsoft</StrongNameKeyId> <PackageDescription>Provides Managed Extensibility Framework types that are useful to developers of extensible applications, or hosts. Commonly Used Types: System.Composition.Hosting.CompositionHost</PackageDescription> </PropertyGroup> <ItemGroup> <Compile Include="System\Composition\Hosting\CompositionHost.cs" /> <Compile Include="System\Composition\Hosting\Core\CompositeActivator.cs" /> <Compile Include="System\Composition\Hosting\Core\CompositionDependency.cs" /> <Compile Include="System\Composition\Hosting\Core\CompositionOperation.cs" /> <Compile Include="System\Composition\Hosting\Core\CycleBreakingExportDescriptor.cs" /> <Compile Include="System\Composition\Hosting\Core\CycleBreakingMetadataDictionary.cs" /> <Compile Include="System\Composition\Hosting\Core\DependencyAccessor.cs" /> <Compile Include="System\Composition\Hosting\Core\DirectExportDescriptor.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptor.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptorPromise.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptorRegistry.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptorRegistryUpdate.cs" /> <Compile Include="System\Composition\Hosting\Core\LifetimeContext.cs" /> <Compile Include="System\Composition\Hosting\Core\UpdateResult.cs" /> <Compile Include="System\Composition\Hosting\Providers\Constants.cs" /> <Compile Include="System\Composition\Hosting\Providers\CurrentScope\CurrentScopeExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\ExportFactory\ExportFactoryExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\ExportFactory\ExportFactoryWithMetadataExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\ImportMany\ImportManyExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\Lazy\LazyExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\Lazy\LazyWithMetadataExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\Metadata\MetadataViewProvider.cs" /> <Compile Include="System\Composition\Hosting\Util\Formatters.cs" /> <Compile Include="System\Composition\Hosting\Util\MethodInfoExtensions.cs" /> <Compile Include="System\Composition\Hosting\Util\SmallSparseInitonlyArray.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)System.Composition.Runtime\src\System.Composition.Runtime.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <Reference Include="System.Collections" /> <Reference Include="System.Linq" /> <Reference Include="System.Linq.Expressions" /> <Reference Include="System.ObjectModel" /> <Reference Include="System.Runtime" /> <Reference Include="System.Threading" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <Reference Include="System.ComponentModel.Composition" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <IsTrimmable>false</IsTrimmable> <IsPackable>true</IsPackable> <StrongNameKeyId>Microsoft</StrongNameKeyId> <PackageDescription>Provides Managed Extensibility Framework types that are useful to developers of extensible applications, or hosts. Commonly Used Types: System.Composition.Hosting.CompositionHost</PackageDescription> </PropertyGroup> <ItemGroup> <Compile Include="System\Composition\Hosting\CompositionHost.cs" /> <Compile Include="System\Composition\Hosting\Core\CompositeActivator.cs" /> <Compile Include="System\Composition\Hosting\Core\CompositionDependency.cs" /> <Compile Include="System\Composition\Hosting\Core\CompositionOperation.cs" /> <Compile Include="System\Composition\Hosting\Core\CycleBreakingExportDescriptor.cs" /> <Compile Include="System\Composition\Hosting\Core\CycleBreakingMetadataDictionary.cs" /> <Compile Include="System\Composition\Hosting\Core\DependencyAccessor.cs" /> <Compile Include="System\Composition\Hosting\Core\DirectExportDescriptor.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptor.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptorPromise.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptorRegistry.cs" /> <Compile Include="System\Composition\Hosting\Core\ExportDescriptorRegistryUpdate.cs" /> <Compile Include="System\Composition\Hosting\Core\LifetimeContext.cs" /> <Compile Include="System\Composition\Hosting\Core\UpdateResult.cs" /> <Compile Include="System\Composition\Hosting\Providers\Constants.cs" /> <Compile Include="System\Composition\Hosting\Providers\CurrentScope\CurrentScopeExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\ExportFactory\ExportFactoryExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\ExportFactory\ExportFactoryWithMetadataExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\ImportMany\ImportManyExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\Lazy\LazyExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\Lazy\LazyWithMetadataExportDescriptorProvider.cs" /> <Compile Include="System\Composition\Hosting\Providers\Metadata\MetadataViewProvider.cs" /> <Compile Include="System\Composition\Hosting\Util\Formatters.cs" /> <Compile Include="System\Composition\Hosting\Util\MethodInfoExtensions.cs" /> <Compile Include="System\Composition\Hosting\Util\SmallSparseInitonlyArray.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="$(LibrariesProjectRoot)System.Composition.Runtime\src\System.Composition.Runtime.csproj" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'"> <Reference Include="System.Collections" /> <Reference Include="System.Linq" /> <Reference Include="System.Linq.Expressions" /> <Reference Include="System.ObjectModel" /> <Reference Include="System.Runtime" /> <Reference Include="System.Threading" /> </ItemGroup> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <Reference Include="System.ComponentModel.Composition" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/Methodical/VT/etc/knight_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="knight.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="knight.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Private.CoreLib/src/System/Collections/IEqualityComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Collections { // An IEqualityComparer is a mechanism to consume custom performant comparison infrastructure // that can be consumed by some of the common collections. public interface IEqualityComparer { bool Equals(object? x, object? y); int GetHashCode(object obj); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Collections { // An IEqualityComparer is a mechanism to consume custom performant comparison infrastructure // that can be consumed by some of the common collections. public interface IEqualityComparer { bool Equals(object? x, object? y); int GetHashCode(object obj); } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/Interop/NativeLibrary/API/NativeLibraryTests.cs
// 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.Reflection; using System.Runtime.InteropServices; using Xunit; using static TestHelpers; public class NativeLibraryTests : IDisposable { private readonly Assembly assembly; private readonly string testBinDir; private readonly string libFullPath; public NativeLibraryTests() { assembly = System.Reflection.Assembly.GetExecutingAssembly(); testBinDir = Path.GetDirectoryName(assembly.Location); libFullPath = NativeLibraryToLoad.GetFullPath(); } [Fact] public void LoadLibraryFullPath_NameOnly() { string libName = libFullPath; EXPECT(LoadLibrary_NameOnly(libName)); EXPECT(TryLoadLibrary_NameOnly(libName)); } [Fact] public void LoadLibraryOnNonExistentFile_NameOnly() { string libName = Path.Combine(testBinDir, "notfound"); EXPECT(LoadLibrary_NameOnly(libName), TestResult.DllNotFound); EXPECT(TryLoadLibrary_NameOnly(libName), TestResult.ReturnFailure); } [Fact] public void LoadLibraryOnInvalidFile_NameOnly() { string libName = Path.Combine(testBinDir, "NativeLibrary.cpp"); EXPECT(LoadLibrary_NameOnly(libName), OperatingSystem.IsWindows() ? TestResult.BadImage : TestResult.DllNotFound); EXPECT(TryLoadLibrary_NameOnly(libName), TestResult.ReturnFailure); } [Fact] public void LoadLibraryFullPath_WithAssembly() { string libName = libFullPath; EXPECT(LoadLibrary_WithAssembly(libName, assembly, null)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null)); } [Fact] public void LoadLibraryOnNonExistentFile_WithAssembly() { string libName = Path.Combine(testBinDir, "notfound"); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null), TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null), TestResult.ReturnFailure); } [Fact] public void LoadLibraryOnInvalidFile_WithAssembly() { string libName = Path.Combine(testBinDir, "NativeLibrary.cpp"); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null), OperatingSystem.IsWindows() ? TestResult.BadImage : TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null), TestResult.ReturnFailure); } [Fact] public void LoadLibraryNameOnly_WithAssembly() { string libName = NativeLibraryToLoad.Name; EXPECT(LoadLibrary_WithAssembly(libName, assembly, null)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null)); } [Fact] public void LoadLibraryFileName_WithAssembly() { string libName = NativeLibraryToLoad.GetFileName(); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void LoadLibraryFullPathWithoutNativePrefixOrSuffix_WithAssembly_Success() { // DllImport doesn't add a prefix if the name is preceeded by a path specification. // Windows only needs a suffix, so adding only the suffix is successful string libName = Path.Combine(testBinDir, NativeLibraryToLoad.Name); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null)); } [Fact] [PlatformSpecific(~TestPlatforms.Windows)] public void LoadLibraryFullPathWithoutNativePrefixOrSuffix_WithAssembly_Failure() { // DllImport doesn't add a prefix if the name is preceeded by a path specification. // Linux and Mac need both prefix and suffix string libName = Path.Combine(testBinDir, NativeLibraryToLoad.Name); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null), TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null), TestResult.ReturnFailure); } public static bool HasKnownLibraryInSystemDirectory => OperatingSystem.IsWindows() && File.Exists(Path.Combine(Environment.SystemDirectory, "url.dll")); [ConditionalFact(nameof(HasKnownLibraryInSystemDirectory))] public void LoadSystemLibrary_WithSearchPath() { string libName = "url.dll"; // Calls on a valid library from System32 directory EXPECT(LoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.System32)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.System32)); // Calls on a valid library from application directory EXPECT(LoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.ApplicationDirectory), TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.ApplicationDirectory), TestResult.ReturnFailure); } [Fact] public void LoadLibrary_NullLibName() { EXPECT(LoadLibrary_WithAssembly(null, assembly, null), TestResult.ArgumentNull); EXPECT(TryLoadLibrary_WithAssembly(null, assembly, null), TestResult.ArgumentNull); } [Fact] public void LoadLibrary_NullAssembly() { string libName = NativeLibraryToLoad.Name; EXPECT(LoadLibrary_WithAssembly(libName, null, null), TestResult.ArgumentNull); EXPECT(TryLoadLibrary_WithAssembly(libName, null, null), TestResult.ArgumentNull); } [Fact] public void LoadLibary_UsesFullPath_EvenWhen_AssemblyDirectory_Specified() { string libName = Path.Combine(testBinDir, Path.Combine("lib", NativeLibraryToLoad.Name)); EXPECT(LoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.AssemblyDirectory), TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.AssemblyDirectory), TestResult.ReturnFailure); } [Fact] public void Free() { string libName = libFullPath; IntPtr handle = NativeLibrary.Load(libName); // Valid Free EXPECT(FreeLibrary(handle)); // Double Free if (OperatingSystem.IsWindows()) { // The FreeLibrary() implementation simply calls the appropriate OS API // with the supplied handle. Not all OSes consistently return an error // when a library is double-freed. EXPECT(FreeLibrary(handle), TestResult.InvalidOperation); } // Null Free EXPECT(FreeLibrary(IntPtr.Zero)); } public void Dispose() {} static TestResult LoadLibrary_NameOnly(string libPath) { IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { handle = NativeLibrary.Load(libPath); if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult TryLoadLibrary_NameOnly(string libPath) { IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { bool success = NativeLibrary.TryLoad(libPath, out handle); if (!success) return TestResult.ReturnFailure; if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult LoadLibrary_WithAssembly(string libName, Assembly assembly, DllImportSearchPath? searchPath) { IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { handle = NativeLibrary.Load(libName, assembly, searchPath); if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult TryLoadLibrary_WithAssembly(string libName, Assembly assembly, DllImportSearchPath? searchPath) { IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { bool success = NativeLibrary.TryLoad(libName, assembly, searchPath, out handle); if (!success) return TestResult.ReturnFailure; if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult FreeLibrary(IntPtr handle) { return Run(() => { NativeLibrary.Free(handle); return TestResult.Success; }); } }
// 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.Reflection; using System.Runtime.InteropServices; using Xunit; using static TestHelpers; public class NativeLibraryTests : IDisposable { private readonly Assembly assembly; private readonly string testBinDir; private readonly string libFullPath; public NativeLibraryTests() { assembly = System.Reflection.Assembly.GetExecutingAssembly(); testBinDir = Path.GetDirectoryName(assembly.Location); libFullPath = NativeLibraryToLoad.GetFullPath(); } [Fact] public void LoadLibraryFullPath_NameOnly() { string libName = libFullPath; EXPECT(LoadLibrary_NameOnly(libName)); EXPECT(TryLoadLibrary_NameOnly(libName)); } [Fact] public void LoadLibraryOnNonExistentFile_NameOnly() { string libName = Path.Combine(testBinDir, "notfound"); EXPECT(LoadLibrary_NameOnly(libName), TestResult.DllNotFound); EXPECT(TryLoadLibrary_NameOnly(libName), TestResult.ReturnFailure); } [Fact] public void LoadLibraryOnInvalidFile_NameOnly() { string libName = Path.Combine(testBinDir, "NativeLibrary.cpp"); EXPECT(LoadLibrary_NameOnly(libName), OperatingSystem.IsWindows() ? TestResult.BadImage : TestResult.DllNotFound); EXPECT(TryLoadLibrary_NameOnly(libName), TestResult.ReturnFailure); } [Fact] public void LoadLibraryFullPath_WithAssembly() { string libName = libFullPath; EXPECT(LoadLibrary_WithAssembly(libName, assembly, null)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null)); } [Fact] public void LoadLibraryOnNonExistentFile_WithAssembly() { string libName = Path.Combine(testBinDir, "notfound"); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null), TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null), TestResult.ReturnFailure); } [Fact] public void LoadLibraryOnInvalidFile_WithAssembly() { string libName = Path.Combine(testBinDir, "NativeLibrary.cpp"); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null), OperatingSystem.IsWindows() ? TestResult.BadImage : TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null), TestResult.ReturnFailure); } [Fact] public void LoadLibraryNameOnly_WithAssembly() { string libName = NativeLibraryToLoad.Name; EXPECT(LoadLibrary_WithAssembly(libName, assembly, null)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null)); } [Fact] public void LoadLibraryFileName_WithAssembly() { string libName = NativeLibraryToLoad.GetFileName(); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void LoadLibraryFullPathWithoutNativePrefixOrSuffix_WithAssembly_Success() { // DllImport doesn't add a prefix if the name is preceeded by a path specification. // Windows only needs a suffix, so adding only the suffix is successful string libName = Path.Combine(testBinDir, NativeLibraryToLoad.Name); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null)); } [Fact] [PlatformSpecific(~TestPlatforms.Windows)] public void LoadLibraryFullPathWithoutNativePrefixOrSuffix_WithAssembly_Failure() { // DllImport doesn't add a prefix if the name is preceeded by a path specification. // Linux and Mac need both prefix and suffix string libName = Path.Combine(testBinDir, NativeLibraryToLoad.Name); EXPECT(LoadLibrary_WithAssembly(libName, assembly, null), TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, null), TestResult.ReturnFailure); } public static bool HasKnownLibraryInSystemDirectory => OperatingSystem.IsWindows() && File.Exists(Path.Combine(Environment.SystemDirectory, "url.dll")); [ConditionalFact(nameof(HasKnownLibraryInSystemDirectory))] public void LoadSystemLibrary_WithSearchPath() { string libName = "url.dll"; // Calls on a valid library from System32 directory EXPECT(LoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.System32)); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.System32)); // Calls on a valid library from application directory EXPECT(LoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.ApplicationDirectory), TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.ApplicationDirectory), TestResult.ReturnFailure); } [Fact] public void LoadLibrary_NullLibName() { EXPECT(LoadLibrary_WithAssembly(null, assembly, null), TestResult.ArgumentNull); EXPECT(TryLoadLibrary_WithAssembly(null, assembly, null), TestResult.ArgumentNull); } [Fact] public void LoadLibrary_NullAssembly() { string libName = NativeLibraryToLoad.Name; EXPECT(LoadLibrary_WithAssembly(libName, null, null), TestResult.ArgumentNull); EXPECT(TryLoadLibrary_WithAssembly(libName, null, null), TestResult.ArgumentNull); } [Fact] public void LoadLibary_UsesFullPath_EvenWhen_AssemblyDirectory_Specified() { string libName = Path.Combine(testBinDir, Path.Combine("lib", NativeLibraryToLoad.Name)); EXPECT(LoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.AssemblyDirectory), TestResult.DllNotFound); EXPECT(TryLoadLibrary_WithAssembly(libName, assembly, DllImportSearchPath.AssemblyDirectory), TestResult.ReturnFailure); } [Fact] public void Free() { string libName = libFullPath; IntPtr handle = NativeLibrary.Load(libName); // Valid Free EXPECT(FreeLibrary(handle)); // Double Free if (OperatingSystem.IsWindows()) { // The FreeLibrary() implementation simply calls the appropriate OS API // with the supplied handle. Not all OSes consistently return an error // when a library is double-freed. EXPECT(FreeLibrary(handle), TestResult.InvalidOperation); } // Null Free EXPECT(FreeLibrary(IntPtr.Zero)); } public void Dispose() {} static TestResult LoadLibrary_NameOnly(string libPath) { IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { handle = NativeLibrary.Load(libPath); if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult TryLoadLibrary_NameOnly(string libPath) { IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { bool success = NativeLibrary.TryLoad(libPath, out handle); if (!success) return TestResult.ReturnFailure; if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult LoadLibrary_WithAssembly(string libName, Assembly assembly, DllImportSearchPath? searchPath) { IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { handle = NativeLibrary.Load(libName, assembly, searchPath); if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult TryLoadLibrary_WithAssembly(string libName, Assembly assembly, DllImportSearchPath? searchPath) { IntPtr handle = IntPtr.Zero; TestResult result = Run(() => { bool success = NativeLibrary.TryLoad(libName, assembly, searchPath, out handle); if (!success) return TestResult.ReturnFailure; if (handle == IntPtr.Zero) return TestResult.ReturnNull; return TestResult.Success; }); NativeLibrary.Free(handle); return result; } static TestResult FreeLibrary(IntPtr handle) { return Run(() => { NativeLibrary.Free(handle); return TestResult.Success; }); } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.CodeDom/tests/System/CodeDom/CodeEventReferenceExpressionTests.cs
// 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 Xunit; namespace System.CodeDom.Tests { public class CodeEventReferenceExpressionTests : CodeObjectTestBase<CodeEventReferenceExpression> { [Fact] public void Ctor_Default() { var eventReference = new CodeEventReferenceExpression(); Assert.Null(eventReference.TargetObject); Assert.Empty(eventReference.EventName); } public static IEnumerable<object[]> Ctor_TestData() { yield return new object[] { null, null }; yield return new object[] { new CodePrimitiveExpression(""), "" }; yield return new object[] { new CodePrimitiveExpression("Value"), "EventName" }; } [Theory] [MemberData(nameof(Ctor_TestData))] public void Ctor(CodeExpression targetObject, string eventName) { var eventReference = new CodeEventReferenceExpression(targetObject, eventName); Assert.Equal(targetObject, eventReference.TargetObject); Assert.Equal(eventName ?? string.Empty, eventReference.EventName); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("EventName")] public void EventName_Set_Get_ReturnsExpected(string value) { var eventReference = new CodeEventReferenceExpression(); eventReference.EventName = value; Assert.Equal(value ?? string.Empty, eventReference.EventName); } [Theory] [MemberData(nameof(CodeExpression_TestData))] public void TargetObject_Set_Get_ReturnsExpected(CodeExpression value) { var eventReference = new CodeEventReferenceExpression(); eventReference.TargetObject = value; Assert.Equal(value, eventReference.TargetObject); } } }
// 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 Xunit; namespace System.CodeDom.Tests { public class CodeEventReferenceExpressionTests : CodeObjectTestBase<CodeEventReferenceExpression> { [Fact] public void Ctor_Default() { var eventReference = new CodeEventReferenceExpression(); Assert.Null(eventReference.TargetObject); Assert.Empty(eventReference.EventName); } public static IEnumerable<object[]> Ctor_TestData() { yield return new object[] { null, null }; yield return new object[] { new CodePrimitiveExpression(""), "" }; yield return new object[] { new CodePrimitiveExpression("Value"), "EventName" }; } [Theory] [MemberData(nameof(Ctor_TestData))] public void Ctor(CodeExpression targetObject, string eventName) { var eventReference = new CodeEventReferenceExpression(targetObject, eventName); Assert.Equal(targetObject, eventReference.TargetObject); Assert.Equal(eventName ?? string.Empty, eventReference.EventName); } [Theory] [InlineData(null)] [InlineData("")] [InlineData("EventName")] public void EventName_Set_Get_ReturnsExpected(string value) { var eventReference = new CodeEventReferenceExpression(); eventReference.EventName = value; Assert.Equal(value ?? string.Empty, eventReference.EventName); } [Theory] [MemberData(nameof(CodeExpression_TestData))] public void TargetObject_Set_Get_ReturnsExpected(CodeExpression value) { var eventReference = new CodeEventReferenceExpression(); eventReference.TargetObject = value; Assert.Equal(value, eventReference.TargetObject); } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M09.5-PDC/b31748/b31748.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/MultiplyExtendedByScalar.Vector128.Double.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyExtendedByScalar_Vector128_Double() { var test = new SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector64<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double testClass) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector64<Double>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.LoadVector64((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector64<Double> _clsVar2; private Vector128<Double> _fld1; private Vector64<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>()); } public SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyExtendedByScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector64<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyExtendedByScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector64<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector64<Double>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(pClsVar1)), AdvSimd.LoadVector64((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Double*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double(); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector64<Double>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.LoadVector64((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector64<Double>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.LoadVector64((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(&test._fld1)), AdvSimd.LoadVector64((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector64<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.MultiplyExtended(left[i], right[0])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.MultiplyExtendedByScalar)}<Double>(Vector128<Double>, Vector64<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyExtendedByScalar_Vector128_Double() { var test = new SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector64<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double testClass) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector64<Double>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.LoadVector64((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector64<Double> _clsVar2; private Vector128<Double> _fld1; private Vector64<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>()); } public SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyExtendedByScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector64<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MultiplyExtendedByScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector64<Double>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector64<Double>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(pClsVar1)), AdvSimd.LoadVector64((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Double>>(_dataTable.inArray2Ptr); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Double*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double(); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MultiplyExtendedByScalar_Vector128_Double(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector64<Double>* pFld2 = &test._fld2) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.LoadVector64((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector64<Double>* pFld2 = &_fld2) { var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(pFld1)), AdvSimd.LoadVector64((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MultiplyExtendedByScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MultiplyExtendedByScalar( AdvSimd.LoadVector128((Double*)(&test._fld1)), AdvSimd.LoadVector64((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector64<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Helpers.MultiplyExtended(left[i], right[0])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.MultiplyExtendedByScalar)}<Double>(Vector128<Double>, Vector64<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Private.Xml/tests/Readers/WrappedReader/WrappedReaderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using OLEDB.Test.ModuleCore; using Xunit; namespace System.Xml.Tests { public partial class WrappedReaderTest : CGenericTestModule { [Theory] [XmlTests(nameof(Create))] public void RunTests(XunitTestCase testCase) { testCase.Run(); } public static CTestModule Create() { var module = new WrappedReaderTest(); module.Init(null); module.AddChild(new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "WrappedReader" } }); module.AddChild(new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "WrappedReader" } }); module.AddChild(new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "WrappedReader" } }); module.AddChild(new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "WrappedReader" } }); module.AddChild(new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "WrappedReader" } }); module.AddChild(new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "WrappedReader" } }); module.AddChild(new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "WrappedReader" } }); module.AddChild(new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "WrappedReader" } }); module.AddChild(new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "WrappedReader" } }); module.AddChild(new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "WrappedReader" } }); module.AddChild(new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "WrappedReader" } }); module.AddChild(new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "WrappedReader" } }); module.AddChild(new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "WrappedReader" } }); module.AddChild(new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "WrappedReader" } }); module.AddChild(new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "WrappedReader" } }); module.AddChild(new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "WrappedReader" } }); module.AddChild(new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "WrappedReader" } }); module.AddChild(new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "WrappedReader" } }); module.AddChild(new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration DCR52258", Desc = "WrappedReader" } }); module.AddChild(new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "WrappedReader" } }); module.AddChild(new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "WrappedReader" } }); module.AddChild(new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "WrappedReader" } }); module.AddChild(new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "WrappedReader" } }); module.AddChild(new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "WrappedReader" } }); module.AddChild(new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "WrappedReader" } }); module.AddChild(new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "WrappedReader" } }); module.AddChild(new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "WrappedReader" } }); module.AddChild(new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "WrappedReader" } }); module.AddChild(new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "WrappedReader" } }); module.AddChild(new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "WrappedReader" } }); module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } }); module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } }); module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } }); module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } }); module.AddChild(new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "WrappedReader" } }); module.AddChild(new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "WrappedReader" } }); module.AddChild(new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "WrappedReader" } }); module.AddChild(new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "WrappedReader" } }); module.AddChild(new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "WrappedReader" } }); module.AddChild(new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "WrappedReader" } }); module.AddChild(new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "WrappedReader" } }); module.AddChild(new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "WrappedReader" } }); module.AddChild(new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "WrappedReader" } }); return module; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using OLEDB.Test.ModuleCore; using Xunit; namespace System.Xml.Tests { public partial class WrappedReaderTest : CGenericTestModule { [Theory] [XmlTests(nameof(Create))] public void RunTests(XunitTestCase testCase) { testCase.Run(); } public static CTestModule Create() { var module = new WrappedReaderTest(); module.Init(null); module.AddChild(new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "WrappedReader" } }); module.AddChild(new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "WrappedReader" } }); module.AddChild(new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "WrappedReader" } }); module.AddChild(new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "WrappedReader" } }); module.AddChild(new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "WrappedReader" } }); module.AddChild(new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "WrappedReader" } }); module.AddChild(new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "WrappedReader" } }); module.AddChild(new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "WrappedReader" } }); module.AddChild(new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "WrappedReader" } }); module.AddChild(new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "WrappedReader" } }); module.AddChild(new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "WrappedReader" } }); module.AddChild(new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "WrappedReader" } }); module.AddChild(new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "WrappedReader" } }); module.AddChild(new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "WrappedReader" } }); module.AddChild(new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "WrappedReader" } }); module.AddChild(new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "WrappedReader" } }); module.AddChild(new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "WrappedReader" } }); module.AddChild(new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "WrappedReader" } }); module.AddChild(new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration DCR52258", Desc = "WrappedReader" } }); module.AddChild(new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "WrappedReader" } }); module.AddChild(new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "WrappedReader" } }); module.AddChild(new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "WrappedReader" } }); module.AddChild(new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "WrappedReader" } }); module.AddChild(new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "WrappedReader" } }); module.AddChild(new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "WrappedReader" } }); module.AddChild(new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "WrappedReader" } }); module.AddChild(new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "WrappedReader" } }); module.AddChild(new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "WrappedReader" } }); module.AddChild(new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "WrappedReader" } }); module.AddChild(new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "WrappedReader" } }); module.AddChild(new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "WrappedReader" } }); module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } }); module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } }); module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } }); module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } }); module.AddChild(new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "WrappedReader" } }); module.AddChild(new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "WrappedReader" } }); module.AddChild(new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "WrappedReader" } }); module.AddChild(new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "WrappedReader" } }); module.AddChild(new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "WrappedReader" } }); module.AddChild(new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "WrappedReader" } }); module.AddChild(new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "WrappedReader" } }); module.AddChild(new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "WrappedReader" } }); module.AddChild(new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "WrappedReader" } }); return module; } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/GC/Scenarios/GCSimulator/GCSimulator_362.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8517 -dc 10000 -sdc 5000 -lt 4 -dp 0.8 -dw 0.8</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <GCStressIncompatible>true</GCStressIncompatible> <CLRTestExecutionArguments>-t 1 -tp 0 -dz 17 -sdz 8517 -dc 10000 -sdc 5000 -lt 4 -dp 0.8 -dw 0.8</CLRTestExecutionArguments> <IsGCSimulatorTest>true</IsGCSimulatorTest> <CLRTestProjectToRun>GCSimulator.csproj</CLRTestProjectToRun> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="GCSimulator.cs" /> <Compile Include="lifetimefx.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Private.CoreLib/src/System/Runtime/ConstrainedExecution/Consistency.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.ConstrainedExecution { [Obsolete(Obsoletions.ConstrainedExecutionRegionMessage, DiagnosticId = Obsoletions.ConstrainedExecutionRegionDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public enum Consistency : int { MayCorruptProcess = 0, MayCorruptAppDomain = 1, MayCorruptInstance = 2, WillNotCorruptState = 3, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.ConstrainedExecution { [Obsolete(Obsoletions.ConstrainedExecutionRegionMessage, DiagnosticId = Obsoletions.ConstrainedExecutionRegionDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public enum Consistency : int { MayCorruptProcess = 0, MayCorruptAppDomain = 1, MayCorruptInstance = 2, WillNotCorruptState = 3, } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/Divide.Double.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void DivideDouble() { var test = new SimpleBinaryOpTest__DivideDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__DivideDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__DivideDouble testClass) { var result = Sse2.Divide(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__DivideDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Divide( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__DivideDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__DivideDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Divide( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Divide( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Divide( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Divide( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.Divide( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.Divide(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Divide(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Divide(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__DivideDouble(); var result = Sse2.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__DivideDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.Divide( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Divide(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Divide( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Divide( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(left[0] / right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i] / right[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Divide)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void DivideDouble() { var test = new SimpleBinaryOpTest__DivideDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__DivideDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__DivideDouble testClass) { var result = Sse2.Divide(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__DivideDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Divide( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__DivideDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__DivideDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Divide( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Divide( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Divide( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Divide), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Divide( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.Divide( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.Divide(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Divide(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Divide(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__DivideDouble(); var result = Sse2.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__DivideDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.Divide( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Divide(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Divide( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Divide(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Divide( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(left[0] / right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i] / right[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Divide)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Speech/src/Recognition/SrgsGrammar/SrgsGrammar.cs
// 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.Collections.ObjectModel; using System.Globalization; using System.Speech.Internal; using System.Speech.Internal.SrgsParser; using System.Xml; #pragma warning disable 56500 // Remove all the catch all statements warnings used by the interop layer namespace System.Speech.Recognition.SrgsGrammar { [Serializable] internal sealed class SrgsGrammar : IGrammar { #region Constructors /// <summary> /// Initializes a new instance of the Grammar class. /// </summary> internal SrgsGrammar() { _rules = new SrgsRulesCollection(); } #endregion #region Internal Methods /// <summary> /// Write the XML fragment describing the object. /// </summary> /// <param name="writer">XmlWriter to which to write the XML fragment.</param> internal void WriteSrgs(XmlWriter writer) { // Write <grammar // version="1.0" // xml:lang="en" // mode="voice" // xmlns="http://www.w3.org/2001/06/grammar" // xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions" // root="myRule" // xml:base="http://www.example.com/base-file-path"> writer.WriteStartElement("grammar", XmlParser.srgsNamespace); writer.WriteAttributeString("xml", "lang", null, _culture.ToString()); if (_root != null) { writer.WriteAttributeString("root", _root.Id); } // Write the attributes for strongly typed grammars WriteSTGAttributes(writer); if (_isModeSet) { switch (_mode) { case SrgsGrammarMode.Voice: writer.WriteAttributeString("mode", "voice"); break; case SrgsGrammarMode.Dtmf: writer.WriteAttributeString("mode", "dtmf"); break; } } // Write the tag format if any string tagFormat = null; switch (_tagFormat) { case SrgsTagFormat.Default: // Nothing to do break; case SrgsTagFormat.MssV1: tagFormat = "semantics-ms/1.0"; break; case SrgsTagFormat.W3cV1: tagFormat = "semantics/1.0"; break; case SrgsTagFormat.KeyValuePairs: tagFormat = "properties-ms/1.0"; break; default: System.Diagnostics.Debug.Assert(false, "Unknown Tag Format!!!"); break; } if (tagFormat != null) { writer.WriteAttributeString("tag-format", tagFormat); } // Write the Alphabet type if not SAPI if (_hasPhoneticAlphabetBeenSet || (_phoneticAlphabet != SrgsPhoneticAlphabet.Sapi && HasPronunciation)) { string alphabet = _phoneticAlphabet == SrgsPhoneticAlphabet.Ipa ? "ipa" : _phoneticAlphabet == SrgsPhoneticAlphabet.Ups ? "x-microsoft-ups" : "x-microsoft-sapi"; writer.WriteAttributeString("sapi", "alphabet", XmlParser.sapiNamespace, alphabet); } if (_xmlBase != null) { writer.WriteAttributeString("xml:base", _xmlBase.ToString()); } writer.WriteAttributeString("version", "1.0"); writer.WriteAttributeString("xmlns", XmlParser.srgsNamespace); if (_isSapiExtensionUsed) { writer.WriteAttributeString("xmlns", "sapi", null, XmlParser.sapiNamespace); } foreach (SrgsRule rule in _rules) { // Validate child _rules rule.Validate(this); } // Write the tag elements if any foreach (string tag in _globalTags) { writer.WriteElementString("tag", tag); } //Write the references to the referenced assemblies and the various scripts WriteGrammarElements(writer); writer.WriteEndElement(); } /// <summary> /// Validate the SRGS element. /// </summary> internal void Validate() { // Validation set the pronunciation so reset it to zero HasPronunciation = HasSapiExtension = false; // validate all the rules foreach (SrgsRule rule in _rules) { // Validate child _rules rule.Validate(this); } // Initial values for ContainsCOde and SapiExtensionUsed. _isSapiExtensionUsed |= HasPronunciation; _fContainsCode |= _language != null || _script.Length > 0 || _usings.Count > 0 || _assemblyReferences.Count > 0 || _codebehind.Count > 0 || _namespace != null || _fDebug; _isSapiExtensionUsed |= _fContainsCode; // If the grammar contains no pronunciations, set the phonetic alphabet to SAPI. // This way, the CFG data can be loaded by SAPI 5.1. if (!HasPronunciation) { PhoneticAlphabet = AlphabetType.Sapi; } // Validate root rule reference if (_root != null) { if (!_rules.Contains(_root)) { XmlParser.ThrowSrgsException(SRID.RootNotDefined, _root.Id); } } if (_globalTags.Count > 0) { _tagFormat = SrgsTagFormat.W3cV1; } // Force the tag format to Sapi properties if .NET semantics are used. if (_fContainsCode) { if (_tagFormat == SrgsTagFormat.Default) { _tagFormat = SrgsTagFormat.KeyValuePairs; } // SAPI semantics only for .NET Semantics if (_tagFormat != SrgsTagFormat.KeyValuePairs) { XmlParser.ThrowSrgsException(SRID.InvalidSemanticProcessingType); } } } IRule IGrammar.CreateRule(string id, RulePublic publicRule, RuleDynamic dynamic, bool hasScript) { SrgsRule rule = new(id); if (publicRule != RulePublic.NotSet) { rule.Scope = publicRule == RulePublic.True ? SrgsRuleScope.Public : SrgsRuleScope.Private; } rule.Dynamic = dynamic; return rule; } void IElement.PostParse(IElement parent) { // Check that the root rule is defined if (_sRoot != null) { bool found = false; foreach (SrgsRule rule in Rules) { if (rule.Id == _sRoot) { Root = rule; found = true; break; } } if (!found) { // "Root rule ""%s"" is undefined." XmlParser.ThrowSrgsException(SRID.RootNotDefined, _sRoot); } } // Resolve the references to the scripts foreach (XmlParser.ForwardReference script in _scriptsForwardReference) { SrgsRule rule = Rules[script._name]; if (rule != null) { rule.Script = rule.Script + script._value; } else { XmlParser.ThrowSrgsException(SRID.InvalidScriptDefinition); } } // Validate the whole grammar Validate(); } #pragma warning disable 56507 // check for null or empty strings // Add a script to this grammar or to a rule internal void AddScript(string rule, string code) { if (rule == null) { _script += code; } else { _scriptsForwardReference.Add(new XmlParser.ForwardReference(rule, code)); } } #endregion #region Internal Properties /// <summary> /// Sets the Root element /// </summary> string IGrammar.Root { get { return _sRoot; } set { _sRoot = value; } } /// <summary> /// Base URI of grammar (xml:base) /// </summary> public Uri XmlBase { get { return _xmlBase; } set { _xmlBase = value; } } /// <summary> /// Grammar language (xml:lang) /// </summary> public CultureInfo Culture { get { return _culture; } set { Helpers.ThrowIfNull(value, nameof(value)); _culture = value; } } /// <summary> /// Grammar mode. voice or dtmf /// </summary> public GrammarType Mode { get { return _mode == SrgsGrammarMode.Voice ? GrammarType.VoiceGrammar : GrammarType.DtmfGrammar; } set { _mode = value == GrammarType.VoiceGrammar ? SrgsGrammarMode.Voice : SrgsGrammarMode.Dtmf; _isModeSet = true; } } /// <summary> /// Pronunciation Alphabet, IPA or SAPI or UPS /// </summary> public AlphabetType PhoneticAlphabet { get { return (AlphabetType)_phoneticAlphabet; } set { _phoneticAlphabet = (SrgsPhoneticAlphabet)value; } } /// <summary>root /// Root rule (srgs:root) /// </summary> public SrgsRule Root { get { return _root; } set { _root = value; } } /// <summary> /// Tag format (srgs:tag-format) /// </summary> public SrgsTagFormat TagFormat { get { return _tagFormat; } set { _tagFormat = value; } } /// <summary> /// Tag format (srgs:tag-format) /// </summary> public Collection<string> GlobalTags { get { return _globalTags; } set { _globalTags = value; } } /// <summary> /// language /// </summary> public string Language { get { return _language; } set { _language = value; } } /// <summary> /// namespace /// </summary> public string Namespace { get { return _namespace; } set { _namespace = value; } } /// <summary> /// CodeBehind /// </summary> public Collection<string> CodeBehind { get { return _codebehind; } set { throw new InvalidOperationException(); } } /// <summary> /// Add #line statements to the inline scripts if set /// </summary> public bool Debug { get { return _fDebug; } set { _fDebug = value; } } /// <summary> /// Scripts /// </summary> public string Script { get { return _script; } set { Helpers.ThrowIfEmptyOrNull(value, nameof(value)); _script = value; } } /// <summary> /// ImportNameSpaces /// </summary> public Collection<string> ImportNamespaces { get { return _usings; } set { throw new InvalidOperationException(); } } /// <summary> /// ImportNameSpaces /// </summary> public Collection<string> AssemblyReferences { get { return _assemblyReferences; } set { throw new InvalidOperationException(); } } #endregion #region Internal Properties /// <summary> /// A collection of _rules that this grammar houses. /// </summary> internal SrgsRulesCollection Rules { get { return _rules; } } /// <summary> /// A collection of _rules that this grammar houses. /// </summary> internal bool HasPronunciation { get { return _hasPronunciation; } set { _hasPronunciation = value; } } /// <summary> /// A collection of _rules that this grammar houses. /// </summary> internal bool HasPhoneticAlphabetBeenSet { set { _hasPhoneticAlphabetBeenSet = value; } } /// <summary> /// A collection of _rules that this grammar houses. /// </summary> internal bool HasSapiExtension { get { return _isSapiExtensionUsed; } set { _isSapiExtensionUsed = value; } } #endregion #region Private Methods /// <summary> /// Write the attributes of the grammar element for strongly typed grammars /// </summary> private void WriteSTGAttributes(XmlWriter writer) { // Write the 'language' attribute if (_language != null) { writer.WriteAttributeString("sapi", "language", XmlParser.sapiNamespace, _language); } // Write the 'namespace' attribute if (_namespace != null) { writer.WriteAttributeString("sapi", "namespace", XmlParser.sapiNamespace, _namespace); } // Write the 'codebehind' attribute foreach (string sFile in _codebehind) { if (!string.IsNullOrEmpty(sFile)) { writer.WriteAttributeString("sapi", "codebehind", XmlParser.sapiNamespace, sFile); } } // Write the 'debug' attribute if (_fDebug) { writer.WriteAttributeString("sapi", "debug", XmlParser.sapiNamespace, "True"); } } /// <summary> /// Write the references to the referenced assemblies and the various scripts /// </summary> private void WriteGrammarElements(XmlWriter writer) { // Write all the <assmblyReference> entries foreach (string sAssembly in _assemblyReferences) { writer.WriteStartElement("sapi", "assemblyReference", XmlParser.sapiNamespace); writer.WriteAttributeString("sapi", "assembly", XmlParser.sapiNamespace, sAssembly); writer.WriteEndElement(); } // Write all the <assmblyReference> entries foreach (string sNamespace in _usings) { if (!string.IsNullOrEmpty(sNamespace)) { writer.WriteStartElement("sapi", "importNamespace", XmlParser.sapiNamespace); writer.WriteAttributeString("sapi", "namespace", XmlParser.sapiNamespace, sNamespace); writer.WriteEndElement(); } } // Then write the rules WriteRules(writer); // At the very bottom write the scripts shared by all the rules WriteGlobalScripts(writer); } /// <summary> /// Write all Rules. /// </summary> private void WriteRules(XmlWriter writer) { // Write <grammar> body and footer. foreach (SrgsRule rule in _rules) { rule.WriteSrgs(writer); } } /// <summary> /// Write the script that are global to this grammar /// </summary> private void WriteGlobalScripts(XmlWriter writer) { if (_script.Length > 0) { writer.WriteStartElement("sapi", "script", XmlParser.sapiNamespace); writer.WriteCData(_script); writer.WriteEndElement(); } } #endregion #region Private Fields private bool _isSapiExtensionUsed; // Set in *.Validate() private Uri _xmlBase; private CultureInfo _culture = CultureInfo.CurrentUICulture; private SrgsGrammarMode _mode = SrgsGrammarMode.Voice; private SrgsPhoneticAlphabet _phoneticAlphabet = SrgsPhoneticAlphabet.Ipa; private bool _hasPhoneticAlphabetBeenSet; private bool _hasPronunciation; private SrgsRule _root; private SrgsTagFormat _tagFormat = SrgsTagFormat.Default; private Collection<string> _globalTags = new(); private bool _isModeSet; private SrgsRulesCollection _rules; private string _sRoot; internal bool _fContainsCode; // Set in *.Validate() // .NET Language for this grammar private string _language; // .NET Language for this grammar private Collection<string> _codebehind = new(); // namespace for the code behind private string _namespace; // Insert #line statements in the sources code if set internal bool _fDebug; // .NET language script private string _script = string.Empty; // .NET language script private List<XmlParser.ForwardReference> _scriptsForwardReference = new(); // .NET Namespaces to import private Collection<string> _usings = new(); // .NET Namespaces to import private Collection<string> _assemblyReferences = new(); #endregion } }
// 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.Collections.ObjectModel; using System.Globalization; using System.Speech.Internal; using System.Speech.Internal.SrgsParser; using System.Xml; #pragma warning disable 56500 // Remove all the catch all statements warnings used by the interop layer namespace System.Speech.Recognition.SrgsGrammar { [Serializable] internal sealed class SrgsGrammar : IGrammar { #region Constructors /// <summary> /// Initializes a new instance of the Grammar class. /// </summary> internal SrgsGrammar() { _rules = new SrgsRulesCollection(); } #endregion #region Internal Methods /// <summary> /// Write the XML fragment describing the object. /// </summary> /// <param name="writer">XmlWriter to which to write the XML fragment.</param> internal void WriteSrgs(XmlWriter writer) { // Write <grammar // version="1.0" // xml:lang="en" // mode="voice" // xmlns="http://www.w3.org/2001/06/grammar" // xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions" // root="myRule" // xml:base="http://www.example.com/base-file-path"> writer.WriteStartElement("grammar", XmlParser.srgsNamespace); writer.WriteAttributeString("xml", "lang", null, _culture.ToString()); if (_root != null) { writer.WriteAttributeString("root", _root.Id); } // Write the attributes for strongly typed grammars WriteSTGAttributes(writer); if (_isModeSet) { switch (_mode) { case SrgsGrammarMode.Voice: writer.WriteAttributeString("mode", "voice"); break; case SrgsGrammarMode.Dtmf: writer.WriteAttributeString("mode", "dtmf"); break; } } // Write the tag format if any string tagFormat = null; switch (_tagFormat) { case SrgsTagFormat.Default: // Nothing to do break; case SrgsTagFormat.MssV1: tagFormat = "semantics-ms/1.0"; break; case SrgsTagFormat.W3cV1: tagFormat = "semantics/1.0"; break; case SrgsTagFormat.KeyValuePairs: tagFormat = "properties-ms/1.0"; break; default: System.Diagnostics.Debug.Assert(false, "Unknown Tag Format!!!"); break; } if (tagFormat != null) { writer.WriteAttributeString("tag-format", tagFormat); } // Write the Alphabet type if not SAPI if (_hasPhoneticAlphabetBeenSet || (_phoneticAlphabet != SrgsPhoneticAlphabet.Sapi && HasPronunciation)) { string alphabet = _phoneticAlphabet == SrgsPhoneticAlphabet.Ipa ? "ipa" : _phoneticAlphabet == SrgsPhoneticAlphabet.Ups ? "x-microsoft-ups" : "x-microsoft-sapi"; writer.WriteAttributeString("sapi", "alphabet", XmlParser.sapiNamespace, alphabet); } if (_xmlBase != null) { writer.WriteAttributeString("xml:base", _xmlBase.ToString()); } writer.WriteAttributeString("version", "1.0"); writer.WriteAttributeString("xmlns", XmlParser.srgsNamespace); if (_isSapiExtensionUsed) { writer.WriteAttributeString("xmlns", "sapi", null, XmlParser.sapiNamespace); } foreach (SrgsRule rule in _rules) { // Validate child _rules rule.Validate(this); } // Write the tag elements if any foreach (string tag in _globalTags) { writer.WriteElementString("tag", tag); } //Write the references to the referenced assemblies and the various scripts WriteGrammarElements(writer); writer.WriteEndElement(); } /// <summary> /// Validate the SRGS element. /// </summary> internal void Validate() { // Validation set the pronunciation so reset it to zero HasPronunciation = HasSapiExtension = false; // validate all the rules foreach (SrgsRule rule in _rules) { // Validate child _rules rule.Validate(this); } // Initial values for ContainsCOde and SapiExtensionUsed. _isSapiExtensionUsed |= HasPronunciation; _fContainsCode |= _language != null || _script.Length > 0 || _usings.Count > 0 || _assemblyReferences.Count > 0 || _codebehind.Count > 0 || _namespace != null || _fDebug; _isSapiExtensionUsed |= _fContainsCode; // If the grammar contains no pronunciations, set the phonetic alphabet to SAPI. // This way, the CFG data can be loaded by SAPI 5.1. if (!HasPronunciation) { PhoneticAlphabet = AlphabetType.Sapi; } // Validate root rule reference if (_root != null) { if (!_rules.Contains(_root)) { XmlParser.ThrowSrgsException(SRID.RootNotDefined, _root.Id); } } if (_globalTags.Count > 0) { _tagFormat = SrgsTagFormat.W3cV1; } // Force the tag format to Sapi properties if .NET semantics are used. if (_fContainsCode) { if (_tagFormat == SrgsTagFormat.Default) { _tagFormat = SrgsTagFormat.KeyValuePairs; } // SAPI semantics only for .NET Semantics if (_tagFormat != SrgsTagFormat.KeyValuePairs) { XmlParser.ThrowSrgsException(SRID.InvalidSemanticProcessingType); } } } IRule IGrammar.CreateRule(string id, RulePublic publicRule, RuleDynamic dynamic, bool hasScript) { SrgsRule rule = new(id); if (publicRule != RulePublic.NotSet) { rule.Scope = publicRule == RulePublic.True ? SrgsRuleScope.Public : SrgsRuleScope.Private; } rule.Dynamic = dynamic; return rule; } void IElement.PostParse(IElement parent) { // Check that the root rule is defined if (_sRoot != null) { bool found = false; foreach (SrgsRule rule in Rules) { if (rule.Id == _sRoot) { Root = rule; found = true; break; } } if (!found) { // "Root rule ""%s"" is undefined." XmlParser.ThrowSrgsException(SRID.RootNotDefined, _sRoot); } } // Resolve the references to the scripts foreach (XmlParser.ForwardReference script in _scriptsForwardReference) { SrgsRule rule = Rules[script._name]; if (rule != null) { rule.Script = rule.Script + script._value; } else { XmlParser.ThrowSrgsException(SRID.InvalidScriptDefinition); } } // Validate the whole grammar Validate(); } #pragma warning disable 56507 // check for null or empty strings // Add a script to this grammar or to a rule internal void AddScript(string rule, string code) { if (rule == null) { _script += code; } else { _scriptsForwardReference.Add(new XmlParser.ForwardReference(rule, code)); } } #endregion #region Internal Properties /// <summary> /// Sets the Root element /// </summary> string IGrammar.Root { get { return _sRoot; } set { _sRoot = value; } } /// <summary> /// Base URI of grammar (xml:base) /// </summary> public Uri XmlBase { get { return _xmlBase; } set { _xmlBase = value; } } /// <summary> /// Grammar language (xml:lang) /// </summary> public CultureInfo Culture { get { return _culture; } set { Helpers.ThrowIfNull(value, nameof(value)); _culture = value; } } /// <summary> /// Grammar mode. voice or dtmf /// </summary> public GrammarType Mode { get { return _mode == SrgsGrammarMode.Voice ? GrammarType.VoiceGrammar : GrammarType.DtmfGrammar; } set { _mode = value == GrammarType.VoiceGrammar ? SrgsGrammarMode.Voice : SrgsGrammarMode.Dtmf; _isModeSet = true; } } /// <summary> /// Pronunciation Alphabet, IPA or SAPI or UPS /// </summary> public AlphabetType PhoneticAlphabet { get { return (AlphabetType)_phoneticAlphabet; } set { _phoneticAlphabet = (SrgsPhoneticAlphabet)value; } } /// <summary>root /// Root rule (srgs:root) /// </summary> public SrgsRule Root { get { return _root; } set { _root = value; } } /// <summary> /// Tag format (srgs:tag-format) /// </summary> public SrgsTagFormat TagFormat { get { return _tagFormat; } set { _tagFormat = value; } } /// <summary> /// Tag format (srgs:tag-format) /// </summary> public Collection<string> GlobalTags { get { return _globalTags; } set { _globalTags = value; } } /// <summary> /// language /// </summary> public string Language { get { return _language; } set { _language = value; } } /// <summary> /// namespace /// </summary> public string Namespace { get { return _namespace; } set { _namespace = value; } } /// <summary> /// CodeBehind /// </summary> public Collection<string> CodeBehind { get { return _codebehind; } set { throw new InvalidOperationException(); } } /// <summary> /// Add #line statements to the inline scripts if set /// </summary> public bool Debug { get { return _fDebug; } set { _fDebug = value; } } /// <summary> /// Scripts /// </summary> public string Script { get { return _script; } set { Helpers.ThrowIfEmptyOrNull(value, nameof(value)); _script = value; } } /// <summary> /// ImportNameSpaces /// </summary> public Collection<string> ImportNamespaces { get { return _usings; } set { throw new InvalidOperationException(); } } /// <summary> /// ImportNameSpaces /// </summary> public Collection<string> AssemblyReferences { get { return _assemblyReferences; } set { throw new InvalidOperationException(); } } #endregion #region Internal Properties /// <summary> /// A collection of _rules that this grammar houses. /// </summary> internal SrgsRulesCollection Rules { get { return _rules; } } /// <summary> /// A collection of _rules that this grammar houses. /// </summary> internal bool HasPronunciation { get { return _hasPronunciation; } set { _hasPronunciation = value; } } /// <summary> /// A collection of _rules that this grammar houses. /// </summary> internal bool HasPhoneticAlphabetBeenSet { set { _hasPhoneticAlphabetBeenSet = value; } } /// <summary> /// A collection of _rules that this grammar houses. /// </summary> internal bool HasSapiExtension { get { return _isSapiExtensionUsed; } set { _isSapiExtensionUsed = value; } } #endregion #region Private Methods /// <summary> /// Write the attributes of the grammar element for strongly typed grammars /// </summary> private void WriteSTGAttributes(XmlWriter writer) { // Write the 'language' attribute if (_language != null) { writer.WriteAttributeString("sapi", "language", XmlParser.sapiNamespace, _language); } // Write the 'namespace' attribute if (_namespace != null) { writer.WriteAttributeString("sapi", "namespace", XmlParser.sapiNamespace, _namespace); } // Write the 'codebehind' attribute foreach (string sFile in _codebehind) { if (!string.IsNullOrEmpty(sFile)) { writer.WriteAttributeString("sapi", "codebehind", XmlParser.sapiNamespace, sFile); } } // Write the 'debug' attribute if (_fDebug) { writer.WriteAttributeString("sapi", "debug", XmlParser.sapiNamespace, "True"); } } /// <summary> /// Write the references to the referenced assemblies and the various scripts /// </summary> private void WriteGrammarElements(XmlWriter writer) { // Write all the <assmblyReference> entries foreach (string sAssembly in _assemblyReferences) { writer.WriteStartElement("sapi", "assemblyReference", XmlParser.sapiNamespace); writer.WriteAttributeString("sapi", "assembly", XmlParser.sapiNamespace, sAssembly); writer.WriteEndElement(); } // Write all the <assmblyReference> entries foreach (string sNamespace in _usings) { if (!string.IsNullOrEmpty(sNamespace)) { writer.WriteStartElement("sapi", "importNamespace", XmlParser.sapiNamespace); writer.WriteAttributeString("sapi", "namespace", XmlParser.sapiNamespace, sNamespace); writer.WriteEndElement(); } } // Then write the rules WriteRules(writer); // At the very bottom write the scripts shared by all the rules WriteGlobalScripts(writer); } /// <summary> /// Write all Rules. /// </summary> private void WriteRules(XmlWriter writer) { // Write <grammar> body and footer. foreach (SrgsRule rule in _rules) { rule.WriteSrgs(writer); } } /// <summary> /// Write the script that are global to this grammar /// </summary> private void WriteGlobalScripts(XmlWriter writer) { if (_script.Length > 0) { writer.WriteStartElement("sapi", "script", XmlParser.sapiNamespace); writer.WriteCData(_script); writer.WriteEndElement(); } } #endregion #region Private Fields private bool _isSapiExtensionUsed; // Set in *.Validate() private Uri _xmlBase; private CultureInfo _culture = CultureInfo.CurrentUICulture; private SrgsGrammarMode _mode = SrgsGrammarMode.Voice; private SrgsPhoneticAlphabet _phoneticAlphabet = SrgsPhoneticAlphabet.Ipa; private bool _hasPhoneticAlphabetBeenSet; private bool _hasPronunciation; private SrgsRule _root; private SrgsTagFormat _tagFormat = SrgsTagFormat.Default; private Collection<string> _globalTags = new(); private bool _isModeSet; private SrgsRulesCollection _rules; private string _sRoot; internal bool _fContainsCode; // Set in *.Validate() // .NET Language for this grammar private string _language; // .NET Language for this grammar private Collection<string> _codebehind = new(); // namespace for the code behind private string _namespace; // Insert #line statements in the sources code if set internal bool _fDebug; // .NET language script private string _script = string.Empty; // .NET language script private List<XmlParser.ForwardReference> _scriptsForwardReference = new(); // .NET Namespaces to import private Collection<string> _usings = new(); // .NET Namespaces to import private Collection<string> _assemblyReferences = new(); #endregion } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/nativeaot/SmokeTests/DynamicGenerics/Logger.cs
// 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 CoreFXTestLibrary { public class Logger { public static void LogInformation(string message, params object[] args) { if (args.Length == 0) Console.WriteLine(message); else Console.WriteLine(message, args); } } }
// 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 CoreFXTestLibrary { public class Logger { public static void LogInformation(string message, params object[] args) { if (args.Length == 0) Console.WriteLine(message); else Console.WriteLine(message, args); } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Text.Encodings.Web/tests/InboxEncoderCommonTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace System.Text.Encodings.Web.Tests { public class HtmlEncoderDefaultCommonTests : InboxEncoderCommonTestBase { public HtmlEncoderDefaultCommonTests() : base(HtmlEncoder.Default, allowedChar: 'a', disallowedChar: '&') { } private protected override string GetExpectedEscapedRepresentation(Rune value) { switch (value.Value) { case '<': return "&lt;"; case '>': return "&gt;"; case '&': return "&amp;"; case '\"': return "&quot;"; default: return FormattableString.Invariant($"&#x{(uint)value.Value:X};"); } } [Fact] public void EncodeUtf16_Battery() { string[] inputs = new string[] { "\n", "<", "a", "\u0234", // U+0234 LATIN SMALL LETTER L WITH CURL "\ud800", // standalone high surrogate "\U0001F415", // U+1F415 DOG "\udfff", // standalone low surrogate "\uFFFF", // end of BMP range "\U00010000", // beginning of supplementary range "\U0010FFFF", // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "&#xA;", "&lt;", "a", "&#x234;", "&#xFFFD;", // replaced standalone high surrogate with replacement char "&#x1F415;", "&#xFFFD;", // replaced standalone low surrogate with replacement char "&#xFFFF;", "&#x10000;", "&#x10FFFF;", }; _RunEncodeUtf16_Battery(inputs, expectedOutputs); } [Fact] public void EncodeUtf8_Battery() { byte[][] inputs = new byte[][] { new byte[] { (byte)'\n' }, new byte[] { (byte)'<' }, new byte[] { (byte)'a' }, new byte[] { 0xC8, 0xB4 }, // U+0234 LATIN SMALL LETTER L WITH CURL new byte[] { 0xFF }, // invalid byte new byte[] { 0xF0, 0x9F, 0x90, 0x95 }, // U+1F415 DOG new byte[] { 0x80 }, // standalone continuation character new byte[] { 0xC2 }, // standalone multi-byte sequence marker new byte[] { 0xEF, 0xBF, 0xBF }, // end of BMP range new byte[] { 0xF0, 0x90, 0x80, 0x80 }, // beginning of supplementary range new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "&#xA;", "&lt;", "a", "&#x234;", "&#xFFFD;", // replaced invalid byte "&#x1F415;", "&#xFFFD;", // replaced standalone continuation char "&#xFFFD;", // replaced standalone multi-byte sequence marker "&#xFFFF;", "&#x10000;", "&#x10FFFF;", }; _RunEncodeUtf8_Battery(inputs, expectedOutputs); } } public class JavaScriptEncoderDefaultCommonTests : InboxEncoderCommonTestBase { public JavaScriptEncoderDefaultCommonTests() : base(JavaScriptEncoder.Default, allowedChar: 'a', disallowedChar: '\"') { } private protected override string GetExpectedEscapedRepresentation(Rune value) { switch (value.Value) { case '\b': return "\\b"; case '\t': return "\\t"; case '\n': return "\\n"; case '\f': return "\\f"; case '\r': return "\\r"; case '\\': return "\\\\"; default: if (value.IsBmp) { return FormattableString.Invariant($"\\u{(uint)value.Value:X4}"); } else { Span<char> asUtf16 = stackalloc char[2]; bool succeeded = value.TryEncodeToUtf16(asUtf16, out int utf16CodeUnitCount); Assert.True(succeeded); Assert.Equal(2, utf16CodeUnitCount); return FormattableString.Invariant($"\\u{(uint)asUtf16[0]:X4}\\u{(uint)asUtf16[1]:X4}"); } } } [Fact] public void EncodeUtf16_Battery() { string[] inputs = new string[] { "\n", "a", "\u0234", // U+0234 LATIN SMALL LETTER L WITH CURL "\ud800", // standalone high surrogate "\U0001F415", // U+1F415 DOG "\udfff", // standalone low surrogate "\uFFFF", // end of BMP range "\U00010000", // beginning of supplementary range "\U0010FFFF", // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "\\n", "a", "\\u0234", "\\uFFFD", // replaced standalone high surrogate with replacement char "\\uD83D\\uDC15", "\\uFFFD", // replaced standalone low surrogate with replacement char "\\uFFFF", "\\uD800\\uDC00", "\\uDBFF\\uDFFF", }; _RunEncodeUtf16_Battery(inputs, expectedOutputs); } [Fact] public void EncodeUtf8_Battery() { byte[][] inputs = new byte[][] { new byte[] { (byte)'\n' }, new byte[] { (byte)'a' }, new byte[] { 0xC8, 0xB4 }, // U+0234 LATIN SMALL LETTER L WITH CURL new byte[] { 0xFF }, // invalid byte new byte[] { 0xF0, 0x9F, 0x90, 0x95 }, // U+1F415 DOG new byte[] { 0x80 }, // standalone continuation character new byte[] { 0xC2 }, // standalone multi-byte sequence marker new byte[] { 0xEF, 0xBF, 0xBF }, // end of BMP range new byte[] { 0xF0, 0x90, 0x80, 0x80 }, // beginning of supplementary range new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "\\n", "a", "\\u0234", "\\uFFFD", // replaced invalid byte "\\uD83D\\uDC15", "\\uFFFD", // replaced standalone continuation char "\\uFFFD", // replaced standalone multi-byte sequence marker "\\uFFFF", "\\uD800\\uDC00", "\\uDBFF\\uDFFF", }; _RunEncodeUtf8_Battery(inputs, expectedOutputs); } } public class JavaScriptEncoderRelaxedCommonTests : InboxEncoderCommonTestBase { public JavaScriptEncoderRelaxedCommonTests() : base(JavaScriptEncoder.UnsafeRelaxedJsonEscaping, allowedChar: 'a', disallowedChar: '\"') { } private protected override string GetExpectedEscapedRepresentation(Rune value) { switch (value.Value) { case '\b': return "\\b"; case '\t': return "\\t"; case '\n': return "\\n"; case '\f': return "\\f"; case '\r': return "\\r"; case '\\': return "\\\\"; case '\"': return "\\\""; default: if (value.IsBmp) { return FormattableString.Invariant($"\\u{(uint)value.Value:X4}"); } else { Span<char> asUtf16 = stackalloc char[2]; bool succeeded = value.TryEncodeToUtf16(asUtf16, out int utf16CodeUnitCount); Assert.True(succeeded); Assert.Equal(2, utf16CodeUnitCount); return FormattableString.Invariant($"\\u{(uint)asUtf16[0]:X4}\\u{(uint)asUtf16[1]:X4}"); } } } [Fact] public void EncodeUtf16_Battery() { string[] inputs = new string[] { "\n", "a", "\u0234", // U+0234 LATIN SMALL LETTER L WITH CURL "\ud800", // standalone high surrogate "\U0001F415", // U+1F415 DOG "\udfff", // standalone low surrogate "\uFFFF", // end of BMP range "\U00010000", // beginning of supplementary range "\U0010FFFF", // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "\\n", "a", "\u0234", // not escaped "\\uFFFD", // replaced standalone high surrogate with replacement char "\\uD83D\\uDC15", "\\uFFFD", // replaced standalone low surrogate with replacement char "\\uFFFF", "\\uD800\\uDC00", "\\uDBFF\\uDFFF", }; _RunEncodeUtf16_Battery(inputs, expectedOutputs); } [Fact] public void EncodeUtf8_Battery() { byte[][] inputs = new byte[][] { new byte[] { (byte)'\n' }, new byte[] { (byte)'a' }, new byte[] { 0xC8, 0xB4 }, // U+0234 LATIN SMALL LETTER L WITH CURL new byte[] { 0xFF }, // invalid byte new byte[] { 0xF0, 0x9F, 0x90, 0x95 }, // U+1F415 DOG new byte[] { 0x80 }, // standalone continuation character new byte[] { 0xC2 }, // standalone multi-byte sequence marker new byte[] { 0xEF, 0xBF, 0xBF }, // end of BMP range new byte[] { 0xF0, 0x90, 0x80, 0x80 }, // beginning of supplementary range new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "\\n", "a", "\u0234", // not escaped "\\uFFFD", // replaced invalid byte "\\uD83D\\uDC15", "\\uFFFD", // replaced standalone continuation char "\\uFFFD", // replaced standalone multi-byte sequence marker "\\uFFFF", "\\uD800\\uDC00", "\\uDBFF\\uDFFF", }; _RunEncodeUtf8_Battery(inputs, expectedOutputs); } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedValidCharsOnly() { _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedValidCharsOnly('\u2663'); // U+2663 BLACK CLUB SUIT } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedSomeCharsNeedEscaping() { _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedSomeCharsNeedEscaping('\u2663'); // U+2663 BLACK CLUB SUIT } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedAllValidChars() { _RunGetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedAllValidChars('\u2663'); // U+2663 BLACK CLUB SUIT } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedSomeCharsNeedEncoding() { _RunGetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedSomeCharsNeedEncoding('\u2663'); // U+2663 BLACK CLUB SUIT } } public class UrlEncoderDefaultCommonTests : InboxEncoderCommonTestBase { public UrlEncoderDefaultCommonTests() : base(UrlEncoder.Default, allowedChar: 'a', disallowedChar: '?') { } private protected override string GetExpectedEscapedRepresentation(Rune value) { Span<byte> asUtf8Bytes = stackalloc byte[4]; Span<char> hexEscaped = stackalloc char[12]; // worst-case 3 output chars per input UTF-8 code unit bool succeeded = value.TryEncodeToUtf8(asUtf8Bytes, out int utf8CodeUnitCount); Assert.True(succeeded); for (int i = 0; i < utf8CodeUnitCount; i++) { hexEscaped[i * 3] = '%'; HexConverter.ToCharsBuffer(asUtf8Bytes[i], hexEscaped, startingIndex: (i * 3) + 1); } return hexEscaped.Slice(0, utf8CodeUnitCount * 3).ToString(); } [Fact] public void EncodeUtf16_Battery() { string[] inputs = new string[] { "\n", "%", "a", "\u0234", // U+0234 LATIN SMALL LETTER L WITH CURL "\ud800", // standalone high surrogate "\U0001F415", // U+1F415 DOG "\udfff", // standalone low surrogate "\uFFFF", // end of BMP range "\U00010000", // beginning of supplementary range "\U0010FFFF", // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "%0A", "%25", "a", "%C8%B4", "%EF%BF%BD", // replaced standalone high surrogate with replacement char "%F0%9F%90%95", "%EF%BF%BD", // replaced standalone low surrogate with replacement char "%EF%BF%BF", "%F0%90%80%80", "%F4%8F%BF%BF", }; _RunEncodeUtf16_Battery(inputs, expectedOutputs); } [Fact] public void EncodeUtf8_Battery() { byte[][] inputs = new byte[][] { new byte[] { (byte)'\n' }, new byte[] { (byte)'%' }, new byte[] { (byte)'a' }, new byte[] { 0xC8, 0xB4 }, // U+0234 LATIN SMALL LETTER L WITH CURL new byte[] { 0xFF }, // invalid byte new byte[] { 0xF0, 0x9F, 0x90, 0x95 }, // U+1F415 DOG new byte[] { 0x80 }, // standalone continuation character new byte[] { 0xC2 }, // standalone multi-byte sequence marker new byte[] { 0xEF, 0xBF, 0xBF }, // end of BMP range new byte[] { 0xF0, 0x90, 0x80, 0x80 }, // beginning of supplementary range new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "%0A", "%25", "a", "%C8%B4", "%EF%BF%BD", // replaced invalid byte "%F0%9F%90%95", "%EF%BF%BD", // replaced standalone continuation char "%EF%BF%BD", // replaced standalone multi-byte sequence marker "%EF%BF%BF", "%F0%90%80%80", "%F4%8F%BF%BF", }; _RunEncodeUtf8_Battery(inputs, expectedOutputs); } } public abstract class InboxEncoderCommonTestBase : IDisposable { private readonly TextEncoder _encoder; private readonly BoundedMemory<byte> _boundedBytes = BoundedMemory.Allocate<byte>(4096); private readonly BoundedMemory<char> _boundedChars = BoundedMemory.Allocate<char>(4096); private readonly char _allowedChar; // representative allowed char for this encoder private readonly char _disallowedChar; // representative never-allowed char for this encoder // U+2D2E is in the Georgian Supplement block but is not currently assigned, hence disallowed by all inbox encoders. // U+2D2E is an interesting test case because both U+002D ('-') and U+002E ('.') are allowed by all inbox encoders, // so using U+2D2E exercises our UTF-16 -> ASCII narrowing paths to make sure that the narrowing process doesn't // inadvertently treat a single non-ASCII BMP char as two independent ASCII chars. IF U+2D2E is ever assigned in // the future, this could cause unit tests to fail, but we'll deal with that problem when (if?) the time comes. private const char BmpExtendedDisallowedChar = '\u2d2e'; protected InboxEncoderCommonTestBase(TextEncoder encoder, char allowedChar, char disallowedChar) { Assert.NotNull(encoder); _encoder = encoder; Assert.True(allowedChar <= 0x7F, "Test setup failure: Allowed char should be ASCII."); Assert.False(encoder.WillEncode(allowedChar), "Test setup failure: Encoder must say this character is allowed."); _allowedChar = allowedChar; Assert.True(disallowedChar <= 0x7F, "Test setup failure: Disallowed char should be ASCII."); Assert.True(encoder.WillEncode(disallowedChar), "Test setup failure: Encoder must say this character is disallowed."); _disallowedChar = disallowedChar; } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf16_AllDataValid() => _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedValidCharsOnly(_allowedChar); protected void _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedValidCharsOnly(char bmpAllowedChar) { // Loop from 96 elements all the way down to 0 elements, which tests that we're // not overrunning our read buffers. var span = _boundedChars.Span; _boundedChars.MakeWriteable(); span.Fill(bmpAllowedChar); // make buffer all-valid _boundedChars.MakeReadonly(); for (int i = 96; i >= 0; i--) { Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf16(span.Slice(span.Length - i))); } // Also check from the beginning of the buffer just in case there's some alignment weirdness // in the SIMD-optimized code that causes us to read past where we should. _boundedChars.MakeWriteable(); for (int i = 96; i >= 0; i--) { span[i] = _disallowedChar; // make this char invalid (ASCII) Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf16(span.Slice(0, i))); } } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf16_SomeCharsNeedEscaping() => _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedSomeCharsNeedEscaping(_allowedChar); protected void _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedSomeCharsNeedEscaping(char bmpAllowedChar) { // Use a 31-element buffer since it will exercise all the different unrolled code paths. var span = _boundedChars.Span.Slice(0, 31); for (int i = 0; i < span.Length - 1; i++) { // First make this the only invalid char in the whole buffer. // Make sure we correctly identify the index which requires escaping. _boundedChars.MakeWriteable(); span.Fill(bmpAllowedChar); // make buffer all-valid span[i] = _disallowedChar; // make this char invalid (ASCII) _boundedChars.MakeReadonly(); Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf16(span)); _boundedChars.MakeWriteable(); span[i] = BmpExtendedDisallowedChar; // make this char invaid (BMP extended) _boundedChars.MakeReadonly(); Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf16(span)); // Use a bad standalone surrogate char instead of a disallowed char // and ensure we get the same index back. _boundedChars.MakeWriteable(); span[i] = '\ud800'; _boundedChars.MakeReadonly(); Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf16(span)); // Then make sure that we correctly identify this char as the *first* // char which requires escaping, even if the buffer contains more // requires-escaping chars after this. if (i < span.Length - 2) { _boundedChars.MakeWriteable(); span[i] = _disallowedChar; span[i + 1] = _disallowedChar; _boundedChars.MakeReadonly(); } Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf16(span)); } } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf8_AllDataValid() { // Loop from 96 elements all the way down to 0 elements, which tests that we're // not overrunning our read buffers. var span = _boundedBytes.Span; _boundedBytes.MakeWriteable(); span.Fill((byte)_allowedChar); // make buffer all-valid _boundedBytes.MakeReadonly(); for (int i = 96; i >= 0; i--) { Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(span.Length - i))); } // Also check from the beginning of the buffer just in case there's some alignment weirdness // in the SIMD-optimized code that causes us to read past where we should. _boundedBytes.MakeWriteable(); for (int i = 96; i >= 0; i--) { span[i] = (byte)_disallowedChar; // make this char invalid Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(0, i))); } } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf8_SomeCharsNeedEscaping() { // Use a 31-element buffer since it will exercise all the different vectorized loops. var span = _boundedBytes.Span.Slice(0, 31); for (int i = 0; i < span.Length - 1; i++) { // First make this the only invalid char in the whole buffer. // Make sure we correctly identify the index which requires escaping. _boundedBytes.MakeWriteable(); span.Fill((byte)_allowedChar); // make buffer all-valid span[i] = (byte)_disallowedChar; // make this char invalid _boundedBytes.MakeReadonly(); Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf8(span)); // Then make sure that we correctly identify this char as the *first* // char which requires escaping, even if the buffer contains more // requires-escaping chars after this. if (i < span.Length - 2) { _boundedBytes.MakeWriteable(); span[i + 1] = (byte)_disallowedChar; _boundedBytes.MakeReadonly(); } Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf8(span)); } } protected void _RunGetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedAllValidChars(char bmpAllowedChar) { Span<byte> allowedCharAsUtf8 = stackalloc byte[3]; Assert.True(new Rune(bmpAllowedChar).TryEncodeToUtf8(allowedCharAsUtf8, out int allowedCharUtf8CodeUnitCount)); allowedCharAsUtf8 = allowedCharAsUtf8.Slice(0, allowedCharUtf8CodeUnitCount); // Copy this character to the end of the buffer 12 times var span = _boundedBytes.Span; span = span.Slice(span.Length - allowedCharAsUtf8.Length * 12); _boundedBytes.MakeWriteable(); span.Clear(); for (int i = 0; i < 12; i++) { allowedCharAsUtf8.CopyTo(span.Slice(allowedCharAsUtf8.Length * i)); } _boundedBytes.MakeReadonly(); // And now make sure we identify all chars as allowed. for (int i = 0; i < 12; i++) { Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(allowedCharAsUtf8.Length * i))); } } protected void _RunGetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedSomeCharsNeedEncoding(char bmpAllowedChar) { Assert.True(bmpAllowedChar >= 0x80, "Must be a non-ASCII char."); Span<byte> allowedCharAsUtf8 = stackalloc byte[3]; Assert.True(new Rune(bmpAllowedChar).TryEncodeToUtf8(allowedCharAsUtf8, out int allowedCharUtf8CodeUnitCount)); allowedCharAsUtf8 = allowedCharAsUtf8.Slice(0, allowedCharUtf8CodeUnitCount); // Copy this character to the end of the buffer 12 times var span = _boundedBytes.Span; span = span.Slice(span.Length - allowedCharAsUtf8.Length * 12); _boundedBytes.MakeWriteable(); span.Clear(); for (int i = 0; i < 12; i++) { allowedCharAsUtf8.CopyTo(span.Slice(allowedCharAsUtf8.Length * i)); } // And now make sure we identify bad chars as disallowed. // The last element in the span will be invalid, and we'll keep shrinking the span // so that the returned index changes on each iteration. for (int i = 0; i < 12; i++) { // First, corrupt the element by making it a standalone continuation byte. span[span.Length - allowedCharAsUtf8.Length] = 0xBF; Assert.Equal((11 - i) * allowedCharAsUtf8.Length, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(allowedCharAsUtf8.Length * i))); // Then, uncorrupt the element by making it a well-formed but never-allowed code point (U+009F is a never-allowed C1 control code point) span[span.Length - allowedCharAsUtf8.Length] = 0xC2; span[span.Length - allowedCharAsUtf8.Length + 1] = 0x9F; Assert.Equal((11 - i) * allowedCharAsUtf8.Length, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(allowedCharAsUtf8.Length * i))); } } [Fact] public unsafe void TryEncodeUnicodeScalar_AllowedBmpChar() { _boundedChars.MakeWriteable(); // First, try with enough space (two chars) in the destination buffer var destination = _boundedChars.Span; destination = destination.Slice(destination.Length - 2); destination.Clear(); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) { bool succeeded = _encoder.TryEncodeUnicodeScalar(_allowedChar, pBuf, destination.Length, out int numCharsWritten); Assert.True(succeeded); Assert.Equal(1, numCharsWritten); Assert.Equal(_allowedChar, destination[0]); // Should reflect char as-is } // Then, try with enough space (one char) in the destination buffer destination.Clear(); destination = destination.Slice(1); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) { bool succeeded = _encoder.TryEncodeUnicodeScalar(_allowedChar, pBuf, destination.Length, out int numCharsWritten); Assert.True(succeeded); Assert.Equal(1, numCharsWritten); Assert.Equal(_allowedChar, destination[0]); // Should reflect char as-is } // Finally, try with not enough space in the destination buffer destination.Clear(); destination = destination.Slice(1); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) // use MemoryMarshal so as to get a valid pointer { bool succeeded = _encoder.TryEncodeUnicodeScalar(_allowedChar, pBuf, destination.Length, out int numCharsWritten); Assert.False(succeeded); Assert.Equal(0, numCharsWritten); } } [Fact] public unsafe void TryEncodeUnicodeScalar_DisallowedBmpChar() { TryEncodeUnicodeScalar_DisallowedScalarCommon(new Rune(_disallowedChar)); } [Fact] public unsafe void TryEncodeUnicodeScalar_DisallowedSupplementaryChar() { TryEncodeUnicodeScalar_DisallowedScalarCommon(new Rune(0x1F604)); // U+1F604 SMILING FACE WITH OPEN MOUTH AND SMILING EYES } private unsafe void TryEncodeUnicodeScalar_DisallowedScalarCommon(Rune value) { _boundedChars.MakeWriteable(); string expectedEscaping = GetExpectedEscapedRepresentation(value); // First, try with enough space +1 in the destination buffer var destination = _boundedChars.Span; destination = destination.Slice(destination.Length - expectedEscaping.Length - 1); destination.Clear(); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) { bool succeeded = _encoder.TryEncodeUnicodeScalar(value.Value, pBuf, destination.Length, out int numCharsWritten); Assert.True(succeeded); Assert.Equal(expectedEscaping.Length, numCharsWritten); Assert.Equal(expectedEscaping, destination.Slice(0, expectedEscaping.Length).ToString()); } // Then, try with enough space +0 in the destination buffer destination.Clear(); destination = destination.Slice(1); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) { bool succeeded = _encoder.TryEncodeUnicodeScalar(value.Value, pBuf, destination.Length, out int numCharsWritten); Assert.True(succeeded); Assert.Equal(expectedEscaping.Length, numCharsWritten); Assert.Equal(expectedEscaping, destination.ToString()); } // Finally, try with not enough space in the destination buffer destination.Clear(); destination = destination.Slice(1); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) // use MemoryMarshal so as to get a valid pointer { bool succeeded = _encoder.TryEncodeUnicodeScalar(value.Value, pBuf, destination.Length, out int numCharsWritten); Assert.False(succeeded); Assert.Equal(0, numCharsWritten); } } protected void _RunEncodeUtf16_Battery(string[] inputs, string[] expectedOutputs) { string accumInput = _disallowedChar.ToString(); string accumExpectedOutput = GetExpectedEscapedRepresentation(new Rune(_disallowedChar)); // First, make sure we handle the simple "can't escape a single char to the buffer" case OperationStatus opStatus = _encoder.Encode(accumInput.AsSpan(), new char[accumExpectedOutput.Length - 1], out int charsConsumed, out int charsWritten); Assert.Equal(OperationStatus.DestinationTooSmall, opStatus); Assert.Equal(0, charsConsumed); Assert.Equal(0, charsWritten); // Then, escape a single char to the destination buffer. // This skips the "find the first char to encode" fast path in TextEncoder.cs. char[] destination = new char[accumExpectedOutput.Length]; opStatus = _encoder.Encode(accumInput.AsSpan(), destination, out charsConsumed, out charsWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(1, charsConsumed); Assert.Equal(destination.Length, charsWritten); Assert.Equal(accumExpectedOutput, new string(destination)); // Now, in a loop, append inputs to the source span and test various edge cases of // destination too small vs. destination properly sized. Assert.Equal(expectedOutputs.Length, inputs.Length); for (int i = 0; i < inputs.Length; i++) { accumInput += inputs[i]; string outputToAppend = expectedOutputs[i]; // Test destination too small - we should make progress up until // the very last thing we appended to the input. destination = new char[accumExpectedOutput.Length + outputToAppend.Length - 1]; opStatus = _encoder.Encode(accumInput.AsSpan(), destination, out charsConsumed, out charsWritten); Assert.Equal(OperationStatus.DestinationTooSmall, opStatus); Assert.Equal(accumInput.Length - inputs[i].Length, charsConsumed); // should've consumed everything except the most recent appended data Assert.Equal(accumExpectedOutput.Length, charsWritten); // should've escaped everything we consumed Assert.Equal(accumExpectedOutput, new string(destination, 0, charsWritten)); // Now test destination just right - we should consume the entire buffer successfully. accumExpectedOutput += outputToAppend; destination = new char[accumExpectedOutput.Length]; opStatus = _encoder.Encode(accumInput.AsSpan(), destination, out charsConsumed, out charsWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(accumInput.Length, charsConsumed); Assert.Equal(accumExpectedOutput.Length, charsWritten); Assert.Equal(accumExpectedOutput, new string(destination)); // Now test destination oversized - we should consume the entire buffer successfully. destination = new char[accumExpectedOutput.Length + 1]; opStatus = _encoder.Encode(accumInput.AsSpan(), destination, out charsConsumed, out charsWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(accumInput.Length, charsConsumed); Assert.Equal(accumExpectedOutput.Length, charsWritten); Assert.Equal(accumExpectedOutput, new string(destination, 0, charsWritten)); // Special-case: if the buffer ended with a legal supplementary scalar value, slice off // the last low surrogate char now and ensure the escaper can handle reading partial // surrogates, returning "Needs More Data". if (EndsWithValidSurrogatePair(accumInput)) { destination.AsSpan().Clear(); opStatus = _encoder.Encode(accumInput.AsSpan(0, accumInput.Length - 1), destination, out charsConsumed, out charsWritten, isFinalBlock: false); Assert.Equal(OperationStatus.NeedMoreData, opStatus); Assert.Equal(accumInput.Length - 2, charsConsumed); Assert.Equal(accumExpectedOutput.Length - outputToAppend.Length, charsWritten); Assert.Equal(accumExpectedOutput.Substring(0, accumExpectedOutput.Length - outputToAppend.Length), new string(destination, 0, charsWritten)); } } } protected void _RunEncodeUtf8_Battery(byte[][] inputs, string[] expectedOutputsAsUtf16) { byte[] accumInput = new byte[] { (byte)_disallowedChar }; byte[] accumExpectedOutput = Encoding.UTF8.GetBytes(GetExpectedEscapedRepresentation(new Rune(_disallowedChar))); byte[][] expectedOutputs = expectedOutputsAsUtf16.Select(Encoding.UTF8.GetBytes).ToArray(); // First, make sure we handle the simple "can't escape a single char to the buffer" case OperationStatus opStatus = _encoder.EncodeUtf8(accumInput, new byte[accumExpectedOutput.Length - 1], out int bytesConsumed, out int bytesWritten); Assert.Equal(OperationStatus.DestinationTooSmall, opStatus); Assert.Equal(0, bytesConsumed); Assert.Equal(0, bytesWritten); // Then, escape a single char to the destination buffer. // This skips the "find the first char to encode" fast path in TextEncoder.cs. byte[] destination = new byte[accumExpectedOutput.Length]; opStatus = _encoder.EncodeUtf8(accumInput, destination, out bytesConsumed, out bytesWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(1, bytesConsumed); Assert.Equal(destination.Length, bytesWritten); Assert.Equal(accumExpectedOutput, destination.ToArray()); // Now, in a loop, append inputs to the source span and test various edge cases of // destination too small vs. destination properly sized. Assert.Equal(expectedOutputs.Length, inputs.Length); for (int i = 0; i < inputs.Length; i++) { accumInput = accumInput.Concat(inputs[i]).ToArray(); byte[] outputToAppend = expectedOutputs[i]; // Test destination too small - we should make progress up until // the very last thing we appended to the input. destination = new byte[accumExpectedOutput.Length + outputToAppend.Length - 1]; opStatus = _encoder.EncodeUtf8(accumInput, destination, out bytesConsumed, out bytesWritten); Assert.Equal(OperationStatus.DestinationTooSmall, opStatus); Assert.Equal(accumInput.Length - inputs[i].Length, bytesConsumed); // should've consumed everything except the most recent appended data Assert.Equal(accumExpectedOutput.Length, bytesWritten); // should've escaped everything we consumed Assert.Equal(accumExpectedOutput, destination.AsSpan(0, bytesWritten).ToArray()); // Now test destination just right - we should consume the entire buffer successfully. accumExpectedOutput = accumExpectedOutput.Concat(outputToAppend).ToArray(); destination = new byte[accumExpectedOutput.Length]; opStatus = _encoder.EncodeUtf8(accumInput, destination, out bytesConsumed, out bytesWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(accumInput.Length, bytesConsumed); Assert.Equal(accumExpectedOutput.Length, bytesWritten); Assert.Equal(accumExpectedOutput, destination); // Now test destination oversized - we should consume the entire buffer successfully. destination = new byte[accumExpectedOutput.Length + 1]; opStatus = _encoder.EncodeUtf8(accumInput, destination, out bytesConsumed, out bytesWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(accumInput.Length, bytesConsumed); Assert.Equal(accumExpectedOutput.Length, bytesWritten); Assert.Equal(accumExpectedOutput, destination.AsSpan(0, bytesWritten).ToArray()); // Special-case: if the buffer ended with a legal supplementary scalar value, slice off // the last few bytes now and ensure the escaper can handle reading partial // values, returning "Needs More Data". if (EndsWithValidMultiByteUtf8Sequence(accumInput)) { destination.AsSpan().Clear(); opStatus = _encoder.EncodeUtf8(accumInput.AsSpan(0, accumInput.Length - 1), destination, out bytesConsumed, out bytesWritten, isFinalBlock: false); Assert.Equal(OperationStatus.NeedMoreData, opStatus); Assert.Equal(accumInput.Length - inputs[i].Length, bytesConsumed); Assert.Equal(accumExpectedOutput.Length - outputToAppend.Length, bytesWritten); Assert.Equal(accumExpectedOutput.AsSpan(0, accumExpectedOutput.Length - outputToAppend.Length).ToArray(), destination.AsSpan(0, bytesWritten).ToArray()); } } } private static bool EndsWithValidSurrogatePair(string input) { return input.Length >= 2 && char.IsHighSurrogate(input[input.Length - 2]) && char.IsLowSurrogate(input[input.Length - 1]); } private static bool EndsWithValidMultiByteUtf8Sequence(byte[] input) { for (int i = input.Length - 1; i >= 0; i--) { if (input[i] >= 0xC0) { return Rune.DecodeFromUtf8(input.AsSpan(i), out _, out int bytesConsumed) == OperationStatus.Done && i + bytesConsumed == input.Length; } } return false; // input was empty? } private protected abstract string GetExpectedEscapedRepresentation(Rune value); private string GetExpectedEscapedRepresentation(string value) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < value.Length;) { Rune.DecodeFromUtf16(value.AsSpan(i), out Rune nextRune, out int charsConsumed); builder.Append(GetExpectedEscapedRepresentation(nextRune)); i += charsConsumed; } return builder.ToString(); } void IDisposable.Dispose() { _boundedBytes.Dispose(); _boundedChars.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace System.Text.Encodings.Web.Tests { public class HtmlEncoderDefaultCommonTests : InboxEncoderCommonTestBase { public HtmlEncoderDefaultCommonTests() : base(HtmlEncoder.Default, allowedChar: 'a', disallowedChar: '&') { } private protected override string GetExpectedEscapedRepresentation(Rune value) { switch (value.Value) { case '<': return "&lt;"; case '>': return "&gt;"; case '&': return "&amp;"; case '\"': return "&quot;"; default: return FormattableString.Invariant($"&#x{(uint)value.Value:X};"); } } [Fact] public void EncodeUtf16_Battery() { string[] inputs = new string[] { "\n", "<", "a", "\u0234", // U+0234 LATIN SMALL LETTER L WITH CURL "\ud800", // standalone high surrogate "\U0001F415", // U+1F415 DOG "\udfff", // standalone low surrogate "\uFFFF", // end of BMP range "\U00010000", // beginning of supplementary range "\U0010FFFF", // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "&#xA;", "&lt;", "a", "&#x234;", "&#xFFFD;", // replaced standalone high surrogate with replacement char "&#x1F415;", "&#xFFFD;", // replaced standalone low surrogate with replacement char "&#xFFFF;", "&#x10000;", "&#x10FFFF;", }; _RunEncodeUtf16_Battery(inputs, expectedOutputs); } [Fact] public void EncodeUtf8_Battery() { byte[][] inputs = new byte[][] { new byte[] { (byte)'\n' }, new byte[] { (byte)'<' }, new byte[] { (byte)'a' }, new byte[] { 0xC8, 0xB4 }, // U+0234 LATIN SMALL LETTER L WITH CURL new byte[] { 0xFF }, // invalid byte new byte[] { 0xF0, 0x9F, 0x90, 0x95 }, // U+1F415 DOG new byte[] { 0x80 }, // standalone continuation character new byte[] { 0xC2 }, // standalone multi-byte sequence marker new byte[] { 0xEF, 0xBF, 0xBF }, // end of BMP range new byte[] { 0xF0, 0x90, 0x80, 0x80 }, // beginning of supplementary range new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "&#xA;", "&lt;", "a", "&#x234;", "&#xFFFD;", // replaced invalid byte "&#x1F415;", "&#xFFFD;", // replaced standalone continuation char "&#xFFFD;", // replaced standalone multi-byte sequence marker "&#xFFFF;", "&#x10000;", "&#x10FFFF;", }; _RunEncodeUtf8_Battery(inputs, expectedOutputs); } } public class JavaScriptEncoderDefaultCommonTests : InboxEncoderCommonTestBase { public JavaScriptEncoderDefaultCommonTests() : base(JavaScriptEncoder.Default, allowedChar: 'a', disallowedChar: '\"') { } private protected override string GetExpectedEscapedRepresentation(Rune value) { switch (value.Value) { case '\b': return "\\b"; case '\t': return "\\t"; case '\n': return "\\n"; case '\f': return "\\f"; case '\r': return "\\r"; case '\\': return "\\\\"; default: if (value.IsBmp) { return FormattableString.Invariant($"\\u{(uint)value.Value:X4}"); } else { Span<char> asUtf16 = stackalloc char[2]; bool succeeded = value.TryEncodeToUtf16(asUtf16, out int utf16CodeUnitCount); Assert.True(succeeded); Assert.Equal(2, utf16CodeUnitCount); return FormattableString.Invariant($"\\u{(uint)asUtf16[0]:X4}\\u{(uint)asUtf16[1]:X4}"); } } } [Fact] public void EncodeUtf16_Battery() { string[] inputs = new string[] { "\n", "a", "\u0234", // U+0234 LATIN SMALL LETTER L WITH CURL "\ud800", // standalone high surrogate "\U0001F415", // U+1F415 DOG "\udfff", // standalone low surrogate "\uFFFF", // end of BMP range "\U00010000", // beginning of supplementary range "\U0010FFFF", // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "\\n", "a", "\\u0234", "\\uFFFD", // replaced standalone high surrogate with replacement char "\\uD83D\\uDC15", "\\uFFFD", // replaced standalone low surrogate with replacement char "\\uFFFF", "\\uD800\\uDC00", "\\uDBFF\\uDFFF", }; _RunEncodeUtf16_Battery(inputs, expectedOutputs); } [Fact] public void EncodeUtf8_Battery() { byte[][] inputs = new byte[][] { new byte[] { (byte)'\n' }, new byte[] { (byte)'a' }, new byte[] { 0xC8, 0xB4 }, // U+0234 LATIN SMALL LETTER L WITH CURL new byte[] { 0xFF }, // invalid byte new byte[] { 0xF0, 0x9F, 0x90, 0x95 }, // U+1F415 DOG new byte[] { 0x80 }, // standalone continuation character new byte[] { 0xC2 }, // standalone multi-byte sequence marker new byte[] { 0xEF, 0xBF, 0xBF }, // end of BMP range new byte[] { 0xF0, 0x90, 0x80, 0x80 }, // beginning of supplementary range new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "\\n", "a", "\\u0234", "\\uFFFD", // replaced invalid byte "\\uD83D\\uDC15", "\\uFFFD", // replaced standalone continuation char "\\uFFFD", // replaced standalone multi-byte sequence marker "\\uFFFF", "\\uD800\\uDC00", "\\uDBFF\\uDFFF", }; _RunEncodeUtf8_Battery(inputs, expectedOutputs); } } public class JavaScriptEncoderRelaxedCommonTests : InboxEncoderCommonTestBase { public JavaScriptEncoderRelaxedCommonTests() : base(JavaScriptEncoder.UnsafeRelaxedJsonEscaping, allowedChar: 'a', disallowedChar: '\"') { } private protected override string GetExpectedEscapedRepresentation(Rune value) { switch (value.Value) { case '\b': return "\\b"; case '\t': return "\\t"; case '\n': return "\\n"; case '\f': return "\\f"; case '\r': return "\\r"; case '\\': return "\\\\"; case '\"': return "\\\""; default: if (value.IsBmp) { return FormattableString.Invariant($"\\u{(uint)value.Value:X4}"); } else { Span<char> asUtf16 = stackalloc char[2]; bool succeeded = value.TryEncodeToUtf16(asUtf16, out int utf16CodeUnitCount); Assert.True(succeeded); Assert.Equal(2, utf16CodeUnitCount); return FormattableString.Invariant($"\\u{(uint)asUtf16[0]:X4}\\u{(uint)asUtf16[1]:X4}"); } } } [Fact] public void EncodeUtf16_Battery() { string[] inputs = new string[] { "\n", "a", "\u0234", // U+0234 LATIN SMALL LETTER L WITH CURL "\ud800", // standalone high surrogate "\U0001F415", // U+1F415 DOG "\udfff", // standalone low surrogate "\uFFFF", // end of BMP range "\U00010000", // beginning of supplementary range "\U0010FFFF", // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "\\n", "a", "\u0234", // not escaped "\\uFFFD", // replaced standalone high surrogate with replacement char "\\uD83D\\uDC15", "\\uFFFD", // replaced standalone low surrogate with replacement char "\\uFFFF", "\\uD800\\uDC00", "\\uDBFF\\uDFFF", }; _RunEncodeUtf16_Battery(inputs, expectedOutputs); } [Fact] public void EncodeUtf8_Battery() { byte[][] inputs = new byte[][] { new byte[] { (byte)'\n' }, new byte[] { (byte)'a' }, new byte[] { 0xC8, 0xB4 }, // U+0234 LATIN SMALL LETTER L WITH CURL new byte[] { 0xFF }, // invalid byte new byte[] { 0xF0, 0x9F, 0x90, 0x95 }, // U+1F415 DOG new byte[] { 0x80 }, // standalone continuation character new byte[] { 0xC2 }, // standalone multi-byte sequence marker new byte[] { 0xEF, 0xBF, 0xBF }, // end of BMP range new byte[] { 0xF0, 0x90, 0x80, 0x80 }, // beginning of supplementary range new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "\\n", "a", "\u0234", // not escaped "\\uFFFD", // replaced invalid byte "\\uD83D\\uDC15", "\\uFFFD", // replaced standalone continuation char "\\uFFFD", // replaced standalone multi-byte sequence marker "\\uFFFF", "\\uD800\\uDC00", "\\uDBFF\\uDFFF", }; _RunEncodeUtf8_Battery(inputs, expectedOutputs); } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedValidCharsOnly() { _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedValidCharsOnly('\u2663'); // U+2663 BLACK CLUB SUIT } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedSomeCharsNeedEscaping() { _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedSomeCharsNeedEscaping('\u2663'); // U+2663 BLACK CLUB SUIT } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedAllValidChars() { _RunGetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedAllValidChars('\u2663'); // U+2663 BLACK CLUB SUIT } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedSomeCharsNeedEncoding() { _RunGetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedSomeCharsNeedEncoding('\u2663'); // U+2663 BLACK CLUB SUIT } } public class UrlEncoderDefaultCommonTests : InboxEncoderCommonTestBase { public UrlEncoderDefaultCommonTests() : base(UrlEncoder.Default, allowedChar: 'a', disallowedChar: '?') { } private protected override string GetExpectedEscapedRepresentation(Rune value) { Span<byte> asUtf8Bytes = stackalloc byte[4]; Span<char> hexEscaped = stackalloc char[12]; // worst-case 3 output chars per input UTF-8 code unit bool succeeded = value.TryEncodeToUtf8(asUtf8Bytes, out int utf8CodeUnitCount); Assert.True(succeeded); for (int i = 0; i < utf8CodeUnitCount; i++) { hexEscaped[i * 3] = '%'; HexConverter.ToCharsBuffer(asUtf8Bytes[i], hexEscaped, startingIndex: (i * 3) + 1); } return hexEscaped.Slice(0, utf8CodeUnitCount * 3).ToString(); } [Fact] public void EncodeUtf16_Battery() { string[] inputs = new string[] { "\n", "%", "a", "\u0234", // U+0234 LATIN SMALL LETTER L WITH CURL "\ud800", // standalone high surrogate "\U0001F415", // U+1F415 DOG "\udfff", // standalone low surrogate "\uFFFF", // end of BMP range "\U00010000", // beginning of supplementary range "\U0010FFFF", // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "%0A", "%25", "a", "%C8%B4", "%EF%BF%BD", // replaced standalone high surrogate with replacement char "%F0%9F%90%95", "%EF%BF%BD", // replaced standalone low surrogate with replacement char "%EF%BF%BF", "%F0%90%80%80", "%F4%8F%BF%BF", }; _RunEncodeUtf16_Battery(inputs, expectedOutputs); } [Fact] public void EncodeUtf8_Battery() { byte[][] inputs = new byte[][] { new byte[] { (byte)'\n' }, new byte[] { (byte)'%' }, new byte[] { (byte)'a' }, new byte[] { 0xC8, 0xB4 }, // U+0234 LATIN SMALL LETTER L WITH CURL new byte[] { 0xFF }, // invalid byte new byte[] { 0xF0, 0x9F, 0x90, 0x95 }, // U+1F415 DOG new byte[] { 0x80 }, // standalone continuation character new byte[] { 0xC2 }, // standalone multi-byte sequence marker new byte[] { 0xEF, 0xBF, 0xBF }, // end of BMP range new byte[] { 0xF0, 0x90, 0x80, 0x80 }, // beginning of supplementary range new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, // end of supplementary range }; // expected outputs correspond to the escaped form of the inputs above string[] expectedOutputs = new string[] { "%0A", "%25", "a", "%C8%B4", "%EF%BF%BD", // replaced invalid byte "%F0%9F%90%95", "%EF%BF%BD", // replaced standalone continuation char "%EF%BF%BD", // replaced standalone multi-byte sequence marker "%EF%BF%BF", "%F0%90%80%80", "%F4%8F%BF%BF", }; _RunEncodeUtf8_Battery(inputs, expectedOutputs); } } public abstract class InboxEncoderCommonTestBase : IDisposable { private readonly TextEncoder _encoder; private readonly BoundedMemory<byte> _boundedBytes = BoundedMemory.Allocate<byte>(4096); private readonly BoundedMemory<char> _boundedChars = BoundedMemory.Allocate<char>(4096); private readonly char _allowedChar; // representative allowed char for this encoder private readonly char _disallowedChar; // representative never-allowed char for this encoder // U+2D2E is in the Georgian Supplement block but is not currently assigned, hence disallowed by all inbox encoders. // U+2D2E is an interesting test case because both U+002D ('-') and U+002E ('.') are allowed by all inbox encoders, // so using U+2D2E exercises our UTF-16 -> ASCII narrowing paths to make sure that the narrowing process doesn't // inadvertently treat a single non-ASCII BMP char as two independent ASCII chars. IF U+2D2E is ever assigned in // the future, this could cause unit tests to fail, but we'll deal with that problem when (if?) the time comes. private const char BmpExtendedDisallowedChar = '\u2d2e'; protected InboxEncoderCommonTestBase(TextEncoder encoder, char allowedChar, char disallowedChar) { Assert.NotNull(encoder); _encoder = encoder; Assert.True(allowedChar <= 0x7F, "Test setup failure: Allowed char should be ASCII."); Assert.False(encoder.WillEncode(allowedChar), "Test setup failure: Encoder must say this character is allowed."); _allowedChar = allowedChar; Assert.True(disallowedChar <= 0x7F, "Test setup failure: Disallowed char should be ASCII."); Assert.True(encoder.WillEncode(disallowedChar), "Test setup failure: Encoder must say this character is disallowed."); _disallowedChar = disallowedChar; } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf16_AllDataValid() => _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedValidCharsOnly(_allowedChar); protected void _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedValidCharsOnly(char bmpAllowedChar) { // Loop from 96 elements all the way down to 0 elements, which tests that we're // not overrunning our read buffers. var span = _boundedChars.Span; _boundedChars.MakeWriteable(); span.Fill(bmpAllowedChar); // make buffer all-valid _boundedChars.MakeReadonly(); for (int i = 96; i >= 0; i--) { Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf16(span.Slice(span.Length - i))); } // Also check from the beginning of the buffer just in case there's some alignment weirdness // in the SIMD-optimized code that causes us to read past where we should. _boundedChars.MakeWriteable(); for (int i = 96; i >= 0; i--) { span[i] = _disallowedChar; // make this char invalid (ASCII) Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf16(span.Slice(0, i))); } } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf16_SomeCharsNeedEscaping() => _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedSomeCharsNeedEscaping(_allowedChar); protected void _RunGetIndexOfFirstCharacterToEncodeUtf16_BmpExtendedSomeCharsNeedEscaping(char bmpAllowedChar) { // Use a 31-element buffer since it will exercise all the different unrolled code paths. var span = _boundedChars.Span.Slice(0, 31); for (int i = 0; i < span.Length - 1; i++) { // First make this the only invalid char in the whole buffer. // Make sure we correctly identify the index which requires escaping. _boundedChars.MakeWriteable(); span.Fill(bmpAllowedChar); // make buffer all-valid span[i] = _disallowedChar; // make this char invalid (ASCII) _boundedChars.MakeReadonly(); Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf16(span)); _boundedChars.MakeWriteable(); span[i] = BmpExtendedDisallowedChar; // make this char invaid (BMP extended) _boundedChars.MakeReadonly(); Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf16(span)); // Use a bad standalone surrogate char instead of a disallowed char // and ensure we get the same index back. _boundedChars.MakeWriteable(); span[i] = '\ud800'; _boundedChars.MakeReadonly(); Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf16(span)); // Then make sure that we correctly identify this char as the *first* // char which requires escaping, even if the buffer contains more // requires-escaping chars after this. if (i < span.Length - 2) { _boundedChars.MakeWriteable(); span[i] = _disallowedChar; span[i + 1] = _disallowedChar; _boundedChars.MakeReadonly(); } Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf16(span)); } } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf8_AllDataValid() { // Loop from 96 elements all the way down to 0 elements, which tests that we're // not overrunning our read buffers. var span = _boundedBytes.Span; _boundedBytes.MakeWriteable(); span.Fill((byte)_allowedChar); // make buffer all-valid _boundedBytes.MakeReadonly(); for (int i = 96; i >= 0; i--) { Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(span.Length - i))); } // Also check from the beginning of the buffer just in case there's some alignment weirdness // in the SIMD-optimized code that causes us to read past where we should. _boundedBytes.MakeWriteable(); for (int i = 96; i >= 0; i--) { span[i] = (byte)_disallowedChar; // make this char invalid Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(0, i))); } } [Fact] public void GetIndexOfFirstCharacterToEncodeUtf8_SomeCharsNeedEscaping() { // Use a 31-element buffer since it will exercise all the different vectorized loops. var span = _boundedBytes.Span.Slice(0, 31); for (int i = 0; i < span.Length - 1; i++) { // First make this the only invalid char in the whole buffer. // Make sure we correctly identify the index which requires escaping. _boundedBytes.MakeWriteable(); span.Fill((byte)_allowedChar); // make buffer all-valid span[i] = (byte)_disallowedChar; // make this char invalid _boundedBytes.MakeReadonly(); Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf8(span)); // Then make sure that we correctly identify this char as the *first* // char which requires escaping, even if the buffer contains more // requires-escaping chars after this. if (i < span.Length - 2) { _boundedBytes.MakeWriteable(); span[i + 1] = (byte)_disallowedChar; _boundedBytes.MakeReadonly(); } Assert.Equal(i, _encoder.FindFirstCharacterToEncodeUtf8(span)); } } protected void _RunGetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedAllValidChars(char bmpAllowedChar) { Span<byte> allowedCharAsUtf8 = stackalloc byte[3]; Assert.True(new Rune(bmpAllowedChar).TryEncodeToUtf8(allowedCharAsUtf8, out int allowedCharUtf8CodeUnitCount)); allowedCharAsUtf8 = allowedCharAsUtf8.Slice(0, allowedCharUtf8CodeUnitCount); // Copy this character to the end of the buffer 12 times var span = _boundedBytes.Span; span = span.Slice(span.Length - allowedCharAsUtf8.Length * 12); _boundedBytes.MakeWriteable(); span.Clear(); for (int i = 0; i < 12; i++) { allowedCharAsUtf8.CopyTo(span.Slice(allowedCharAsUtf8.Length * i)); } _boundedBytes.MakeReadonly(); // And now make sure we identify all chars as allowed. for (int i = 0; i < 12; i++) { Assert.Equal(-1, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(allowedCharAsUtf8.Length * i))); } } protected void _RunGetIndexOfFirstCharacterToEncodeUtf8_BmpExtendedSomeCharsNeedEncoding(char bmpAllowedChar) { Assert.True(bmpAllowedChar >= 0x80, "Must be a non-ASCII char."); Span<byte> allowedCharAsUtf8 = stackalloc byte[3]; Assert.True(new Rune(bmpAllowedChar).TryEncodeToUtf8(allowedCharAsUtf8, out int allowedCharUtf8CodeUnitCount)); allowedCharAsUtf8 = allowedCharAsUtf8.Slice(0, allowedCharUtf8CodeUnitCount); // Copy this character to the end of the buffer 12 times var span = _boundedBytes.Span; span = span.Slice(span.Length - allowedCharAsUtf8.Length * 12); _boundedBytes.MakeWriteable(); span.Clear(); for (int i = 0; i < 12; i++) { allowedCharAsUtf8.CopyTo(span.Slice(allowedCharAsUtf8.Length * i)); } // And now make sure we identify bad chars as disallowed. // The last element in the span will be invalid, and we'll keep shrinking the span // so that the returned index changes on each iteration. for (int i = 0; i < 12; i++) { // First, corrupt the element by making it a standalone continuation byte. span[span.Length - allowedCharAsUtf8.Length] = 0xBF; Assert.Equal((11 - i) * allowedCharAsUtf8.Length, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(allowedCharAsUtf8.Length * i))); // Then, uncorrupt the element by making it a well-formed but never-allowed code point (U+009F is a never-allowed C1 control code point) span[span.Length - allowedCharAsUtf8.Length] = 0xC2; span[span.Length - allowedCharAsUtf8.Length + 1] = 0x9F; Assert.Equal((11 - i) * allowedCharAsUtf8.Length, _encoder.FindFirstCharacterToEncodeUtf8(span.Slice(allowedCharAsUtf8.Length * i))); } } [Fact] public unsafe void TryEncodeUnicodeScalar_AllowedBmpChar() { _boundedChars.MakeWriteable(); // First, try with enough space (two chars) in the destination buffer var destination = _boundedChars.Span; destination = destination.Slice(destination.Length - 2); destination.Clear(); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) { bool succeeded = _encoder.TryEncodeUnicodeScalar(_allowedChar, pBuf, destination.Length, out int numCharsWritten); Assert.True(succeeded); Assert.Equal(1, numCharsWritten); Assert.Equal(_allowedChar, destination[0]); // Should reflect char as-is } // Then, try with enough space (one char) in the destination buffer destination.Clear(); destination = destination.Slice(1); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) { bool succeeded = _encoder.TryEncodeUnicodeScalar(_allowedChar, pBuf, destination.Length, out int numCharsWritten); Assert.True(succeeded); Assert.Equal(1, numCharsWritten); Assert.Equal(_allowedChar, destination[0]); // Should reflect char as-is } // Finally, try with not enough space in the destination buffer destination.Clear(); destination = destination.Slice(1); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) // use MemoryMarshal so as to get a valid pointer { bool succeeded = _encoder.TryEncodeUnicodeScalar(_allowedChar, pBuf, destination.Length, out int numCharsWritten); Assert.False(succeeded); Assert.Equal(0, numCharsWritten); } } [Fact] public unsafe void TryEncodeUnicodeScalar_DisallowedBmpChar() { TryEncodeUnicodeScalar_DisallowedScalarCommon(new Rune(_disallowedChar)); } [Fact] public unsafe void TryEncodeUnicodeScalar_DisallowedSupplementaryChar() { TryEncodeUnicodeScalar_DisallowedScalarCommon(new Rune(0x1F604)); // U+1F604 SMILING FACE WITH OPEN MOUTH AND SMILING EYES } private unsafe void TryEncodeUnicodeScalar_DisallowedScalarCommon(Rune value) { _boundedChars.MakeWriteable(); string expectedEscaping = GetExpectedEscapedRepresentation(value); // First, try with enough space +1 in the destination buffer var destination = _boundedChars.Span; destination = destination.Slice(destination.Length - expectedEscaping.Length - 1); destination.Clear(); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) { bool succeeded = _encoder.TryEncodeUnicodeScalar(value.Value, pBuf, destination.Length, out int numCharsWritten); Assert.True(succeeded); Assert.Equal(expectedEscaping.Length, numCharsWritten); Assert.Equal(expectedEscaping, destination.Slice(0, expectedEscaping.Length).ToString()); } // Then, try with enough space +0 in the destination buffer destination.Clear(); destination = destination.Slice(1); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) { bool succeeded = _encoder.TryEncodeUnicodeScalar(value.Value, pBuf, destination.Length, out int numCharsWritten); Assert.True(succeeded); Assert.Equal(expectedEscaping.Length, numCharsWritten); Assert.Equal(expectedEscaping, destination.ToString()); } // Finally, try with not enough space in the destination buffer destination.Clear(); destination = destination.Slice(1); fixed (char* pBuf = &MemoryMarshal.GetReference(destination)) // use MemoryMarshal so as to get a valid pointer { bool succeeded = _encoder.TryEncodeUnicodeScalar(value.Value, pBuf, destination.Length, out int numCharsWritten); Assert.False(succeeded); Assert.Equal(0, numCharsWritten); } } protected void _RunEncodeUtf16_Battery(string[] inputs, string[] expectedOutputs) { string accumInput = _disallowedChar.ToString(); string accumExpectedOutput = GetExpectedEscapedRepresentation(new Rune(_disallowedChar)); // First, make sure we handle the simple "can't escape a single char to the buffer" case OperationStatus opStatus = _encoder.Encode(accumInput.AsSpan(), new char[accumExpectedOutput.Length - 1], out int charsConsumed, out int charsWritten); Assert.Equal(OperationStatus.DestinationTooSmall, opStatus); Assert.Equal(0, charsConsumed); Assert.Equal(0, charsWritten); // Then, escape a single char to the destination buffer. // This skips the "find the first char to encode" fast path in TextEncoder.cs. char[] destination = new char[accumExpectedOutput.Length]; opStatus = _encoder.Encode(accumInput.AsSpan(), destination, out charsConsumed, out charsWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(1, charsConsumed); Assert.Equal(destination.Length, charsWritten); Assert.Equal(accumExpectedOutput, new string(destination)); // Now, in a loop, append inputs to the source span and test various edge cases of // destination too small vs. destination properly sized. Assert.Equal(expectedOutputs.Length, inputs.Length); for (int i = 0; i < inputs.Length; i++) { accumInput += inputs[i]; string outputToAppend = expectedOutputs[i]; // Test destination too small - we should make progress up until // the very last thing we appended to the input. destination = new char[accumExpectedOutput.Length + outputToAppend.Length - 1]; opStatus = _encoder.Encode(accumInput.AsSpan(), destination, out charsConsumed, out charsWritten); Assert.Equal(OperationStatus.DestinationTooSmall, opStatus); Assert.Equal(accumInput.Length - inputs[i].Length, charsConsumed); // should've consumed everything except the most recent appended data Assert.Equal(accumExpectedOutput.Length, charsWritten); // should've escaped everything we consumed Assert.Equal(accumExpectedOutput, new string(destination, 0, charsWritten)); // Now test destination just right - we should consume the entire buffer successfully. accumExpectedOutput += outputToAppend; destination = new char[accumExpectedOutput.Length]; opStatus = _encoder.Encode(accumInput.AsSpan(), destination, out charsConsumed, out charsWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(accumInput.Length, charsConsumed); Assert.Equal(accumExpectedOutput.Length, charsWritten); Assert.Equal(accumExpectedOutput, new string(destination)); // Now test destination oversized - we should consume the entire buffer successfully. destination = new char[accumExpectedOutput.Length + 1]; opStatus = _encoder.Encode(accumInput.AsSpan(), destination, out charsConsumed, out charsWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(accumInput.Length, charsConsumed); Assert.Equal(accumExpectedOutput.Length, charsWritten); Assert.Equal(accumExpectedOutput, new string(destination, 0, charsWritten)); // Special-case: if the buffer ended with a legal supplementary scalar value, slice off // the last low surrogate char now and ensure the escaper can handle reading partial // surrogates, returning "Needs More Data". if (EndsWithValidSurrogatePair(accumInput)) { destination.AsSpan().Clear(); opStatus = _encoder.Encode(accumInput.AsSpan(0, accumInput.Length - 1), destination, out charsConsumed, out charsWritten, isFinalBlock: false); Assert.Equal(OperationStatus.NeedMoreData, opStatus); Assert.Equal(accumInput.Length - 2, charsConsumed); Assert.Equal(accumExpectedOutput.Length - outputToAppend.Length, charsWritten); Assert.Equal(accumExpectedOutput.Substring(0, accumExpectedOutput.Length - outputToAppend.Length), new string(destination, 0, charsWritten)); } } } protected void _RunEncodeUtf8_Battery(byte[][] inputs, string[] expectedOutputsAsUtf16) { byte[] accumInput = new byte[] { (byte)_disallowedChar }; byte[] accumExpectedOutput = Encoding.UTF8.GetBytes(GetExpectedEscapedRepresentation(new Rune(_disallowedChar))); byte[][] expectedOutputs = expectedOutputsAsUtf16.Select(Encoding.UTF8.GetBytes).ToArray(); // First, make sure we handle the simple "can't escape a single char to the buffer" case OperationStatus opStatus = _encoder.EncodeUtf8(accumInput, new byte[accumExpectedOutput.Length - 1], out int bytesConsumed, out int bytesWritten); Assert.Equal(OperationStatus.DestinationTooSmall, opStatus); Assert.Equal(0, bytesConsumed); Assert.Equal(0, bytesWritten); // Then, escape a single char to the destination buffer. // This skips the "find the first char to encode" fast path in TextEncoder.cs. byte[] destination = new byte[accumExpectedOutput.Length]; opStatus = _encoder.EncodeUtf8(accumInput, destination, out bytesConsumed, out bytesWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(1, bytesConsumed); Assert.Equal(destination.Length, bytesWritten); Assert.Equal(accumExpectedOutput, destination.ToArray()); // Now, in a loop, append inputs to the source span and test various edge cases of // destination too small vs. destination properly sized. Assert.Equal(expectedOutputs.Length, inputs.Length); for (int i = 0; i < inputs.Length; i++) { accumInput = accumInput.Concat(inputs[i]).ToArray(); byte[] outputToAppend = expectedOutputs[i]; // Test destination too small - we should make progress up until // the very last thing we appended to the input. destination = new byte[accumExpectedOutput.Length + outputToAppend.Length - 1]; opStatus = _encoder.EncodeUtf8(accumInput, destination, out bytesConsumed, out bytesWritten); Assert.Equal(OperationStatus.DestinationTooSmall, opStatus); Assert.Equal(accumInput.Length - inputs[i].Length, bytesConsumed); // should've consumed everything except the most recent appended data Assert.Equal(accumExpectedOutput.Length, bytesWritten); // should've escaped everything we consumed Assert.Equal(accumExpectedOutput, destination.AsSpan(0, bytesWritten).ToArray()); // Now test destination just right - we should consume the entire buffer successfully. accumExpectedOutput = accumExpectedOutput.Concat(outputToAppend).ToArray(); destination = new byte[accumExpectedOutput.Length]; opStatus = _encoder.EncodeUtf8(accumInput, destination, out bytesConsumed, out bytesWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(accumInput.Length, bytesConsumed); Assert.Equal(accumExpectedOutput.Length, bytesWritten); Assert.Equal(accumExpectedOutput, destination); // Now test destination oversized - we should consume the entire buffer successfully. destination = new byte[accumExpectedOutput.Length + 1]; opStatus = _encoder.EncodeUtf8(accumInput, destination, out bytesConsumed, out bytesWritten); Assert.Equal(OperationStatus.Done, opStatus); Assert.Equal(accumInput.Length, bytesConsumed); Assert.Equal(accumExpectedOutput.Length, bytesWritten); Assert.Equal(accumExpectedOutput, destination.AsSpan(0, bytesWritten).ToArray()); // Special-case: if the buffer ended with a legal supplementary scalar value, slice off // the last few bytes now and ensure the escaper can handle reading partial // values, returning "Needs More Data". if (EndsWithValidMultiByteUtf8Sequence(accumInput)) { destination.AsSpan().Clear(); opStatus = _encoder.EncodeUtf8(accumInput.AsSpan(0, accumInput.Length - 1), destination, out bytesConsumed, out bytesWritten, isFinalBlock: false); Assert.Equal(OperationStatus.NeedMoreData, opStatus); Assert.Equal(accumInput.Length - inputs[i].Length, bytesConsumed); Assert.Equal(accumExpectedOutput.Length - outputToAppend.Length, bytesWritten); Assert.Equal(accumExpectedOutput.AsSpan(0, accumExpectedOutput.Length - outputToAppend.Length).ToArray(), destination.AsSpan(0, bytesWritten).ToArray()); } } } private static bool EndsWithValidSurrogatePair(string input) { return input.Length >= 2 && char.IsHighSurrogate(input[input.Length - 2]) && char.IsLowSurrogate(input[input.Length - 1]); } private static bool EndsWithValidMultiByteUtf8Sequence(byte[] input) { for (int i = input.Length - 1; i >= 0; i--) { if (input[i] >= 0xC0) { return Rune.DecodeFromUtf8(input.AsSpan(i), out _, out int bytesConsumed) == OperationStatus.Done && i + bytesConsumed == input.Length; } } return false; // input was empty? } private protected abstract string GetExpectedEscapedRepresentation(Rune value); private string GetExpectedEscapedRepresentation(string value) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < value.Length;) { Rune.DecodeFromUtf16(value.AsSpan(i), out Rune nextRune, out int charsConsumed); builder.Append(GetExpectedEscapedRepresentation(nextRune)); i += charsConsumed; } return builder.ToString(); } void IDisposable.Dispose() { _boundedBytes.Dispose(); _boundedChars.Dispose(); } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Scheduling/SpoolingTask.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SpoolingTask.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// A factory class to execute spooling logic. /// </summary> internal static class SpoolingTask { //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. Executes synchronously, // and by the time this API has returned all of the results have been produced. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // channels - the producer-consumer channels // taskScheduler - the task manager on which to execute // internal static void SpoolStopAndGo<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, SynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler) { Debug.Assert(partitions.PartitionCount == channels.Length); Debug.Assert(groupState != null); // Ensure all tasks in this query are parented under a common root. Task rootTask = new Task( () => { int maxToRunInParallel = partitions.PartitionCount - 1; // A stop-and-go merge uses the current thread for one task and then blocks before // returning to the caller, until all results have been accumulated. We do this by // running the last partition on the calling thread. for (int i = 0; i < maxToRunInParallel; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]); asyncTask.RunAsynchronously(taskScheduler); } TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel); // Run one task synchronously on the current thread. QueryTask syncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>( maxToRunInParallel, groupState, partitions[maxToRunInParallel], channels[maxToRunInParallel]); syncTask.RunSynchronously(taskScheduler); }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // We don't want to return until the task is finished. Run it on the calling thread. rootTask.RunSynchronously(taskScheduler); // Wait for the query to complete, propagate exceptions, and so on. // For pipelined queries, this step happens in the async enumerator. groupState.QueryEnd(false); } //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. Runs asynchronously. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // channels - the producer-consumer channels // taskScheduler - the task manager on which to execute // [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] internal static void SpoolPipeline<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, AsynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler) { Debug.Assert(partitions.PartitionCount == channels.Length); Debug.Assert(groupState != null); // Ensure all tasks in this query are parented under a common root. Because this // is a pipelined query, we detach it from the parent (to avoid blocking the calling // thread), and run the query on a separate thread. Task rootTask = new Task( () => { // Create tasks that will enumerate the partitions in parallel. Because we're pipelining, // we will begin running these tasks in parallel and then return. for (int i = 0; i < partitions.PartitionCount; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new PipelineSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]); asyncTask.RunAsynchronously(taskScheduler); } }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // And schedule it for execution. This is done after beginning to ensure no thread tries to // end the query before its root task has been recorded properly. rootTask.Start(taskScheduler); // We don't call QueryEnd here; when we return, the query is still executing, and the // last enumerator to be disposed of will call QueryEnd for us. } //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. This is a for-all style // execution, meaning that the query will be run fully (for effect) before returning // and that there are no channels into which data will be queued. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // taskScheduler - the task manager on which to execute // internal static void SpoolForAll<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, TaskScheduler taskScheduler) { Debug.Assert(groupState != null); // Ensure all tasks in this query are parented under a common root. Task rootTask = new Task( () => { int maxToRunInParallel = partitions.PartitionCount - 1; // Create tasks that will enumerate the partitions in parallel "for effect"; in other words, // no data will be placed into any kind of producer-consumer channel. for (int i = 0; i < maxToRunInParallel; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i]); asyncTask.RunAsynchronously(taskScheduler); } TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel); // Run one task synchronously on the current thread. QueryTask syncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(maxToRunInParallel, groupState, partitions[maxToRunInParallel]); syncTask.RunSynchronously(taskScheduler); }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // We don't want to return until the task is finished. Run it on the calling thread. rootTask.RunSynchronously(taskScheduler); // Wait for the query to complete, propagate exceptions, and so on. // For pipelined queries, this step happens in the async enumerator. groupState.QueryEnd(false); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> internal sealed class StopAndGoSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The destination channel into which data is placed. This can be null if we are // enumerating "for effect", e.g. forall loop. private readonly SynchronousChannel<TInputOutput> _destination; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal StopAndGoSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, SynchronousChannel<TInputOutput> destination) : base(taskIndex, groupState) { Debug.Assert(source != null); _source = source; _destination = destination; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream, placing each element // into the destination channel. TInputOutput current = default(TInputOutput)!; TIgnoreKey keyUnused = default(TIgnoreKey)!; QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source; SynchronousChannel<TInputOutput> destination = _destination; CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken; destination.Init(); while (source.MoveNext(ref current!, ref keyUnused)) { // If an abort has been requested, stop this worker immediately. if (cancelToken.IsCancellationRequested) { break; } destination.Enqueue(current); } } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Signal that we are done, in the case of asynchronous consumption. if (_destination != null) { _destination.SetDone(); } // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _source.Dispose(); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] internal sealed class PipelineSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The destination channel into which data is placed. This can be null if we are // enumerating "for effect", e.g. forall loop. private readonly AsynchronousChannel<TInputOutput> _destination; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal PipelineSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, AsynchronousChannel<TInputOutput> destination) : base(taskIndex, groupState) { Debug.Assert(source != null); _source = source; _destination = destination; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream, placing each element // into the destination channel. TInputOutput current = default(TInputOutput)!; TIgnoreKey keyUnused = default(TIgnoreKey)!; QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source; AsynchronousChannel<TInputOutput> destination = _destination; CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken; while (source.MoveNext(ref current!, ref keyUnused)) { // If an abort has been requested, stop this worker immediately. if (cancelToken.IsCancellationRequested) { break; } destination.Enqueue(current); } // Flush remaining data to the query consumer in preparation for channel shutdown. destination.FlushBuffers(); } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Signal that we are done, in the case of asynchronous consumption. if (_destination != null) { _destination.SetDone(); } // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _source.Dispose(); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> internal sealed class ForAllSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal ForAllSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source) : base(taskIndex, groupState) { Debug.Assert(source != null); _source = source; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream for effect. TInputOutput currentUnused = default(TInputOutput)!; TIgnoreKey keyUnused = default(TIgnoreKey)!; //Note: this only ever runs with a ForAll operator, and ForAllEnumerator performs cancellation checks while (_source.MoveNext(ref currentUnused!, ref keyUnused)) ; } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Dispose of the source enumerator _source.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SpoolingTask.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// A factory class to execute spooling logic. /// </summary> internal static class SpoolingTask { //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. Executes synchronously, // and by the time this API has returned all of the results have been produced. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // channels - the producer-consumer channels // taskScheduler - the task manager on which to execute // internal static void SpoolStopAndGo<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, SynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler) { Debug.Assert(partitions.PartitionCount == channels.Length); Debug.Assert(groupState != null); // Ensure all tasks in this query are parented under a common root. Task rootTask = new Task( () => { int maxToRunInParallel = partitions.PartitionCount - 1; // A stop-and-go merge uses the current thread for one task and then blocks before // returning to the caller, until all results have been accumulated. We do this by // running the last partition on the calling thread. for (int i = 0; i < maxToRunInParallel; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]); asyncTask.RunAsynchronously(taskScheduler); } TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel); // Run one task synchronously on the current thread. QueryTask syncTask = new StopAndGoSpoolingTask<TInputOutput, TIgnoreKey>( maxToRunInParallel, groupState, partitions[maxToRunInParallel], channels[maxToRunInParallel]); syncTask.RunSynchronously(taskScheduler); }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // We don't want to return until the task is finished. Run it on the calling thread. rootTask.RunSynchronously(taskScheduler); // Wait for the query to complete, propagate exceptions, and so on. // For pipelined queries, this step happens in the async enumerator. groupState.QueryEnd(false); } //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. Runs asynchronously. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // channels - the producer-consumer channels // taskScheduler - the task manager on which to execute // [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] internal static void SpoolPipeline<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, AsynchronousChannel<TInputOutput>[] channels, TaskScheduler taskScheduler) { Debug.Assert(partitions.PartitionCount == channels.Length); Debug.Assert(groupState != null); // Ensure all tasks in this query are parented under a common root. Because this // is a pipelined query, we detach it from the parent (to avoid blocking the calling // thread), and run the query on a separate thread. Task rootTask = new Task( () => { // Create tasks that will enumerate the partitions in parallel. Because we're pipelining, // we will begin running these tasks in parallel and then return. for (int i = 0; i < partitions.PartitionCount; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new PipelineSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i], channels[i]); asyncTask.RunAsynchronously(taskScheduler); } }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // And schedule it for execution. This is done after beginning to ensure no thread tries to // end the query before its root task has been recorded properly. rootTask.Start(taskScheduler); // We don't call QueryEnd here; when we return, the query is still executing, and the // last enumerator to be disposed of will call QueryEnd for us. } //----------------------------------------------------------------------------------- // Creates and begins execution of a new spooling task. This is a for-all style // execution, meaning that the query will be run fully (for effect) before returning // and that there are no channels into which data will be queued. // // Arguments: // groupState - values for inter-task communication // partitions - the producer enumerators // taskScheduler - the task manager on which to execute // internal static void SpoolForAll<TInputOutput, TIgnoreKey>( QueryTaskGroupState groupState, PartitionedStream<TInputOutput, TIgnoreKey> partitions, TaskScheduler taskScheduler) { Debug.Assert(groupState != null); // Ensure all tasks in this query are parented under a common root. Task rootTask = new Task( () => { int maxToRunInParallel = partitions.PartitionCount - 1; // Create tasks that will enumerate the partitions in parallel "for effect"; in other words, // no data will be placed into any kind of producer-consumer channel. for (int i = 0; i < maxToRunInParallel; i++) { TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] asynchronously", i); QueryTask asyncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(i, groupState, partitions[i]); asyncTask.RunAsynchronously(taskScheduler); } TraceHelpers.TraceInfo("SpoolingTask::Spool: Running partition[{0}] synchronously", maxToRunInParallel); // Run one task synchronously on the current thread. QueryTask syncTask = new ForAllSpoolingTask<TInputOutput, TIgnoreKey>(maxToRunInParallel, groupState, partitions[maxToRunInParallel]); syncTask.RunSynchronously(taskScheduler); }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // We don't want to return until the task is finished. Run it on the calling thread. rootTask.RunSynchronously(taskScheduler); // Wait for the query to complete, propagate exceptions, and so on. // For pipelined queries, this step happens in the async enumerator. groupState.QueryEnd(false); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> internal sealed class StopAndGoSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The destination channel into which data is placed. This can be null if we are // enumerating "for effect", e.g. forall loop. private readonly SynchronousChannel<TInputOutput> _destination; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal StopAndGoSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, SynchronousChannel<TInputOutput> destination) : base(taskIndex, groupState) { Debug.Assert(source != null); _source = source; _destination = destination; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream, placing each element // into the destination channel. TInputOutput current = default(TInputOutput)!; TIgnoreKey keyUnused = default(TIgnoreKey)!; QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source; SynchronousChannel<TInputOutput> destination = _destination; CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken; destination.Init(); while (source.MoveNext(ref current!, ref keyUnused)) { // If an abort has been requested, stop this worker immediately. if (cancelToken.IsCancellationRequested) { break; } destination.Enqueue(current); } } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Signal that we are done, in the case of asynchronous consumption. if (_destination != null) { _destination.SetDone(); } // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _source.Dispose(); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> [System.Runtime.Versioning.UnsupportedOSPlatform("browser")] internal sealed class PipelineSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The destination channel into which data is placed. This can be null if we are // enumerating "for effect", e.g. forall loop. private readonly AsynchronousChannel<TInputOutput> _destination; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal PipelineSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, AsynchronousChannel<TInputOutput> destination) : base(taskIndex, groupState) { Debug.Assert(source != null); _source = source; _destination = destination; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream, placing each element // into the destination channel. TInputOutput current = default(TInputOutput)!; TIgnoreKey keyUnused = default(TIgnoreKey)!; QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source = _source; AsynchronousChannel<TInputOutput> destination = _destination; CancellationToken cancelToken = _groupState.CancellationState.MergedCancellationToken; while (source.MoveNext(ref current!, ref keyUnused)) { // If an abort has been requested, stop this worker immediately. if (cancelToken.IsCancellationRequested) { break; } destination.Enqueue(current); } // Flush remaining data to the query consumer in preparation for channel shutdown. destination.FlushBuffers(); } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Signal that we are done, in the case of asynchronous consumption. if (_destination != null) { _destination.SetDone(); } // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _source.Dispose(); } } /// <summary> /// A spooling task handles marshaling data from a producer to a consumer. It's given /// a single enumerator object that contains all of the production algorithms, a single /// destination channel from which consumers draw results, and (optionally) a /// synchronization primitive using which to notify asynchronous consumers. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TIgnoreKey"></typeparam> internal sealed class ForAllSpoolingTask<TInputOutput, TIgnoreKey> : SpoolingTaskBase { // The data source from which to pull data. private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; //----------------------------------------------------------------------------------- // Creates, but does not execute, a new spooling task. // // Arguments: // taskIndex - the unique index of this task // source - the producer enumerator // destination - the destination channel into which to spool elements // // Assumptions: // Source cannot be null, although the other arguments may be. // internal ForAllSpoolingTask( int taskIndex, QueryTaskGroupState groupState, QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source) : base(taskIndex, groupState) { Debug.Assert(source != null); _source = source; } //----------------------------------------------------------------------------------- // This method is responsible for enumerating results and enqueueing them to // the output channel(s) as appropriate. Each base class implements its own. // protected override void SpoolingWork() { // We just enumerate over the entire source data stream for effect. TInputOutput currentUnused = default(TInputOutput)!; TIgnoreKey keyUnused = default(TIgnoreKey)!; //Note: this only ever runs with a ForAll operator, and ForAllEnumerator performs cancellation checks while (_source.MoveNext(ref currentUnused!, ref keyUnused)) ; } //----------------------------------------------------------------------------------- // Ensure we signal that the channel is complete. // protected override void SpoolingFinally() { // Call the base implementation. base.SpoolingFinally(); // Dispose of the source enumerator _source.Dispose(); } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/WebSocketReceiveResult.cs
// 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; namespace System.Net.WebSockets { public class WebSocketReceiveResult { public WebSocketReceiveResult(int count, WebSocketMessageType messageType, bool endOfMessage) : this(count, messageType, endOfMessage, null, null) { } public WebSocketReceiveResult(int count, WebSocketMessageType messageType, bool endOfMessage, WebSocketCloseStatus? closeStatus, string? closeStatusDescription) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } Count = count; EndOfMessage = endOfMessage; MessageType = messageType; CloseStatus = closeStatus; CloseStatusDescription = closeStatusDescription; } public int Count { get; } public bool EndOfMessage { get; } public WebSocketMessageType MessageType { get; } public WebSocketCloseStatus? CloseStatus { get; } public string? CloseStatusDescription { get; } } }
// 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; namespace System.Net.WebSockets { public class WebSocketReceiveResult { public WebSocketReceiveResult(int count, WebSocketMessageType messageType, bool endOfMessage) : this(count, messageType, endOfMessage, null, null) { } public WebSocketReceiveResult(int count, WebSocketMessageType messageType, bool endOfMessage, WebSocketCloseStatus? closeStatus, string? closeStatusDescription) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } Count = count; EndOfMessage = endOfMessage; MessageType = messageType; CloseStatus = closeStatus; CloseStatusDescription = closeStatusDescription; } public int Count { get; } public bool EndOfMessage { get; } public WebSocketMessageType MessageType { get; } public WebSocketCloseStatus? CloseStatus { get; } public string? CloseStatusDescription { get; } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/Common/src/System/Security/Cryptography/Asn1/DigestInfoAsn.xml
<?xml version="1.0" encoding="utf-8" ?> <asn:Sequence xmlns:asn="http://schemas.dot.net/asnxml/201808/" name="DigestInfoAsn" namespace="System.Security.Cryptography.Asn1"> <!-- https://tools.ietf.org/html/rfc2313#section-10.1.2 DigestInfo ::= SEQUENCE { digestAlgorithm DigestAlgorithmIdentifier, digest Digest } DigestAlgorithmIdentifier ::= AlgorithmIdentifier Digest ::= OCTET STRING --> <asn:AsnType name="DigestAlgorithm" typeName="System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn" /> <asn:OctetString name="Digest" /> </asn:Sequence>
<?xml version="1.0" encoding="utf-8" ?> <asn:Sequence xmlns:asn="http://schemas.dot.net/asnxml/201808/" name="DigestInfoAsn" namespace="System.Security.Cryptography.Asn1"> <!-- https://tools.ietf.org/html/rfc2313#section-10.1.2 DigestInfo ::= SEQUENCE { digestAlgorithm DigestAlgorithmIdentifier, digest Digest } DigestAlgorithmIdentifier ::= AlgorithmIdentifier Digest ::= OCTET STRING --> <asn:AsnType name="DigestAlgorithm" typeName="System.Security.Cryptography.Asn1.AlgorithmIdentifierAsn" /> <asn:OctetString name="Digest" /> </asn:Sequence>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Data.OleDb/src/OleDbConnection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Text; namespace System.Data.OleDb { using SysTx = Transactions; // wraps the OLEDB IDBInitialize interface which represents a connection // Notes about connection pooling // 1. Connection pooling isn't supported on Win95 // 2. Only happens if we use the IDataInitialize or IDBPromptInitialize interfaces // it won't happen if you directly create the provider and set its properties // 3. First call on IDBInitialize must be Initialize, can't QI for any other interfaces before that [DefaultEvent("InfoMessage")] public sealed partial class OleDbConnection : DbConnection, ICloneable, IDbConnection { private static readonly object EventInfoMessage = new object(); public OleDbConnection(string? connectionString) : this() { ConnectionString = connectionString; } private OleDbConnection(OleDbConnection connection) : this() { // Clone CopyFrom(connection); } [ DefaultValue(""), Editor("Microsoft.VSDesigner.Data.ADO.Design.OleDbConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), #pragma warning disable 618 // ignore obsolete warning about RecommendedAsConfigurable to use SettingsBindableAttribute RecommendedAsConfigurable(true), #pragma warning restore 618 SettingsBindable(true), RefreshProperties(RefreshProperties.All), AllowNull ] public override string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(value); } } private OleDbConnectionString? OleDbConnectionStringValue { get { return (OleDbConnectionString?)ConnectionOptions; } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override int ConnectionTimeout { get { object? value; if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_TIMEOUT); } else { OleDbConnectionString? constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.ConnectTimeout : ADP.DefaultConnectionTimeout; } if (null != value) { return Convert.ToInt32(value, CultureInfo.InvariantCulture); } else { return ADP.DefaultConnectionTimeout; } } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override string Database { get { OleDbConnectionString? constr = (OleDbConnectionString?)UserConnectionOptions; object? value = (null != constr) ? constr.InitialCatalog : string.Empty; if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { OleDbConnectionInternal connection = GetOpenConnection(); if (null != connection) { if (connection.HasSession) { value = GetDataSourceValue(OleDbPropertySetGuid.DataSource, ODB.DBPROP_CURRENTCATALOG); } else { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_CATALOG); } } else { constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.InitialCatalog : string.Empty; } } return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } [ Browsable(true) ] public override string DataSource { get { OleDbConnectionString? constr = (OleDbConnectionString?)UserConnectionOptions; object? value = (null != constr) ? constr.DataSource : string.Empty; if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_DATASOURCE); if ((null == value) || ((value is string) && (0 == (value as string)!.Length))) { value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DATASOURCENAME); } } else { constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.DataSource : string.Empty; } } return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } internal bool IsOpen { get { return (null != GetOpenConnection()); } } internal OleDbTransaction? LocalTransaction { set { OleDbConnectionInternal openConnection = GetOpenConnection(); if (null != openConnection) { openConnection.LocalTransaction = value; } } } [ Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public string Provider { get { OleDbConnectionString? constr = this.OleDbConnectionStringValue; string? value = ((null != constr) ? constr.ConvertValueToString(ODB.Provider, null) : null); return ((null != value) ? value : string.Empty); } } internal OleDbConnectionPoolGroupProviderInfo ProviderInfo { get { Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo"); return (OleDbConnectionPoolGroupProviderInfo)PoolGroup!.ProviderInfo!; } } public override string ServerVersion { get { return InnerConnection.ServerVersion; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), // ResDescriptionAttribute(SR.DbConnection_State), ] public override ConnectionState State { get { return InnerConnection.State; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public void ResetState() { if (IsOpen) { object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_CONNECTIONSTATUS); if (value is int) { int connectionStatus = (int)value; switch (connectionStatus) { case ODB.DBPROPVAL_CS_UNINITIALIZED: // provider closed on us case ODB.DBPROPVAL_CS_COMMUNICATIONFAILURE: // broken connection GetOpenConnection().DoomThisConnection(); NotifyWeakReference(OleDbReferenceCollection.Canceling); Close(); break; case ODB.DBPROPVAL_CS_INITIALIZED: // everything is okay break; default: // have to assume everything is okay Debug.Assert(false, $"Unknown 'Connection Status' value {connectionStatus.ToString("G", CultureInfo.InvariantCulture)}"); break; } } } } public event OleDbInfoMessageEventHandler? InfoMessage { add { Events.AddHandler(EventInfoMessage, value); } remove { Events.RemoveHandler(EventInfoMessage, value); } } internal UnsafeNativeMethods.ICommandText? ICommandText() { Debug.Assert(null != GetOpenConnection(), "ICommandText closed"); return GetOpenConnection().ICommandText(); } private IDBPropertiesWrapper IDBProperties() { Debug.Assert(null != GetOpenConnection(), "IDBProperties closed"); return GetOpenConnection().IDBProperties(); } internal IOpenRowsetWrapper IOpenRowset() { Debug.Assert(null != GetOpenConnection(), "IOpenRowset closed"); return GetOpenConnection().IOpenRowset(); } internal int SqlSupport() { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SqlSupport"); return this.OleDbConnectionStringValue.GetSqlSupport(this); } internal bool SupportMultipleResults() { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportMultipleResults"); return this.OleDbConnectionStringValue.GetSupportMultipleResults(this); } internal bool SupportIRow(OleDbCommand cmd) { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportIRow"); return this.OleDbConnectionStringValue.GetSupportIRow(this, cmd); } internal int QuotedIdentifierCase() { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString QuotedIdentifierCase"); int quotedIdentifierCase; object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_QUOTEDIDENTIFIERCASE); if (value is int) {// not OleDbPropertyStatus quotedIdentifierCase = (int)value; } else { quotedIdentifierCase = -1; } return quotedIdentifierCase; } public new OleDbTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Unspecified); } public new OleDbTransaction BeginTransaction(IsolationLevel isolationLevel) { return (OleDbTransaction)InnerConnection.BeginTransaction(isolationLevel); } public override void ChangeDatabase(string value) { CheckStateOpen(ADP.ChangeDatabase); if (string.IsNullOrWhiteSpace(value)) { throw ADP.EmptyDatabaseName(); } SetDataSourcePropertyValue(OleDbPropertySetGuid.DataSource, ODB.DBPROP_CURRENTCATALOG, ODB.Current_Catalog, true, value); } internal void CheckStateOpen(string method) { ConnectionState state = State; if (ConnectionState.Open != state) { throw ADP.OpenConnectionRequired(method, state); } } object ICloneable.Clone() { OleDbConnection clone = new OleDbConnection(this); return clone; } public override void Close() { InnerConnection.CloseConnection(this, ConnectionFactory); // does not require GC.KeepAlive(this) because of OnStateChange } public new OleDbCommand CreateCommand() { return new OleDbCommand("", this); } private void DisposeMe(bool disposing) { if (disposing) { // release mananged objects if (DesignMode) { // release the object pool in design-mode so that // native MDAC can be properly released during shutdown OleDbConnection.ReleaseObjectPool(); } } } // suppress this message - we cannot use SafeHandle here. protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = InnerConnection.BeginTransaction(isolationLevel); // InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the DbTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } internal object? GetDataSourcePropertyValue(Guid propertySet, int propertyID) { OleDbConnectionInternal connection = GetOpenConnection(); return connection.GetDataSourcePropertyValue(propertySet, propertyID); } internal object? GetDataSourceValue(Guid propertySet, int propertyID) { object? value = GetDataSourcePropertyValue(propertySet, propertyID); if ((value is OleDbPropertyStatus) || Convert.IsDBNull(value)) { value = null; } return value; } private OleDbConnectionInternal GetOpenConnection() { DbConnectionInternal innerConnection = InnerConnection; return (innerConnection as OleDbConnectionInternal)!; } internal void GetLiteralQuotes(string method, out string quotePrefix, out string quoteSuffix) { CheckStateOpen(method); OleDbConnectionPoolGroupProviderInfo info = ProviderInfo; if (info.HasQuoteFix) { quotePrefix = info.QuotePrefix!; quoteSuffix = info.QuoteSuffix!; } else { OleDbConnectionInternal connection = GetOpenConnection(); quotePrefix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_PREFIX) ?? ""; quoteSuffix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_SUFFIX) ?? ""; info.SetQuoteFix(quotePrefix, quoteSuffix); } } public DataTable? GetOleDbSchemaTable(Guid schema, object?[]? restrictions) { CheckStateOpen(ADP.GetOleDbSchemaTable); OleDbConnectionInternal connection = GetOpenConnection(); if (OleDbSchemaGuid.DbInfoLiterals == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildInfoLiterals(); } throw ODB.InvalidRestrictionsDbInfoLiteral("restrictions"); } else if (OleDbSchemaGuid.SchemaGuids == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildSchemaGuids(); } throw ODB.InvalidRestrictionsSchemaGuids("restrictions"); } else if (OleDbSchemaGuid.DbInfoKeywords == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildInfoKeywords(); } throw ODB.InvalidRestrictionsDbInfoKeywords("restrictions"); } if (connection.SupportSchemaRowset(schema)) { return connection.GetSchemaRowset(schema, restrictions); } else { using (IDBSchemaRowsetWrapper wrapper = connection.IDBSchemaRowset()) { if (null == wrapper.Value) { throw ODB.SchemaRowsetsNotSupported(Provider); } } throw ODB.NotSupportedSchemaTable(schema, this); } } internal DataTable? GetSchemaRowset(Guid schema, object?[] restrictions) { Debug.Assert(null != GetOpenConnection(), "GetSchemaRowset closed"); return GetOpenConnection().GetSchemaRowset(schema, restrictions); } internal bool HasLiveReader(OleDbCommand cmd) { bool result = false; OleDbConnectionInternal openConnection = GetOpenConnection(); if (null != openConnection) { result = openConnection.HasLiveReader(cmd); } return result; } internal void OnInfoMessage(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode) { OleDbInfoMessageEventHandler? handler = (OleDbInfoMessageEventHandler?)Events[EventInfoMessage]; if (null != handler) { try { OleDbException exception = OleDbException.CreateException(errorInfo, errorCode, null); OleDbInfoMessageEventArgs e = new OleDbInfoMessageEventArgs(exception); handler(this, e); } catch (Exception e) { // eat the exception // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } } public override void Open() { InnerConnection.OpenConnection(this, ConnectionFactory); // need to manually enlist in some cases, because // native OLE DB doesn't know about SysTx transactions. if ((0 != (ODB.DBPROPVAL_OS_TXNENLISTMENT & ((OleDbConnectionString)(this.ConnectionOptions!)).OleDbServices)) && ADP.NeedManualEnlistment()) { GetOpenConnection().EnlistTransactionInternal(SysTx.Transaction.Current); } } internal void SetDataSourcePropertyValue(Guid propertySet, int propertyID, string description, bool required, object value) { CheckStateOpen(ADP.SetProperties); OleDbHResult hr; using (IDBPropertiesWrapper idbProperties = IDBProperties()) { using (DBPropSet propSet = DBPropSet.CreateProperty(propertySet, propertyID, required, value)) { hr = idbProperties.Value.SetProperties(propSet.PropertySetCount, propSet); if (hr < 0) { Exception? e = OleDbConnection.ProcessResults(hr, null, this); if (OleDbHResult.DB_E_ERRORSOCCURRED == hr) { StringBuilder builder = new StringBuilder(); Debug.Assert(1 == propSet.PropertySetCount, "too many PropertySets"); ItagDBPROP[] dbprops = propSet.GetPropertySet(0, out propertySet); Debug.Assert(1 == dbprops.Length, "too many Properties"); ODB.PropsetSetFailure(builder, description, dbprops[0].dwStatus); e = ODB.PropsetSetFailure(builder.ToString(), e!); } if (null != e) { throw e; } } else { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } } } internal bool SupportSchemaRowset(Guid schema) { return GetOpenConnection().SupportSchemaRowset(schema); } internal OleDbTransaction? ValidateTransaction(OleDbTransaction? transaction, string method) { return GetOpenConnection().ValidateTransaction(transaction, method); } internal static Exception? ProcessResults(OleDbHResult hresult, OleDbConnection? connection, object? src) { if ((0 <= (int)hresult) && ((null == connection) || (null == connection.Events[EventInfoMessage]))) { SafeNativeMethods.Wrapper.ClearErrorInfo(); return null; } // ErrorInfo object is to be checked regardless the hresult returned by the function called Exception? e = null; OleDbHResult hr = UnsafeNativeMethods.GetErrorInfo(0, out UnsafeNativeMethods.IErrorInfo? errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo if ((OleDbHResult.S_OK == hr) && (null != errorInfo)) { try { if (hresult < 0) { // UNDONE: if authentication failed - throw a unique exception object type //if (/*OLEDB_Error.DB_SEC_E_AUTH_FAILED*/unchecked((int)0x80040E4D) == hr) { //} //else if (/*OLEDB_Error.DB_E_CANCELED*/unchecked((int)0x80040E4E) == hr) { //} // else { e = OleDbException.CreateException(errorInfo, hresult, null); //} if (OleDbHResult.DB_E_OBJECTOPEN == hresult) { e = ADP.OpenReaderExists(e); } ResetState(connection); } else if (null != connection) { connection.OnInfoMessage(errorInfo, hresult); } } finally { UnsafeNativeMethods.ReleaseErrorInfoObject(errorInfo); } } else if (0 < hresult) { // @devnote: OnInfoMessage with no ErrorInfo } else if ((int)hresult < 0) { e = ODB.NoErrorInformation((null != connection) ? connection.Provider : null, hresult, null); // OleDbException ResetState(connection); } if (null != e) { ADP.TraceExceptionAsReturnValue(e); } return e; } // @devnote: should be multithread safe public static void ReleaseObjectPool() { OleDbConnectionString.ReleaseObjectPool(); OleDbConnectionInternal.ReleaseObjectPool(); OleDbConnectionFactory.SingletonInstance.ClearAllPools(); } private static void ResetState(OleDbConnection? connection) { if (null != connection) { connection.ResetState(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Text; namespace System.Data.OleDb { using SysTx = Transactions; // wraps the OLEDB IDBInitialize interface which represents a connection // Notes about connection pooling // 1. Connection pooling isn't supported on Win95 // 2. Only happens if we use the IDataInitialize or IDBPromptInitialize interfaces // it won't happen if you directly create the provider and set its properties // 3. First call on IDBInitialize must be Initialize, can't QI for any other interfaces before that [DefaultEvent("InfoMessage")] public sealed partial class OleDbConnection : DbConnection, ICloneable, IDbConnection { private static readonly object EventInfoMessage = new object(); public OleDbConnection(string? connectionString) : this() { ConnectionString = connectionString; } private OleDbConnection(OleDbConnection connection) : this() { // Clone CopyFrom(connection); } [ DefaultValue(""), Editor("Microsoft.VSDesigner.Data.ADO.Design.OleDbConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"), #pragma warning disable 618 // ignore obsolete warning about RecommendedAsConfigurable to use SettingsBindableAttribute RecommendedAsConfigurable(true), #pragma warning restore 618 SettingsBindable(true), RefreshProperties(RefreshProperties.All), AllowNull ] public override string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(value); } } private OleDbConnectionString? OleDbConnectionStringValue { get { return (OleDbConnectionString?)ConnectionOptions; } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public override int ConnectionTimeout { get { object? value; if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_TIMEOUT); } else { OleDbConnectionString? constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.ConnectTimeout : ADP.DefaultConnectionTimeout; } if (null != value) { return Convert.ToInt32(value, CultureInfo.InvariantCulture); } else { return ADP.DefaultConnectionTimeout; } } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override string Database { get { OleDbConnectionString? constr = (OleDbConnectionString?)UserConnectionOptions; object? value = (null != constr) ? constr.InitialCatalog : string.Empty; if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { OleDbConnectionInternal connection = GetOpenConnection(); if (null != connection) { if (connection.HasSession) { value = GetDataSourceValue(OleDbPropertySetGuid.DataSource, ODB.DBPROP_CURRENTCATALOG); } else { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_CATALOG); } } else { constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.InitialCatalog : string.Empty; } } return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } [ Browsable(true) ] public override string DataSource { get { OleDbConnectionString? constr = (OleDbConnectionString?)UserConnectionOptions; object? value = (null != constr) ? constr.DataSource : string.Empty; if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_DATASOURCE); if ((null == value) || ((value is string) && (0 == (value as string)!.Length))) { value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DATASOURCENAME); } } else { constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.DataSource : string.Empty; } } return Convert.ToString(value, CultureInfo.InvariantCulture)!; } } internal bool IsOpen { get { return (null != GetOpenConnection()); } } internal OleDbTransaction? LocalTransaction { set { OleDbConnectionInternal openConnection = GetOpenConnection(); if (null != openConnection) { openConnection.LocalTransaction = value; } } } [ Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public string Provider { get { OleDbConnectionString? constr = this.OleDbConnectionStringValue; string? value = ((null != constr) ? constr.ConvertValueToString(ODB.Provider, null) : null); return ((null != value) ? value : string.Empty); } } internal OleDbConnectionPoolGroupProviderInfo ProviderInfo { get { Debug.Assert(null != this.PoolGroup, "PoolGroup must never be null when accessing ProviderInfo"); return (OleDbConnectionPoolGroupProviderInfo)PoolGroup!.ProviderInfo!; } } public override string ServerVersion { get { return InnerConnection.ServerVersion; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), // ResDescriptionAttribute(SR.DbConnection_State), ] public override ConnectionState State { get { return InnerConnection.State; } } [EditorBrowsable(EditorBrowsableState.Advanced)] public void ResetState() { if (IsOpen) { object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_CONNECTIONSTATUS); if (value is int) { int connectionStatus = (int)value; switch (connectionStatus) { case ODB.DBPROPVAL_CS_UNINITIALIZED: // provider closed on us case ODB.DBPROPVAL_CS_COMMUNICATIONFAILURE: // broken connection GetOpenConnection().DoomThisConnection(); NotifyWeakReference(OleDbReferenceCollection.Canceling); Close(); break; case ODB.DBPROPVAL_CS_INITIALIZED: // everything is okay break; default: // have to assume everything is okay Debug.Assert(false, $"Unknown 'Connection Status' value {connectionStatus.ToString("G", CultureInfo.InvariantCulture)}"); break; } } } } public event OleDbInfoMessageEventHandler? InfoMessage { add { Events.AddHandler(EventInfoMessage, value); } remove { Events.RemoveHandler(EventInfoMessage, value); } } internal UnsafeNativeMethods.ICommandText? ICommandText() { Debug.Assert(null != GetOpenConnection(), "ICommandText closed"); return GetOpenConnection().ICommandText(); } private IDBPropertiesWrapper IDBProperties() { Debug.Assert(null != GetOpenConnection(), "IDBProperties closed"); return GetOpenConnection().IDBProperties(); } internal IOpenRowsetWrapper IOpenRowset() { Debug.Assert(null != GetOpenConnection(), "IOpenRowset closed"); return GetOpenConnection().IOpenRowset(); } internal int SqlSupport() { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SqlSupport"); return this.OleDbConnectionStringValue.GetSqlSupport(this); } internal bool SupportMultipleResults() { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportMultipleResults"); return this.OleDbConnectionStringValue.GetSupportMultipleResults(this); } internal bool SupportIRow(OleDbCommand cmd) { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportIRow"); return this.OleDbConnectionStringValue.GetSupportIRow(this, cmd); } internal int QuotedIdentifierCase() { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString QuotedIdentifierCase"); int quotedIdentifierCase; object? value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_QUOTEDIDENTIFIERCASE); if (value is int) {// not OleDbPropertyStatus quotedIdentifierCase = (int)value; } else { quotedIdentifierCase = -1; } return quotedIdentifierCase; } public new OleDbTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Unspecified); } public new OleDbTransaction BeginTransaction(IsolationLevel isolationLevel) { return (OleDbTransaction)InnerConnection.BeginTransaction(isolationLevel); } public override void ChangeDatabase(string value) { CheckStateOpen(ADP.ChangeDatabase); if (string.IsNullOrWhiteSpace(value)) { throw ADP.EmptyDatabaseName(); } SetDataSourcePropertyValue(OleDbPropertySetGuid.DataSource, ODB.DBPROP_CURRENTCATALOG, ODB.Current_Catalog, true, value); } internal void CheckStateOpen(string method) { ConnectionState state = State; if (ConnectionState.Open != state) { throw ADP.OpenConnectionRequired(method, state); } } object ICloneable.Clone() { OleDbConnection clone = new OleDbConnection(this); return clone; } public override void Close() { InnerConnection.CloseConnection(this, ConnectionFactory); // does not require GC.KeepAlive(this) because of OnStateChange } public new OleDbCommand CreateCommand() { return new OleDbCommand("", this); } private void DisposeMe(bool disposing) { if (disposing) { // release mananged objects if (DesignMode) { // release the object pool in design-mode so that // native MDAC can be properly released during shutdown OleDbConnection.ReleaseObjectPool(); } } } // suppress this message - we cannot use SafeHandle here. protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = InnerConnection.BeginTransaction(isolationLevel); // InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the DbTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } internal object? GetDataSourcePropertyValue(Guid propertySet, int propertyID) { OleDbConnectionInternal connection = GetOpenConnection(); return connection.GetDataSourcePropertyValue(propertySet, propertyID); } internal object? GetDataSourceValue(Guid propertySet, int propertyID) { object? value = GetDataSourcePropertyValue(propertySet, propertyID); if ((value is OleDbPropertyStatus) || Convert.IsDBNull(value)) { value = null; } return value; } private OleDbConnectionInternal GetOpenConnection() { DbConnectionInternal innerConnection = InnerConnection; return (innerConnection as OleDbConnectionInternal)!; } internal void GetLiteralQuotes(string method, out string quotePrefix, out string quoteSuffix) { CheckStateOpen(method); OleDbConnectionPoolGroupProviderInfo info = ProviderInfo; if (info.HasQuoteFix) { quotePrefix = info.QuotePrefix!; quoteSuffix = info.QuoteSuffix!; } else { OleDbConnectionInternal connection = GetOpenConnection(); quotePrefix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_PREFIX) ?? ""; quoteSuffix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_SUFFIX) ?? ""; info.SetQuoteFix(quotePrefix, quoteSuffix); } } public DataTable? GetOleDbSchemaTable(Guid schema, object?[]? restrictions) { CheckStateOpen(ADP.GetOleDbSchemaTable); OleDbConnectionInternal connection = GetOpenConnection(); if (OleDbSchemaGuid.DbInfoLiterals == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildInfoLiterals(); } throw ODB.InvalidRestrictionsDbInfoLiteral("restrictions"); } else if (OleDbSchemaGuid.SchemaGuids == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildSchemaGuids(); } throw ODB.InvalidRestrictionsSchemaGuids("restrictions"); } else if (OleDbSchemaGuid.DbInfoKeywords == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildInfoKeywords(); } throw ODB.InvalidRestrictionsDbInfoKeywords("restrictions"); } if (connection.SupportSchemaRowset(schema)) { return connection.GetSchemaRowset(schema, restrictions); } else { using (IDBSchemaRowsetWrapper wrapper = connection.IDBSchemaRowset()) { if (null == wrapper.Value) { throw ODB.SchemaRowsetsNotSupported(Provider); } } throw ODB.NotSupportedSchemaTable(schema, this); } } internal DataTable? GetSchemaRowset(Guid schema, object?[] restrictions) { Debug.Assert(null != GetOpenConnection(), "GetSchemaRowset closed"); return GetOpenConnection().GetSchemaRowset(schema, restrictions); } internal bool HasLiveReader(OleDbCommand cmd) { bool result = false; OleDbConnectionInternal openConnection = GetOpenConnection(); if (null != openConnection) { result = openConnection.HasLiveReader(cmd); } return result; } internal void OnInfoMessage(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode) { OleDbInfoMessageEventHandler? handler = (OleDbInfoMessageEventHandler?)Events[EventInfoMessage]; if (null != handler) { try { OleDbException exception = OleDbException.CreateException(errorInfo, errorCode, null); OleDbInfoMessageEventArgs e = new OleDbInfoMessageEventArgs(exception); handler(this, e); } catch (Exception e) { // eat the exception // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } } public override void Open() { InnerConnection.OpenConnection(this, ConnectionFactory); // need to manually enlist in some cases, because // native OLE DB doesn't know about SysTx transactions. if ((0 != (ODB.DBPROPVAL_OS_TXNENLISTMENT & ((OleDbConnectionString)(this.ConnectionOptions!)).OleDbServices)) && ADP.NeedManualEnlistment()) { GetOpenConnection().EnlistTransactionInternal(SysTx.Transaction.Current); } } internal void SetDataSourcePropertyValue(Guid propertySet, int propertyID, string description, bool required, object value) { CheckStateOpen(ADP.SetProperties); OleDbHResult hr; using (IDBPropertiesWrapper idbProperties = IDBProperties()) { using (DBPropSet propSet = DBPropSet.CreateProperty(propertySet, propertyID, required, value)) { hr = idbProperties.Value.SetProperties(propSet.PropertySetCount, propSet); if (hr < 0) { Exception? e = OleDbConnection.ProcessResults(hr, null, this); if (OleDbHResult.DB_E_ERRORSOCCURRED == hr) { StringBuilder builder = new StringBuilder(); Debug.Assert(1 == propSet.PropertySetCount, "too many PropertySets"); ItagDBPROP[] dbprops = propSet.GetPropertySet(0, out propertySet); Debug.Assert(1 == dbprops.Length, "too many Properties"); ODB.PropsetSetFailure(builder, description, dbprops[0].dwStatus); e = ODB.PropsetSetFailure(builder.ToString(), e!); } if (null != e) { throw e; } } else { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } } } internal bool SupportSchemaRowset(Guid schema) { return GetOpenConnection().SupportSchemaRowset(schema); } internal OleDbTransaction? ValidateTransaction(OleDbTransaction? transaction, string method) { return GetOpenConnection().ValidateTransaction(transaction, method); } internal static Exception? ProcessResults(OleDbHResult hresult, OleDbConnection? connection, object? src) { if ((0 <= (int)hresult) && ((null == connection) || (null == connection.Events[EventInfoMessage]))) { SafeNativeMethods.Wrapper.ClearErrorInfo(); return null; } // ErrorInfo object is to be checked regardless the hresult returned by the function called Exception? e = null; OleDbHResult hr = UnsafeNativeMethods.GetErrorInfo(0, out UnsafeNativeMethods.IErrorInfo? errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo if ((OleDbHResult.S_OK == hr) && (null != errorInfo)) { try { if (hresult < 0) { // UNDONE: if authentication failed - throw a unique exception object type //if (/*OLEDB_Error.DB_SEC_E_AUTH_FAILED*/unchecked((int)0x80040E4D) == hr) { //} //else if (/*OLEDB_Error.DB_E_CANCELED*/unchecked((int)0x80040E4E) == hr) { //} // else { e = OleDbException.CreateException(errorInfo, hresult, null); //} if (OleDbHResult.DB_E_OBJECTOPEN == hresult) { e = ADP.OpenReaderExists(e); } ResetState(connection); } else if (null != connection) { connection.OnInfoMessage(errorInfo, hresult); } } finally { UnsafeNativeMethods.ReleaseErrorInfoObject(errorInfo); } } else if (0 < hresult) { // @devnote: OnInfoMessage with no ErrorInfo } else if ((int)hresult < 0) { e = ODB.NoErrorInformation((null != connection) ? connection.Provider : null, hresult, null); // OleDbException ResetState(connection); } if (null != e) { ADP.TraceExceptionAsReturnValue(e); } return e; } // @devnote: should be multithread safe public static void ReleaseObjectPool() { OleDbConnectionString.ReleaseObjectPool(); OleDbConnectionInternal.ReleaseObjectPool(); OleDbConnectionFactory.SingletonInstance.ClearAllPools(); } private static void ResetState(OleDbConnection? connection) { if (null != connection) { connection.ResetState(); } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./docs/design/features/StringDeduplication.md
# String Deduplication ## **Problem Space** Duplicated strings have been frequently observed in managed heaps. In some user scenarios they can take up most of the heap. Folks have been doing their own string deduplication. One of our first party customers did their own deduplication and were able to reduce the heap size by >70% but they could not do this for all workloads they have; only when they can find a feasible place to do so. A general opt in solution in the runtime would help reduce the heap size significantly for scenarios with a large percentage taken up by duplicated strings. ## **Glossary** Dedup - string deduplication is often shortened to dedup in this document. ## **Design goals** This is an opt-in feature and should have no performance penalty when it’s off. And by default it’s off. When it’s on, we aim to – - Only deduplicate strings in old generations of the GC heap. - Not increase the STW pauses for ephemeral GCs. - Not regress string allocation speed. - Provide static analysis and runtime checks to detect patterns incompatible with string deduping. This is required to enable customers to opt-in into this feature with confidence. ## Details #### **History** The string deduplication feature has been brought up before. See [runtime issue #9022](https://github.com/dotnet/runtime/issues/9022) for discussion. And a proof of concept was gracefully [attempted](https://github.com/dotnet/coreclr/pull/15135) by [@Rattenkrieg](https://github.com/Rattenkrieg) before. But it was incomplete and the design didn’t have the kind of perf characteristics desired – it had most of the logic in GC vs outside GC. An example of a user implemented string deduplication is Roslyn’s [StringTable utility](https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/Portable/InternalUtilities/StringTable.cs). #### **Customer impact estimation and validation** As a general rule we want to have this for all features we add to the runtime. Issue #[9022](https://github.com/dotnet/runtime/issues/9022) It mentioned some general data: “The expectation is that typical apps have 20% of their GC heap be strings. Some measurements we have seen is that for at least some applications, 10-30% of strings all may be duplicated, so this might save 2-3% of the GC heap. Not huge, but the feature is not that difficult either.” But keep in mind that this is an *average* - specific scenarios could have much higher percentage of duplicated strings. I have heard from customers who had much more dramatic heap reduction when they eliminated duplicated strings. Those are scenarios that would benefit from this feature the most. There are 2 sources of data we could get – - Our dump database. We can ask the TI team to help us look at the general percent of duplicated strings on the GC heap. It would be useful to also provide tooling to help users to check how much space duplicated strings take. Some internal folks have written tooling for this but it requires work to ship. - We already know of teams that can benefit from deduping. We should start a conversation with them to collect some data to have a rough idea about the baseline and make sure we have a way to verify private builds with them. #### **Design outline** This is an opt in feature. When the runtime detects it’s turned on, it creates a dedup thread to do the work. Detection of duplicated strings is done by looking into a hash table. The key into this hash table is the hash code of the content of a string. Detailed description of this detection is later in this doc. As the dedup thread goes through the old generations linearly, it looks for references to a string object (denoted by the method table) and either calculates or looks up the hash code of that string to see if it already exists in the hash table. If so it will attempt to change the reference to point to that string with a CAS operation. If this fails, which means some other thread changed the reference at the mean time, we simply ignore this and move on. We expect the CAS failure rate to be very low. Since the new string reference we will write to the heap has the exact same type info, it means BGC can read either the old or the new reference and will get the same size info so deduping would not conflict with BGC concurrent mark. It does not conflict with BGC sweep because BGC sweep does not read references inside an object. The dedup hash table acts as weak references to the strings. Depending on the scenario we might choose to null out these weak references or not (if it’s more performant to rebuild the hash table). If we we do the former these weak references would be treated as short weak handles so the following will happen before we scan for finalization - - During BGC final mark phase we will need to null out the strings that are not marked in the hash table. This can be made concurrent. - During a full blocking GC we will need to null out the strings that are not marked in the hash table, and relocate the ones that got promoted if we are doing a compacting GC. **Alternate design points** - Should we create multiple threads to do the work? Deduping can be done leisurely, so it doesn’t merit having multiple threads. - Can we use an existing thread to do the work on? The finalizer thread is something that’s idling most of the time. However there are already plenty of types of work scheduled to potentially run on the finalizer thread so adding yet another thing, especially an opt in feature, can get messy. #### **Which strings to dedup** Only strings allocated on the managed heap will be considered for deduplication. And only the ones that live in the old generations, meaning gen2 an LOH, will be considered. Deduping in young generations would be unproductive as they will likely die very soon. It would be extremely unproductive if the copy we are deduping to actually lived in young gens. #### **Calculating hash codes and large string consideration** Currently calling GetHashCode of a string calculates a 32-bit hash code. This is not stored anywhere, unlike the default hash code that’s stored either in the syncblk or a syncblk entry, depending whether the syncblk is also used by something else like locking. As the deduping thread goes through the heap it will calculate the 32-bit hash code and actually install it. However, a 32-bit hash code means we always need to check for collision by actually comparing the string content if the hash code is the same. And for large strings having to compare the string content could be very costly. For LOH compaction we already allocate a padding object for each large object (which currently takes up at most 0.4% of LOH space on 64-bit). We could make this padding object 1-ptr size larger and store the address of the string it’s deduped too. Likewise we can also use this to store the fact “this is the copy the hash table keeps track of so no need to dedup”. This way we can avoid having to do the detection multiple times for the same string. Below illustrates a scenario where large strings are deduplicated. `pad | s0 | pad | s1 | pad | s0_1` `obj0 (-> s0) | obj1 (-> s0_1) | obj2 (->s1) | obj3 (->s0_1) | obj4 (->s1) ` Each string obj, ie, s*, is a string on LOH and has a padding object in front of it which is not shown. s0_1 has the same content as s0. s1 has the same hash code but not the same content. "obj->s" means obj points to a string object s, or has a ref to s. So obj0 has a ref to s0, obj1 has a ref to s0_1, obj2 has a ref to s1 and so on. 1. As we go through the heap, we see obj0 which points to s0. 2. s0’s hash is calculated which we use to look into the hash table. 3. We see that no entries exist for that hash so we create an entry for it and in s0’s padding indicates that it’s stored in the hash table, ie, it’s the copy we keep. 4. Then we see obj1 which points to s0_1 whose hash doesn’t exist yet. We calculate the hash for s0_1, and see that there’s an entry for this hash already in the hash table, now we compare the content and see that it’s the same, now we store s0 in the padding object before s0_1 and change obj1’s ref to point to s0. 5. Then we see obj2 and calculate s1’s hash. We notice an entry already exists for that hash so we compare the content and the content is not the same as s0’s. So we enter s1 into the hash table and indicate that it’s stored in the hash table. 6. Then we see obj3, and s0_1 indicates that it should be deduped to s0 so we change obj3’s ref to point to s0_1 right away. 7. Then we see obj4 which points to s1 and s1 indicates it’s stored in the hash table so we don’t need to dedup. Since we know the size of a string object trivially, we know which strings are on LOH. **Situations when we choose to not dedup** - If `InterlockCompareExchangePointer` fails because the ref was modified while we were finding a copy to dedup to (or insert into the hash table), we skip this ref. - If too many collisions exist for a hash code, we skip deduping for strings with that hash code. This avoids the DoS attack by creating too many strings for the same hash. - If the string is too large. At some point going through a very large string to calculate its hash code will become simply not worth the effort. We'll need to do some perf investigation to figure out a good limit. **Alternate design points** - Should we calculate the hash codes for SOH strings as gen1 GCs promote them into gen2? This would increase gen1 pause. - Should we dedup while creating LOH strings? This would reduce LOH string allocation speed and potentially by a lot. #### **How often to dedup** If there’s no new objects that get into gen2/LOH, there’s no need to run dedup as the duplicates would have already been eliminated (mostly) during the last dedup cycle. So we should use the new amount of objects these generations get to determine how often to dedup, ie, taking the following factors into consideration - - We know when new LOH strings are allocated (all LOH allocations are done via C++ helpers in gchelpers.cpp), we can take the accumulative size of new LOH strings till it reaches a certain percentage of LOH before starting the next dedup cycle. - We know how much is promoted into gen2 and we can also wait till a certain percentage of gen2 consists of newly promoted memory before starting the next dedup cycle. #### **Compatibility** The following scenarios become problematic or more problematic when deduping is on so we need ways to help users find them. - Mutating the string content Strings are supposed to be immutable. However in unsafe code you can change the string content after it’s created. Changing string content already asking for trouble without deduping – you could be changing the interned copy which means you are modifying someone else’s string which could cause completely unpredictable results for them. The most common way is to use the fixed keyword: ```c# fixed (char* p = str) { p[0] = 'C'; } ``` There are other ways such as `((char*)(gcHandlePointingToString.AddrOfPinnedObject())) = 'c';` Or `Unsafe.AsRef (in str.GetPinnableReference()) = 'c';` - Locking on a string Locking on a string object is already discouraged due to a string can be interned. Having string dedup on can make this problematic more often if the string you called lock on is now deduped to a different string object. - Reference equality This example illustrates an example of `ReferenceEquals` that will not work if `_field` was deduped to a different string reference by the time the assignment to a2 happens. ```c# string _field; void Test() { _field = new string('a', 1); string a1 = _field; Thread.Sleep(1000); string a2 = _field; // This assert can fail with string deduping turned on Debug.Assert(ReferenceEquals(a1,a2)); } ``` **Runtime assistance to help with these scenarios** - Static analysis For .NET 5.0, there’s a static analysis [plan](https://github.com/dotnet/runtime/issues/30740). Verifying if string content is mutated can be part of that analysis suite. It would also be beneficial to have VS do this verification and give you a warning when you are mutating string content. To start with we will provide analysis for the following – 1. Using the fixed keyword to modify string content. I’m seeing that there are almost 600 places in libraries that do `fixed (char*` but hopefully most of them do not actually modify the string content. We should definitely be encouraging folks to switch to using `string.Create` like what [PR#31700](https://github.com/dotnet/runtime/pull/31700) did. 2. Using lock on a string object. - Reference equality checks on strings Since `ReferenceEquals` is performance critical API, we cannot do checks in its implementation. Checks will be done by how it's jitted - when the JIT sees that there are two object references being compared for equality, when a special diagnostics flag is set, it can jit a call to a helper method to do that and that helper method can produce diagnostics when the code is trying to compare identity of two strings. We do have some libraries that rely on `ReferenceEquals`. We need to figure out what to do about them. See discussion [here](https://github.com/dotnet/runtime/pull/31971#pullrequestreview-355531406). - Additional checks in heap verification Heap verification will now include checks to verify that no one changes the string content after it’s hash is computed. This can be turned on when a certain level of COMPlus_HeapVerify is specified. - Stress mode Instead of waiting till the productive moment to start the next deduping cycle, we can have a stress mode where we dedup randomly to catch problems sooner, same idea as GC stress to detect GC holes sooner. We could even artificially create duplicates in this stress mode to find places that depend on object identity. - Backup nonconcurrent dedup mode If you are running into these problematic scenarios and cannot make changes, and you can tolerate longer STW (Stop-The-World) pauses, we will provide a mode where deduping is completely done in either a full blocking GC or during the STW pause of a BGC. Obviously this would make BGC’s STW pauses much, much longer. This would basically just call the function that the dedup thread calls, but in these STW pauses. If you use a CPU profiler you should be able to see preciously how long the dedup part takes during the STW pause. We will either provide this as an API (GC.DeduplicateStrings) or as a config that only does dedup during full blocking GCs. The former is flexible and can give you detailed info such as how much space deduplicating strings saved. You could call this leisurely at a time when you know longer latency can be tolerated (eg, the server instance is taken out of rotation so you can tolerate a long pause). #### **Potential future work** **Experimenting with RTM** We might see some performance gains using RTM (Restricted Transactional Memory) on machines with large L1 caches but this is a P2 item. After we have the software solution implemented it would be easy to experiment with this. However, I have doubts it would give perf gain in most scenarios since looking into the hash table is quite a bit of work for RTM and likely will give high abort rate. **Deduping other types of objects** We might consider to not limit deduping to just strings. There was a discussion in [runtime issue #12628](https://github.com/dotnet/runtime/issues/12628). **Deduping long lived references on stack** There might be merit to look into deduping long lived refs on the stack. The amount of work it requires and the return makes it low priority but it may help with some corner cases.
# String Deduplication ## **Problem Space** Duplicated strings have been frequently observed in managed heaps. In some user scenarios they can take up most of the heap. Folks have been doing their own string deduplication. One of our first party customers did their own deduplication and were able to reduce the heap size by >70% but they could not do this for all workloads they have; only when they can find a feasible place to do so. A general opt in solution in the runtime would help reduce the heap size significantly for scenarios with a large percentage taken up by duplicated strings. ## **Glossary** Dedup - string deduplication is often shortened to dedup in this document. ## **Design goals** This is an opt-in feature and should have no performance penalty when it’s off. And by default it’s off. When it’s on, we aim to – - Only deduplicate strings in old generations of the GC heap. - Not increase the STW pauses for ephemeral GCs. - Not regress string allocation speed. - Provide static analysis and runtime checks to detect patterns incompatible with string deduping. This is required to enable customers to opt-in into this feature with confidence. ## Details #### **History** The string deduplication feature has been brought up before. See [runtime issue #9022](https://github.com/dotnet/runtime/issues/9022) for discussion. And a proof of concept was gracefully [attempted](https://github.com/dotnet/coreclr/pull/15135) by [@Rattenkrieg](https://github.com/Rattenkrieg) before. But it was incomplete and the design didn’t have the kind of perf characteristics desired – it had most of the logic in GC vs outside GC. An example of a user implemented string deduplication is Roslyn’s [StringTable utility](https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/Portable/InternalUtilities/StringTable.cs). #### **Customer impact estimation and validation** As a general rule we want to have this for all features we add to the runtime. Issue #[9022](https://github.com/dotnet/runtime/issues/9022) It mentioned some general data: “The expectation is that typical apps have 20% of their GC heap be strings. Some measurements we have seen is that for at least some applications, 10-30% of strings all may be duplicated, so this might save 2-3% of the GC heap. Not huge, but the feature is not that difficult either.” But keep in mind that this is an *average* - specific scenarios could have much higher percentage of duplicated strings. I have heard from customers who had much more dramatic heap reduction when they eliminated duplicated strings. Those are scenarios that would benefit from this feature the most. There are 2 sources of data we could get – - Our dump database. We can ask the TI team to help us look at the general percent of duplicated strings on the GC heap. It would be useful to also provide tooling to help users to check how much space duplicated strings take. Some internal folks have written tooling for this but it requires work to ship. - We already know of teams that can benefit from deduping. We should start a conversation with them to collect some data to have a rough idea about the baseline and make sure we have a way to verify private builds with them. #### **Design outline** This is an opt in feature. When the runtime detects it’s turned on, it creates a dedup thread to do the work. Detection of duplicated strings is done by looking into a hash table. The key into this hash table is the hash code of the content of a string. Detailed description of this detection is later in this doc. As the dedup thread goes through the old generations linearly, it looks for references to a string object (denoted by the method table) and either calculates or looks up the hash code of that string to see if it already exists in the hash table. If so it will attempt to change the reference to point to that string with a CAS operation. If this fails, which means some other thread changed the reference at the mean time, we simply ignore this and move on. We expect the CAS failure rate to be very low. Since the new string reference we will write to the heap has the exact same type info, it means BGC can read either the old or the new reference and will get the same size info so deduping would not conflict with BGC concurrent mark. It does not conflict with BGC sweep because BGC sweep does not read references inside an object. The dedup hash table acts as weak references to the strings. Depending on the scenario we might choose to null out these weak references or not (if it’s more performant to rebuild the hash table). If we we do the former these weak references would be treated as short weak handles so the following will happen before we scan for finalization - - During BGC final mark phase we will need to null out the strings that are not marked in the hash table. This can be made concurrent. - During a full blocking GC we will need to null out the strings that are not marked in the hash table, and relocate the ones that got promoted if we are doing a compacting GC. **Alternate design points** - Should we create multiple threads to do the work? Deduping can be done leisurely, so it doesn’t merit having multiple threads. - Can we use an existing thread to do the work on? The finalizer thread is something that’s idling most of the time. However there are already plenty of types of work scheduled to potentially run on the finalizer thread so adding yet another thing, especially an opt in feature, can get messy. #### **Which strings to dedup** Only strings allocated on the managed heap will be considered for deduplication. And only the ones that live in the old generations, meaning gen2 an LOH, will be considered. Deduping in young generations would be unproductive as they will likely die very soon. It would be extremely unproductive if the copy we are deduping to actually lived in young gens. #### **Calculating hash codes and large string consideration** Currently calling GetHashCode of a string calculates a 32-bit hash code. This is not stored anywhere, unlike the default hash code that’s stored either in the syncblk or a syncblk entry, depending whether the syncblk is also used by something else like locking. As the deduping thread goes through the heap it will calculate the 32-bit hash code and actually install it. However, a 32-bit hash code means we always need to check for collision by actually comparing the string content if the hash code is the same. And for large strings having to compare the string content could be very costly. For LOH compaction we already allocate a padding object for each large object (which currently takes up at most 0.4% of LOH space on 64-bit). We could make this padding object 1-ptr size larger and store the address of the string it’s deduped too. Likewise we can also use this to store the fact “this is the copy the hash table keeps track of so no need to dedup”. This way we can avoid having to do the detection multiple times for the same string. Below illustrates a scenario where large strings are deduplicated. `pad | s0 | pad | s1 | pad | s0_1` `obj0 (-> s0) | obj1 (-> s0_1) | obj2 (->s1) | obj3 (->s0_1) | obj4 (->s1) ` Each string obj, ie, s*, is a string on LOH and has a padding object in front of it which is not shown. s0_1 has the same content as s0. s1 has the same hash code but not the same content. "obj->s" means obj points to a string object s, or has a ref to s. So obj0 has a ref to s0, obj1 has a ref to s0_1, obj2 has a ref to s1 and so on. 1. As we go through the heap, we see obj0 which points to s0. 2. s0’s hash is calculated which we use to look into the hash table. 3. We see that no entries exist for that hash so we create an entry for it and in s0’s padding indicates that it’s stored in the hash table, ie, it’s the copy we keep. 4. Then we see obj1 which points to s0_1 whose hash doesn’t exist yet. We calculate the hash for s0_1, and see that there’s an entry for this hash already in the hash table, now we compare the content and see that it’s the same, now we store s0 in the padding object before s0_1 and change obj1’s ref to point to s0. 5. Then we see obj2 and calculate s1’s hash. We notice an entry already exists for that hash so we compare the content and the content is not the same as s0’s. So we enter s1 into the hash table and indicate that it’s stored in the hash table. 6. Then we see obj3, and s0_1 indicates that it should be deduped to s0 so we change obj3’s ref to point to s0_1 right away. 7. Then we see obj4 which points to s1 and s1 indicates it’s stored in the hash table so we don’t need to dedup. Since we know the size of a string object trivially, we know which strings are on LOH. **Situations when we choose to not dedup** - If `InterlockCompareExchangePointer` fails because the ref was modified while we were finding a copy to dedup to (or insert into the hash table), we skip this ref. - If too many collisions exist for a hash code, we skip deduping for strings with that hash code. This avoids the DoS attack by creating too many strings for the same hash. - If the string is too large. At some point going through a very large string to calculate its hash code will become simply not worth the effort. We'll need to do some perf investigation to figure out a good limit. **Alternate design points** - Should we calculate the hash codes for SOH strings as gen1 GCs promote them into gen2? This would increase gen1 pause. - Should we dedup while creating LOH strings? This would reduce LOH string allocation speed and potentially by a lot. #### **How often to dedup** If there’s no new objects that get into gen2/LOH, there’s no need to run dedup as the duplicates would have already been eliminated (mostly) during the last dedup cycle. So we should use the new amount of objects these generations get to determine how often to dedup, ie, taking the following factors into consideration - - We know when new LOH strings are allocated (all LOH allocations are done via C++ helpers in gchelpers.cpp), we can take the accumulative size of new LOH strings till it reaches a certain percentage of LOH before starting the next dedup cycle. - We know how much is promoted into gen2 and we can also wait till a certain percentage of gen2 consists of newly promoted memory before starting the next dedup cycle. #### **Compatibility** The following scenarios become problematic or more problematic when deduping is on so we need ways to help users find them. - Mutating the string content Strings are supposed to be immutable. However in unsafe code you can change the string content after it’s created. Changing string content already asking for trouble without deduping – you could be changing the interned copy which means you are modifying someone else’s string which could cause completely unpredictable results for them. The most common way is to use the fixed keyword: ```c# fixed (char* p = str) { p[0] = 'C'; } ``` There are other ways such as `((char*)(gcHandlePointingToString.AddrOfPinnedObject())) = 'c';` Or `Unsafe.AsRef (in str.GetPinnableReference()) = 'c';` - Locking on a string Locking on a string object is already discouraged due to a string can be interned. Having string dedup on can make this problematic more often if the string you called lock on is now deduped to a different string object. - Reference equality This example illustrates an example of `ReferenceEquals` that will not work if `_field` was deduped to a different string reference by the time the assignment to a2 happens. ```c# string _field; void Test() { _field = new string('a', 1); string a1 = _field; Thread.Sleep(1000); string a2 = _field; // This assert can fail with string deduping turned on Debug.Assert(ReferenceEquals(a1,a2)); } ``` **Runtime assistance to help with these scenarios** - Static analysis For .NET 5.0, there’s a static analysis [plan](https://github.com/dotnet/runtime/issues/30740). Verifying if string content is mutated can be part of that analysis suite. It would also be beneficial to have VS do this verification and give you a warning when you are mutating string content. To start with we will provide analysis for the following – 1. Using the fixed keyword to modify string content. I’m seeing that there are almost 600 places in libraries that do `fixed (char*` but hopefully most of them do not actually modify the string content. We should definitely be encouraging folks to switch to using `string.Create` like what [PR#31700](https://github.com/dotnet/runtime/pull/31700) did. 2. Using lock on a string object. - Reference equality checks on strings Since `ReferenceEquals` is performance critical API, we cannot do checks in its implementation. Checks will be done by how it's jitted - when the JIT sees that there are two object references being compared for equality, when a special diagnostics flag is set, it can jit a call to a helper method to do that and that helper method can produce diagnostics when the code is trying to compare identity of two strings. We do have some libraries that rely on `ReferenceEquals`. We need to figure out what to do about them. See discussion [here](https://github.com/dotnet/runtime/pull/31971#pullrequestreview-355531406). - Additional checks in heap verification Heap verification will now include checks to verify that no one changes the string content after it’s hash is computed. This can be turned on when a certain level of COMPlus_HeapVerify is specified. - Stress mode Instead of waiting till the productive moment to start the next deduping cycle, we can have a stress mode where we dedup randomly to catch problems sooner, same idea as GC stress to detect GC holes sooner. We could even artificially create duplicates in this stress mode to find places that depend on object identity. - Backup nonconcurrent dedup mode If you are running into these problematic scenarios and cannot make changes, and you can tolerate longer STW (Stop-The-World) pauses, we will provide a mode where deduping is completely done in either a full blocking GC or during the STW pause of a BGC. Obviously this would make BGC’s STW pauses much, much longer. This would basically just call the function that the dedup thread calls, but in these STW pauses. If you use a CPU profiler you should be able to see preciously how long the dedup part takes during the STW pause. We will either provide this as an API (GC.DeduplicateStrings) or as a config that only does dedup during full blocking GCs. The former is flexible and can give you detailed info such as how much space deduplicating strings saved. You could call this leisurely at a time when you know longer latency can be tolerated (eg, the server instance is taken out of rotation so you can tolerate a long pause). #### **Potential future work** **Experimenting with RTM** We might see some performance gains using RTM (Restricted Transactional Memory) on machines with large L1 caches but this is a P2 item. After we have the software solution implemented it would be easy to experiment with this. However, I have doubts it would give perf gain in most scenarios since looking into the hash table is quite a bit of work for RTM and likely will give high abort rate. **Deduping other types of objects** We might consider to not limit deduping to just strings. There was a discussion in [runtime issue #12628](https://github.com/dotnet/runtime/issues/12628). **Deduping long lived references on stack** There might be merit to look into deduping long lived refs on the stack. The amount of work it requires and the return makes it low priority but it may help with some corner cases.
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/Microsoft.Extensions.Configuration.UserSecrets/ref/Microsoft.Extensions.Configuration.UserSecrets.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Extensions.Configuration { public static partial class UserSecretsConfigurationExtensions { public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, System.Reflection.Assembly assembly) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, System.Reflection.Assembly assembly, bool optional) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, System.Reflection.Assembly assembly, bool optional, bool reloadOnChange) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, string userSecretsId) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, string userSecretsId, bool reloadOnChange) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets<T>(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration) where T : class { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets<T>(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, bool optional) where T : class { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets<T>(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, bool optional, bool reloadOnChange) where T : class { throw null; } } } namespace Microsoft.Extensions.Configuration.UserSecrets { public partial class PathHelper { public PathHelper() { } public static string GetSecretsPathFromSecretsId(string userSecretsId) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited=false, AllowMultiple=false)] public partial class UserSecretsIdAttribute : System.Attribute { public UserSecretsIdAttribute(string userSecretId) { } public string UserSecretsId { get { throw null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace Microsoft.Extensions.Configuration { public static partial class UserSecretsConfigurationExtensions { public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, System.Reflection.Assembly assembly) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, System.Reflection.Assembly assembly, bool optional) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, System.Reflection.Assembly assembly, bool optional, bool reloadOnChange) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, string userSecretsId) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, string userSecretsId, bool reloadOnChange) { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets<T>(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration) where T : class { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets<T>(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, bool optional) where T : class { throw null; } public static Microsoft.Extensions.Configuration.IConfigurationBuilder AddUserSecrets<T>(this Microsoft.Extensions.Configuration.IConfigurationBuilder configuration, bool optional, bool reloadOnChange) where T : class { throw null; } } } namespace Microsoft.Extensions.Configuration.UserSecrets { public partial class PathHelper { public PathHelper() { } public static string GetSecretsPathFromSecretsId(string userSecretsId) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Assembly, Inherited=false, AllowMultiple=false)] public partial class UserSecretsIdAttribute : System.Attribute { public UserSecretsIdAttribute(string userSecretId) { } public string UserSecretsId { get { throw null; } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/UniversalCryptoDecryptor.cs
// 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.Security.Cryptography; using Internal.Cryptography; namespace System.Security.Cryptography { // // A cross-platform ICryptoTransform implementation for decryption. // // - Implements the various padding algorithms (as we support padding algorithms that the underlying native apis don't.) // // - Parameterized by a BasicSymmetricCipher which encapsulates the algorithm, key, IV, chaining mode, direction of encryption // and the underlying native apis implementing the encryption. // internal sealed class UniversalCryptoDecryptor : UniversalCryptoTransform { public UniversalCryptoDecryptor(PaddingMode paddingMode, BasicSymmetricCipher basicSymmetricCipher) : base(paddingMode, basicSymmetricCipher) { } protected override int UncheckedTransformBlock(ReadOnlySpan<byte> inputBuffer, Span<byte> outputBuffer) { // // If we're decrypting, it's possible to be called with the last blocks of the data, and then // have TransformFinalBlock called with an empty array. Since we don't know if this is the case, // we won't decrypt the last block of the input until either TransformBlock or // TransformFinalBlock is next called. // // We don't need to do this for PaddingMode.None because there is no padding to strip, and // we also don't do this for PaddingMode.Zeros since there is no way for us to tell if the // zeros at the end of a block are part of the plaintext or the padding. // int decryptedBytes = 0; if (SymmetricPadding.DepaddingRequired(PaddingMode)) { // If we have data saved from a previous call, decrypt that into the output first if (_heldoverCipher != null) { int depadDecryptLength = BasicSymmetricCipher.Transform(_heldoverCipher, outputBuffer); outputBuffer = outputBuffer.Slice(depadDecryptLength); decryptedBytes += depadDecryptLength; } else { _heldoverCipher = new byte[InputBlockSize]; } // Postpone the last block to the next round. Debug.Assert(inputBuffer.Length >= _heldoverCipher.Length, "inputBuffer.Length >= _heldoverCipher.Length"); inputBuffer.Slice(inputBuffer.Length - _heldoverCipher.Length).CopyTo(_heldoverCipher); inputBuffer = inputBuffer.Slice(0, inputBuffer.Length - _heldoverCipher.Length); Debug.Assert(inputBuffer.Length % InputBlockSize == 0, "Did not remove whole blocks for depadding"); } if (inputBuffer.Length > 0) { decryptedBytes += BasicSymmetricCipher.Transform(inputBuffer, outputBuffer); } return decryptedBytes; } protected override unsafe int UncheckedTransformFinalBlock(ReadOnlySpan<byte> inputBuffer, Span<byte> outputBuffer) { // We can't complete decryption on a partial block if (inputBuffer.Length % PaddingSizeBytes != 0) throw new CryptographicException(SR.Cryptography_PartialBlock); // // If we have postponed cipher bits from the prior round, copy that into the decryption buffer followed by the input data. // Otherwise the decryption buffer is just the input data. // ReadOnlySpan<byte> inputCiphertext; Span<byte> ciphertext; byte[]? rentedCiphertext = null; int rentedCiphertextSize = 0; try { if (_heldoverCipher == null) { rentedCiphertextSize = inputBuffer.Length; rentedCiphertext = CryptoPool.Rent(inputBuffer.Length); ciphertext = rentedCiphertext.AsSpan(0, inputBuffer.Length); inputCiphertext = inputBuffer; } else { rentedCiphertextSize = _heldoverCipher.Length + inputBuffer.Length; rentedCiphertext = CryptoPool.Rent(rentedCiphertextSize); ciphertext = rentedCiphertext.AsSpan(0, rentedCiphertextSize); _heldoverCipher.AsSpan().CopyTo(ciphertext); inputBuffer.CopyTo(ciphertext.Slice(_heldoverCipher.Length)); // Decrypt in-place inputCiphertext = ciphertext; } int unpaddedLength = 0; fixed (byte* pCiphertext = ciphertext) { // Decrypt the data, then strip the padding to get the final decrypted data. Note that even if the cipherText length is 0, we must // invoke TransformFinal() so that the cipher object knows to reset for the next cipher operation. int decryptWritten = BasicSymmetricCipher.TransformFinal(inputCiphertext, ciphertext); Span<byte> decryptedBytes = ciphertext.Slice(0, decryptWritten); if (decryptedBytes.Length > 0) { unpaddedLength = SymmetricPadding.GetPaddingLength(decryptedBytes, PaddingMode, InputBlockSize); decryptedBytes.Slice(0, unpaddedLength).CopyTo(outputBuffer); } } Reset(); return unpaddedLength; } finally { if (rentedCiphertext != null) { CryptoPool.Return(rentedCiphertext, clearSize: rentedCiphertextSize); } } } protected override unsafe byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (SymmetricPadding.DepaddingRequired(PaddingMode)) { byte[] rented = CryptoPool.Rent(inputCount + InputBlockSize); int written = 0; fixed (byte* pRented = rented) { try { written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), rented); return rented.AsSpan(0, written).ToArray(); } finally { CryptoPool.Return(rented, clearSize: written); } } } else { byte[] buffer = GC.AllocateUninitializedArray<byte>(inputCount); int written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), buffer); Debug.Assert(written == buffer.Length); return buffer; } } protected sealed override void Dispose(bool disposing) { if (disposing) { byte[]? heldoverCipher = _heldoverCipher; _heldoverCipher = null; if (heldoverCipher != null) { Array.Clear(heldoverCipher); } } base.Dispose(disposing); } private void Reset() { if (_heldoverCipher != null) { Array.Clear(_heldoverCipher); _heldoverCipher = null; } } // // For padding modes that support automatic depadding, TransformBlock() leaves the last block it is given undone since it has no way of knowing // whether this is the final block that needs depadding. This block is held (in encrypted form) in _heldoverCipher. The next call to TransformBlock // or TransformFinalBlock must include the decryption of _heldoverCipher in the results. // private byte[]? _heldoverCipher; } }
// 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.Security.Cryptography; using Internal.Cryptography; namespace System.Security.Cryptography { // // A cross-platform ICryptoTransform implementation for decryption. // // - Implements the various padding algorithms (as we support padding algorithms that the underlying native apis don't.) // // - Parameterized by a BasicSymmetricCipher which encapsulates the algorithm, key, IV, chaining mode, direction of encryption // and the underlying native apis implementing the encryption. // internal sealed class UniversalCryptoDecryptor : UniversalCryptoTransform { public UniversalCryptoDecryptor(PaddingMode paddingMode, BasicSymmetricCipher basicSymmetricCipher) : base(paddingMode, basicSymmetricCipher) { } protected override int UncheckedTransformBlock(ReadOnlySpan<byte> inputBuffer, Span<byte> outputBuffer) { // // If we're decrypting, it's possible to be called with the last blocks of the data, and then // have TransformFinalBlock called with an empty array. Since we don't know if this is the case, // we won't decrypt the last block of the input until either TransformBlock or // TransformFinalBlock is next called. // // We don't need to do this for PaddingMode.None because there is no padding to strip, and // we also don't do this for PaddingMode.Zeros since there is no way for us to tell if the // zeros at the end of a block are part of the plaintext or the padding. // int decryptedBytes = 0; if (SymmetricPadding.DepaddingRequired(PaddingMode)) { // If we have data saved from a previous call, decrypt that into the output first if (_heldoverCipher != null) { int depadDecryptLength = BasicSymmetricCipher.Transform(_heldoverCipher, outputBuffer); outputBuffer = outputBuffer.Slice(depadDecryptLength); decryptedBytes += depadDecryptLength; } else { _heldoverCipher = new byte[InputBlockSize]; } // Postpone the last block to the next round. Debug.Assert(inputBuffer.Length >= _heldoverCipher.Length, "inputBuffer.Length >= _heldoverCipher.Length"); inputBuffer.Slice(inputBuffer.Length - _heldoverCipher.Length).CopyTo(_heldoverCipher); inputBuffer = inputBuffer.Slice(0, inputBuffer.Length - _heldoverCipher.Length); Debug.Assert(inputBuffer.Length % InputBlockSize == 0, "Did not remove whole blocks for depadding"); } if (inputBuffer.Length > 0) { decryptedBytes += BasicSymmetricCipher.Transform(inputBuffer, outputBuffer); } return decryptedBytes; } protected override unsafe int UncheckedTransformFinalBlock(ReadOnlySpan<byte> inputBuffer, Span<byte> outputBuffer) { // We can't complete decryption on a partial block if (inputBuffer.Length % PaddingSizeBytes != 0) throw new CryptographicException(SR.Cryptography_PartialBlock); // // If we have postponed cipher bits from the prior round, copy that into the decryption buffer followed by the input data. // Otherwise the decryption buffer is just the input data. // ReadOnlySpan<byte> inputCiphertext; Span<byte> ciphertext; byte[]? rentedCiphertext = null; int rentedCiphertextSize = 0; try { if (_heldoverCipher == null) { rentedCiphertextSize = inputBuffer.Length; rentedCiphertext = CryptoPool.Rent(inputBuffer.Length); ciphertext = rentedCiphertext.AsSpan(0, inputBuffer.Length); inputCiphertext = inputBuffer; } else { rentedCiphertextSize = _heldoverCipher.Length + inputBuffer.Length; rentedCiphertext = CryptoPool.Rent(rentedCiphertextSize); ciphertext = rentedCiphertext.AsSpan(0, rentedCiphertextSize); _heldoverCipher.AsSpan().CopyTo(ciphertext); inputBuffer.CopyTo(ciphertext.Slice(_heldoverCipher.Length)); // Decrypt in-place inputCiphertext = ciphertext; } int unpaddedLength = 0; fixed (byte* pCiphertext = ciphertext) { // Decrypt the data, then strip the padding to get the final decrypted data. Note that even if the cipherText length is 0, we must // invoke TransformFinal() so that the cipher object knows to reset for the next cipher operation. int decryptWritten = BasicSymmetricCipher.TransformFinal(inputCiphertext, ciphertext); Span<byte> decryptedBytes = ciphertext.Slice(0, decryptWritten); if (decryptedBytes.Length > 0) { unpaddedLength = SymmetricPadding.GetPaddingLength(decryptedBytes, PaddingMode, InputBlockSize); decryptedBytes.Slice(0, unpaddedLength).CopyTo(outputBuffer); } } Reset(); return unpaddedLength; } finally { if (rentedCiphertext != null) { CryptoPool.Return(rentedCiphertext, clearSize: rentedCiphertextSize); } } } protected override unsafe byte[] UncheckedTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (SymmetricPadding.DepaddingRequired(PaddingMode)) { byte[] rented = CryptoPool.Rent(inputCount + InputBlockSize); int written = 0; fixed (byte* pRented = rented) { try { written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), rented); return rented.AsSpan(0, written).ToArray(); } finally { CryptoPool.Return(rented, clearSize: written); } } } else { byte[] buffer = GC.AllocateUninitializedArray<byte>(inputCount); int written = UncheckedTransformFinalBlock(inputBuffer.AsSpan(inputOffset, inputCount), buffer); Debug.Assert(written == buffer.Length); return buffer; } } protected sealed override void Dispose(bool disposing) { if (disposing) { byte[]? heldoverCipher = _heldoverCipher; _heldoverCipher = null; if (heldoverCipher != null) { Array.Clear(heldoverCipher); } } base.Dispose(disposing); } private void Reset() { if (_heldoverCipher != null) { Array.Clear(_heldoverCipher); _heldoverCipher = null; } } // // For padding modes that support automatic depadding, TransformBlock() leaves the last block it is given undone since it has no way of knowing // whether this is the final block that needs depadding. This block is held (in encrypted form) in _heldoverCipher. The next call to TransformBlock // or TransformFinalBlock must include the decryption of _heldoverCipher in the results. // private byte[]? _heldoverCipher; } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/HardwareIntrinsics/General/Vector256/Add.UInt16.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AddUInt16() { var test = new VectorBinaryOpTest__AddUInt16(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__AddUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt16> _fld1; public Vector256<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__AddUInt16 testClass) { var result = Vector256.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector256<UInt16> _clsVar1; private static Vector256<UInt16> _clsVar2; private Vector256<UInt16> _fld1; private Vector256<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__AddUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); } public VectorBinaryOpTest__AddUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Add( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Add), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr); var result = Vector256.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__AddUInt16(); var result = Vector256.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ushort)(left[0] + right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ushort)(left[i] + right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Add)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AddUInt16() { var test = new VectorBinaryOpTest__AddUInt16(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBinaryOpTest__AddUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt16> _fld1; public Vector256<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorBinaryOpTest__AddUInt16 testClass) { var result = Vector256.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector256<UInt16> _clsVar1; private static Vector256<UInt16> _clsVar2; private Vector256<UInt16> _fld1; private Vector256<UInt16> _fld2; private DataTable _dataTable; static VectorBinaryOpTest__AddUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); } public VectorBinaryOpTest__AddUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector256.Add( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector256).GetMethod(nameof(Vector256.Add), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) }); if (method is null) { method = typeof(Vector256).GetMethod(nameof(Vector256.Add), 1, new Type[] { typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(UInt16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector256.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr); var result = Vector256.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBinaryOpTest__AddUInt16(); var result = Vector256.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector256.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector256.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ushort)(left[0] + right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ushort)(left[i] + right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.Add)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/Methodical/MDArray/basics/structarr_basics_cs_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="structarr.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="structarr.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLoggerProvider.cs
// 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.Threading; namespace Microsoft.Extensions.Logging.EventSource { /// <summary> /// The provider for the <see cref="EventSourceLogger"/>. /// </summary> [ProviderAlias("EventSource")] public class EventSourceLoggerProvider : ILoggerProvider { private static int _globalFactoryID; // A small integer that uniquely identifies the LoggerFactory associated with this LoggingProvider. private readonly int _factoryID; private EventSourceLogger? _loggers; // Linked list of loggers that I have created private readonly LoggingEventSource _eventSource; public EventSourceLoggerProvider(LoggingEventSource eventSource!!) { _eventSource = eventSource; _factoryID = Interlocked.Increment(ref _globalFactoryID); } /// <inheritdoc /> public ILogger CreateLogger(string categoryName) { return _loggers = new EventSourceLogger(categoryName, _factoryID, _eventSource, _loggers); } /// <inheritdoc /> public void Dispose() { // Turn off any logging for (EventSourceLogger? logger = _loggers; logger != null; logger = logger.Next) { logger.Level = LogLevel.None; } } } }
// 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.Threading; namespace Microsoft.Extensions.Logging.EventSource { /// <summary> /// The provider for the <see cref="EventSourceLogger"/>. /// </summary> [ProviderAlias("EventSource")] public class EventSourceLoggerProvider : ILoggerProvider { private static int _globalFactoryID; // A small integer that uniquely identifies the LoggerFactory associated with this LoggingProvider. private readonly int _factoryID; private EventSourceLogger? _loggers; // Linked list of loggers that I have created private readonly LoggingEventSource _eventSource; public EventSourceLoggerProvider(LoggingEventSource eventSource!!) { _eventSource = eventSource; _factoryID = Interlocked.Increment(ref _globalFactoryID); } /// <inheritdoc /> public ILogger CreateLogger(string categoryName) { return _loggers = new EventSourceLogger(categoryName, _factoryID, _eventSource, _loggers); } /// <inheritdoc /> public void Dispose() { // Turn off any logging for (EventSourceLogger? logger = _loggers; logger != null; logger = logger.Next) { logger.Level = LogLevel.None; } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Security.Permissions/src/CompatibilitySuppressions.xml
<?xml version="1.0" encoding="utf-8"?> <Suppressions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Suppression> <DiagnosticId>CP0002</DiagnosticId> <Target>M:System.Security.Permissions.KeyContainerPermissionAccessEntryCollection.CopyTo(System.Array,System.Int32)</Target> <Left>lib/netstandard2.0/System.Security.Permissions.dll</Left> <Right>lib/net462/System.Security.Permissions.dll</Right> </Suppression> <Suppression> <DiagnosticId>CP0002</DiagnosticId> <Target>M:System.Security.Permissions.KeyContainerPermissionAccessEntryCollection.#ctor</Target> <Left>lib/netstandard2.0/System.Security.Permissions.dll</Left> <Right>lib/net462/System.Security.Permissions.dll</Right> </Suppression> <Suppression> <DiagnosticId>CP0002</DiagnosticId> <Target>M:System.Security.Permissions.KeyContainerPermissionAccessEntryEnumerator.#ctor</Target> <Left>lib/netstandard2.0/System.Security.Permissions.dll</Left> <Right>lib/net462/System.Security.Permissions.dll</Right> </Suppression> <Suppression> <DiagnosticId>CP0001</DiagnosticId> <Target>T:System.Xaml.Permissions.XamlLoadPermission</Target> <Left>lib/net5.0/System.Security.Permissions.dll</Left> <Right>lib/netstandard2.0/System.Security.Permissions.dll</Right> <IsBaselineSuppression>true</IsBaselineSuppression> </Suppression> <Suppression> <DiagnosticId>CP0001</DiagnosticId> <Target>T:System.Xaml.Permissions.XamlLoadPermission</Target> <Left>lib/netcoreapp3.1/System.Security.Permissions.dll</Left> <Right>lib/netstandard2.0/System.Security.Permissions.dll</Right> <IsBaselineSuppression>true</IsBaselineSuppression> </Suppression> </Suppressions>
<?xml version="1.0" encoding="utf-8"?> <Suppressions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Suppression> <DiagnosticId>CP0002</DiagnosticId> <Target>M:System.Security.Permissions.KeyContainerPermissionAccessEntryCollection.CopyTo(System.Array,System.Int32)</Target> <Left>lib/netstandard2.0/System.Security.Permissions.dll</Left> <Right>lib/net462/System.Security.Permissions.dll</Right> </Suppression> <Suppression> <DiagnosticId>CP0002</DiagnosticId> <Target>M:System.Security.Permissions.KeyContainerPermissionAccessEntryCollection.#ctor</Target> <Left>lib/netstandard2.0/System.Security.Permissions.dll</Left> <Right>lib/net462/System.Security.Permissions.dll</Right> </Suppression> <Suppression> <DiagnosticId>CP0002</DiagnosticId> <Target>M:System.Security.Permissions.KeyContainerPermissionAccessEntryEnumerator.#ctor</Target> <Left>lib/netstandard2.0/System.Security.Permissions.dll</Left> <Right>lib/net462/System.Security.Permissions.dll</Right> </Suppression> <Suppression> <DiagnosticId>CP0001</DiagnosticId> <Target>T:System.Xaml.Permissions.XamlLoadPermission</Target> <Left>lib/net5.0/System.Security.Permissions.dll</Left> <Right>lib/netstandard2.0/System.Security.Permissions.dll</Right> <IsBaselineSuppression>true</IsBaselineSuppression> </Suppression> <Suppression> <DiagnosticId>CP0001</DiagnosticId> <Target>T:System.Xaml.Permissions.XamlLoadPermission</Target> <Left>lib/netcoreapp3.1/System.Security.Permissions.dll</Left> <Right>lib/netstandard2.0/System.Security.Permissions.dll</Right> <IsBaselineSuppression>true</IsBaselineSuppression> </Suppression> </Suppressions>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/PropertyNameTests.cs
// 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.Text.Json.Serialization; using System.Text.Json.Serialization.Tests; namespace System.Text.Json.SourceGeneration.Tests { public sealed partial class PropertyNameTests_Metadata : PropertyNameTests { public PropertyNameTests_Metadata() : base(new StringSerializerWrapper(PropertyNameTestsContext_Metadata.Default, (options) => new PropertyNameTestsContext_Metadata(options))) { } [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)] [JsonSerializable(typeof(Dictionary<string, OverridePropertyNameDesignTime_TestClass>))] [JsonSerializable(typeof(Dictionary<string, int>))] [JsonSerializable(typeof(int))] [JsonSerializable(typeof(ClassWithSpecialCharacters))] [JsonSerializable(typeof(ClassWithPropertyNamePermutations))] [JsonSerializable(typeof(ClassWithUnicodeProperty))] [JsonSerializable(typeof(DuplicatePropertyNameDesignTime_TestClass))] [JsonSerializable(typeof(EmptyPropertyName_TestClass))] [JsonSerializable(typeof(IntPropertyNamesDifferentByCaseOnly_TestClass))] [JsonSerializable(typeof(NullPropertyName_TestClass))] [JsonSerializable(typeof(ObjectPropertyNamesDifferentByCaseOnly_TestClass))] [JsonSerializable(typeof(OverridePropertyNameDesignTime_TestClass))] [JsonSerializable(typeof(SimpleTestClass))] internal sealed partial class PropertyNameTestsContext_Metadata : JsonSerializerContext { } } public sealed partial class PropertyNameTests_Default : PropertyNameTests { public PropertyNameTests_Default() : base(new StringSerializerWrapper(PropertyNameTestsContext_Default.Default, (options) => new PropertyNameTestsContext_Default(options))) { } [JsonSerializable(typeof(Dictionary<string, OverridePropertyNameDesignTime_TestClass>))] [JsonSerializable(typeof(Dictionary<string, int>))] [JsonSerializable(typeof(int))] [JsonSerializable(typeof(ClassWithSpecialCharacters))] [JsonSerializable(typeof(ClassWithPropertyNamePermutations))] [JsonSerializable(typeof(ClassWithUnicodeProperty))] [JsonSerializable(typeof(DuplicatePropertyNameDesignTime_TestClass))] [JsonSerializable(typeof(EmptyPropertyName_TestClass))] [JsonSerializable(typeof(IntPropertyNamesDifferentByCaseOnly_TestClass))] [JsonSerializable(typeof(NullPropertyName_TestClass))] [JsonSerializable(typeof(ObjectPropertyNamesDifferentByCaseOnly_TestClass))] [JsonSerializable(typeof(OverridePropertyNameDesignTime_TestClass))] [JsonSerializable(typeof(SimpleTestClass))] internal sealed partial class PropertyNameTestsContext_Default : JsonSerializerContext { } } }
// 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.Text.Json.Serialization; using System.Text.Json.Serialization.Tests; namespace System.Text.Json.SourceGeneration.Tests { public sealed partial class PropertyNameTests_Metadata : PropertyNameTests { public PropertyNameTests_Metadata() : base(new StringSerializerWrapper(PropertyNameTestsContext_Metadata.Default, (options) => new PropertyNameTestsContext_Metadata(options))) { } [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Metadata)] [JsonSerializable(typeof(Dictionary<string, OverridePropertyNameDesignTime_TestClass>))] [JsonSerializable(typeof(Dictionary<string, int>))] [JsonSerializable(typeof(int))] [JsonSerializable(typeof(ClassWithSpecialCharacters))] [JsonSerializable(typeof(ClassWithPropertyNamePermutations))] [JsonSerializable(typeof(ClassWithUnicodeProperty))] [JsonSerializable(typeof(DuplicatePropertyNameDesignTime_TestClass))] [JsonSerializable(typeof(EmptyPropertyName_TestClass))] [JsonSerializable(typeof(IntPropertyNamesDifferentByCaseOnly_TestClass))] [JsonSerializable(typeof(NullPropertyName_TestClass))] [JsonSerializable(typeof(ObjectPropertyNamesDifferentByCaseOnly_TestClass))] [JsonSerializable(typeof(OverridePropertyNameDesignTime_TestClass))] [JsonSerializable(typeof(SimpleTestClass))] internal sealed partial class PropertyNameTestsContext_Metadata : JsonSerializerContext { } } public sealed partial class PropertyNameTests_Default : PropertyNameTests { public PropertyNameTests_Default() : base(new StringSerializerWrapper(PropertyNameTestsContext_Default.Default, (options) => new PropertyNameTestsContext_Default(options))) { } [JsonSerializable(typeof(Dictionary<string, OverridePropertyNameDesignTime_TestClass>))] [JsonSerializable(typeof(Dictionary<string, int>))] [JsonSerializable(typeof(int))] [JsonSerializable(typeof(ClassWithSpecialCharacters))] [JsonSerializable(typeof(ClassWithPropertyNamePermutations))] [JsonSerializable(typeof(ClassWithUnicodeProperty))] [JsonSerializable(typeof(DuplicatePropertyNameDesignTime_TestClass))] [JsonSerializable(typeof(EmptyPropertyName_TestClass))] [JsonSerializable(typeof(IntPropertyNamesDifferentByCaseOnly_TestClass))] [JsonSerializable(typeof(NullPropertyName_TestClass))] [JsonSerializable(typeof(ObjectPropertyNamesDifferentByCaseOnly_TestClass))] [JsonSerializable(typeof(OverridePropertyNameDesignTime_TestClass))] [JsonSerializable(typeof(SimpleTestClass))] internal sealed partial class PropertyNameTestsContext_Default : JsonSerializerContext { } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/profiler/eventpipe/eventpipe_readevents.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <OutputType>exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <Optimize>true</Optimize> <!-- This test provides no interesting scenarios for GCStress --> <GCStressIncompatible>true</GCStressIncompatible> <!-- The test launches a secondary process and process launch creates an infinite event loop in the SocketAsyncEngine on Linux. Since runincontext loads even framework assemblies into the unloadable context, locals in this loop prevent unloading --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> <ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" /> <ProjectReference Include="../common/profiler_common.csproj" /> <CMakeProjectReference Include="$(MSBuildThisFileDirectory)/../native/CMakeLists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier> <OutputType>exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <Optimize>true</Optimize> <!-- This test provides no interesting scenarios for GCStress --> <GCStressIncompatible>true</GCStressIncompatible> <!-- The test launches a secondary process and process launch creates an infinite event loop in the SocketAsyncEngine on Linux. Since runincontext loads even framework assemblies into the unloadable context, locals in this loop prevent unloading --> <UnloadabilityIncompatible>true</UnloadabilityIncompatible> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> <ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" /> <ProjectReference Include="../common/profiler_common.csproj" /> <CMakeProjectReference Include="$(MSBuildThisFileDirectory)/../native/CMakeLists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest242/Generated242.il
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated242 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct292`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase1`1<class BaseClass0>, class IBase2`2<!T1,!T0> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method4() cil managed noinlining { ldstr "MyStruct292::Method4.2316()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ret } .method public hidebysig virtual instance string Method5() cil managed noinlining { ldstr "MyStruct292::Method5.2318()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "MyStruct292::Method6.2320<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method6<[1]>() ldstr "MyStruct292::Method6.MI.2321<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct292::Method7.2322<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<T1,T0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T1,!T0>::Method7<[1]>() ldstr "MyStruct292::Method7.MI.2323<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod578() cil managed noinlining { ldstr "MyStruct292::ClassMethod578.2324()" ret } .method public hidebysig newslot instance string ClassMethod579() cil managed noinlining { ldstr "MyStruct292::ClassMethod579.2325()" ret } .method public hidebysig newslot instance string ClassMethod580<M0>() cil managed noinlining { ldstr "MyStruct292::ClassMethod580.2326<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod581<M0>() cil managed noinlining { ldstr "MyStruct292::ClassMethod581.2327<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated242 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.T.T<T0,T1,(valuetype MyStruct292`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.T.T<T0,T1,(valuetype MyStruct292`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T1,!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.A.T<T1,(valuetype MyStruct292`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.A.T<T1,(valuetype MyStruct292`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.A.A<(valuetype MyStruct292`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.A.A<(valuetype MyStruct292`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.A.B<(valuetype MyStruct292`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.A.B<(valuetype MyStruct292`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.B.T<T1,(valuetype MyStruct292`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.B.T<T1,(valuetype MyStruct292`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.B.A<(valuetype MyStruct292`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.B.A<(valuetype MyStruct292`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.B.B<(valuetype MyStruct292`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.B.B<(valuetype MyStruct292`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method4() ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method5() ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod578() ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod579() ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod580<object>() ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod581<object>() ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method4() ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method5() ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod578() ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod579() ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod580<object>() ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod581<object>() ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method4() ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method5() ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod578() ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod579() ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod580<object>() ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod581<object>() ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method4() ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method5() ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod578() ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod579() ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod580<object>() ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod581<object>() ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.B<valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_6 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.B<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.B<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_7 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.A<valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: .try { ldloc V_7 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV24 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24: .try { ldloc V_7 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV25 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV25} LV25: .try { ldloc V_7 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.B<valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV26 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26: .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV27 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV27} LV27: .try { ldloc V_8 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.A<valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV28 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV28} LV28: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV29 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV29} LV29: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV30 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV30} LV30: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.B<valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV31 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV31} LV31: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV32 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV32} LV32: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV33 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV33} LV33: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.B<valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV34 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV34} LV34: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.A.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.A.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.A.B<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_11 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.B.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_11 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.B.A<valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_12 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.B.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_12 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.B.B<valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod578() calli default string(object) ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod579() calli default string(object) ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod580<object>() calli default string(object) ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod581<object>() calli default string(object) ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod578() calli default string(object) ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod579() calli default string(object) ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod580<object>() calli default string(object) ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod581<object>() calli default string(object) ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod578() calli default string(object) ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod579() calli default string(object) ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod580<object>() calli default string(object) ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod581<object>() calli default string(object) ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod578() calli default string(object) ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod579() calli default string(object) ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod580<object>() calli default string(object) ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod581<object>() calli default string(object) ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated242::MethodCallingTest() call void Generated242::ConstrainedCallsTest() call void Generated242::StructConstrainedInterfaceCallsTest() call void Generated242::CalliTest() ldc.i4 100 ret } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestFramework { .publickeytoken = ( B0 3F 5F 7F 11 D5 0A 3A ) } //TYPES IN FORWARDER ASSEMBLIES: //TEST ASSEMBLY: .assembly Generated242 { .hash algorithm 0x00008004 } .assembly extern xunit.core {} .class public BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } .class public BaseClass1 extends BaseClass0 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void BaseClass0::.ctor() ret } } .class public sequential sealed MyStruct292`2<T0, T1> extends [mscorlib]System.ValueType implements class IBase1`1<class BaseClass0>, class IBase2`2<!T1,!T0> { .pack 0 .size 1 .method public hidebysig newslot virtual instance string Method4() cil managed noinlining { ldstr "MyStruct292::Method4.2316()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method4'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ret } .method public hidebysig virtual instance string Method5() cil managed noinlining { ldstr "MyStruct292::Method5.2318()" ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method5'() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ret } .method public hidebysig newslot virtual instance string Method6<M0>() cil managed noinlining { ldstr "MyStruct292::Method6.2320<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase1<class BaseClass0>.Method6'<M0>() cil managed noinlining { .override method instance string class IBase1`1<class BaseClass0>::Method6<[1]>() ldstr "MyStruct292::Method6.MI.2321<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string Method7<M0>() cil managed noinlining { ldstr "MyStruct292::Method7.2322<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot virtual instance string 'IBase2<T1,T0>.Method7'<M0>() cil managed noinlining { .override method instance string class IBase2`2<!T1,!T0>::Method7<[1]>() ldstr "MyStruct292::Method7.MI.2323<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod578() cil managed noinlining { ldstr "MyStruct292::ClassMethod578.2324()" ret } .method public hidebysig newslot instance string ClassMethod579() cil managed noinlining { ldstr "MyStruct292::ClassMethod579.2325()" ret } .method public hidebysig newslot instance string ClassMethod580<M0>() cil managed noinlining { ldstr "MyStruct292::ClassMethod580.2326<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig newslot instance string ClassMethod581<M0>() cil managed noinlining { ldstr "MyStruct292::ClassMethod581.2327<" ldtoken !!M0 call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call string [mscorlib]System.String::Concat(object,object) ldstr ">()" call string [mscorlib]System.String::Concat(object,object) ret } .method public hidebysig virtual instance bool Equals(object obj) cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance int32 GetHashCode() cil managed { ldc.i4.0 ret } .method public hidebysig virtual instance string ToString() cil managed { ldstr "" ret } } .class interface public abstract IBase1`1<+T0> { .method public hidebysig newslot abstract virtual instance string Method4() cil managed { } .method public hidebysig newslot abstract virtual instance string Method5() cil managed { } .method public hidebysig newslot abstract virtual instance string Method6<M0>() cil managed { } } .class interface public abstract IBase2`2<+T0, -T1> { .method public hidebysig newslot abstract virtual instance string Method7<M0>() cil managed { } } .class public auto ansi beforefieldinit Generated242 { .method static void M.BaseClass0<(BaseClass0)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass0<(BaseClass0)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.BaseClass1<(BaseClass1)W>(!!W inst, string exp) cil managed { .maxstack 5 .locals init (string[] actualResults) ldc.i4.s 0 newarr string stloc.s actualResults ldarg.1 ldstr "M.BaseClass1<(BaseClass1)W>(!!W inst, string exp)" ldc.i4.s 0 ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.T<T0,(class IBase1`1<!!T0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<!!T0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.A<(class IBase1`1<class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 8 .locals init (string[] actualResults) ldc.i4.s 3 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase1.B<(class IBase1`1<class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 3 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. !!W callvirt instance string class IBase1`1<class BaseClass1>::Method6<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.T.T<T0,T1,(class IBase2`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<!!T0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.T<T1,(class IBase2`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.A<(class IBase2`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.A.B<(class IBase2`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.T<T1,(class IBase2`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,!!T1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.A<(class IBase2`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 6 .locals init (string[] actualResults) ldc.i4.s 1 newarr string stloc.s actualResults ldarg.1 ldstr "M.IBase2.B.B<(class IBase2`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 1 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. !!W callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.T.T<T0,T1,(valuetype MyStruct292`2<!!T0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.T.T<T0,T1,(valuetype MyStruct292`2<!!T0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<!!T0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<!!T0,!!T1> callvirt instance string class IBase2`2<!!T1,!!T0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.A.T<T1,(valuetype MyStruct292`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.A.T<T1,(valuetype MyStruct292`2<class BaseClass0,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.A.A<(valuetype MyStruct292`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.A.A<(valuetype MyStruct292`2<class BaseClass0,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.A.B<(valuetype MyStruct292`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.A.B<(valuetype MyStruct292`2<class BaseClass0,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass0,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.B.T<T1,(valuetype MyStruct292`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.B.T<T1,(valuetype MyStruct292`2<class BaseClass1,!!T1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,!!T1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,!!T1> callvirt instance string class IBase2`2<!!T1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.B.A<(valuetype MyStruct292`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.B.A<(valuetype MyStruct292`2<class BaseClass1,class BaseClass0>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass0> callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method static void M.MyStruct292.B.B<(valuetype MyStruct292`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp) cil managed { .maxstack 9 .locals init (string[] actualResults) ldc.i4.s 4 newarr string stloc.s actualResults ldarg.1 ldstr "M.MyStruct292.B.B<(valuetype MyStruct292`2<class BaseClass1,class BaseClass1>)W>(!!W 'inst', string exp)" ldc.i4.s 4 ldloc.s actualResults ldc.i4.s 0 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method4() stelem.ref ldloc.s actualResults ldc.i4.s 1 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method5() stelem.ref ldloc.s actualResults ldc.i4.s 2 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() stelem.ref ldloc.s actualResults ldc.i4.s 3 ldarga.s 0 constrained. valuetype MyStruct292`2<class BaseClass1,class BaseClass1> callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() stelem.ref ldloc.s actualResults call void [TestFramework]TestFramework::MethodCallTest(string,string,int32,string[]) ret } .method public hidebysig static void MethodCallingTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calling Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass0> V_1) ldloca V_1 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloca V_1 dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method4() ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method5() ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod578() ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod579() ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod580<object>() ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod581<object>() ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ToString() pop pop ldloc V_1 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_1 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass1> V_2) ldloca V_2 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloca V_2 dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method4() ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method5() ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method6<object>() ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod578() ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod579() ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod580<object>() ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod581<object>() ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ToString() pop pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_2 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass0> V_3) ldloca V_3 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloca V_3 dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method4() ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method5() ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method7<object>() ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod578() ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod579() ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod580<object>() ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod581<object>() ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Equals(object) pop dup call instance int32 valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::GetHashCode() pop dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ToString() pop pop ldloc V_3 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_3 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass1> V_4) ldloca V_4 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloca V_4 dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method4() ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method5() ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method6<object>() ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod578() ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod579() ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod580<object>() ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod581<object>() ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type MyStruct292" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup ldnull call instance bool valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Equals(object) pop dup call instance int32 valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::GetHashCode() pop dup call instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ToString() pop pop ldloc V_4 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase1`1<class BaseClass0>::Method4() ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method5() ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) dup callvirt instance string class IBase1`1<class BaseClass0>::Method6<object>() ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldloc V_4 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> dup callvirt instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) pop ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void ConstrainedCallsTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Constrained Calls Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass0> V_5) ldloca V_5 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass0> .try { ldloc V_5 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_5 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_5 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.B<valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass1> V_6) ldloca V_6 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass1> .try { ldloc V_6 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .try { ldloc V_6 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV12 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV12} LV12: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV13 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV13} LV13: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV14 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV14} LV14: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV15 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV15} LV15: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV16 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV16} LV16: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV17 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV17} LV17: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.B<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV18 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV18} LV18: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV19 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV19} LV19: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV20 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV20} LV20: .try { ldloc V_6 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.B<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV21 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV21} LV21: .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass0> V_7) ldloca V_7 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass0> .try { ldloc V_7 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV22 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV22} LV22: .try { ldloc V_7 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.A<valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV23 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV23} LV23: .try { ldloc V_7 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV24 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV24} LV24: .try { ldloc V_7 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV25 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV25} LV25: .try { ldloc V_7 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.B<valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV26 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV26} LV26: .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass1> V_8) ldloca V_8 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass1> .try { ldloc V_8 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV27 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV27} LV27: .try { ldloc V_8 ldstr "MyStruct292::Method4.MI.2317()#MyStruct292::Method5.MI.2319()#MyStruct292::Method6.MI.2321<System.Object>()#" call void Generated242::M.IBase1.A<valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV28 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV28} LV28: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV29 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV29} LV29: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV30 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV30} LV30: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.B.B<valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV31 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV31} LV31: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV32 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV32} LV32: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV33 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV33} LV33: .try { ldloc V_8 ldstr "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.IBase2.A.B<valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV34 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV34} LV34: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void StructConstrainedInterfaceCallsTest() cil managed { .maxstack 10 ldstr "===================== Struct Constrained Interface Calls Test =====================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass0> V_9) ldloca V_9 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass0> .try { ldloc V_9 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.T.T<class BaseClass0,class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!2,string) leave.s LV0 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV0} LV0: .try { ldloc V_9 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.A.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!1,string) leave.s LV1 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV1} LV1: .try { ldloc V_9 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.A.A<valuetype MyStruct292`2<class BaseClass0,class BaseClass0>>(!!0,string) leave.s LV2 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV2} LV2: .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass1> V_10) ldloca V_10 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass1> .try { ldloc V_10 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.T.T<class BaseClass0,class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!2,string) leave.s LV3 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV3} LV3: .try { ldloc V_10 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.A.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!1,string) leave.s LV4 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV4} LV4: .try { ldloc V_10 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.A.B<valuetype MyStruct292`2<class BaseClass0,class BaseClass1>>(!!0,string) leave.s LV5 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV5} LV5: .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass0> V_11) ldloca V_11 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass0> .try { ldloc V_11 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.T.T<class BaseClass1,class BaseClass0,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!2,string) leave.s LV6 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV6} LV6: .try { ldloc V_11 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.B.T<class BaseClass0,valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!1,string) leave.s LV7 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV7} LV7: .try { ldloc V_11 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.B.A<valuetype MyStruct292`2<class BaseClass1,class BaseClass0>>(!!0,string) leave.s LV8 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV8} LV8: .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass1> V_12) ldloca V_12 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass1> .try { ldloc V_12 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.T.T<class BaseClass1,class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!2,string) leave.s LV9 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV9} LV9: .try { ldloc V_12 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.B.T<class BaseClass1,valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!1,string) leave.s LV10 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV10} LV10: .try { ldloc V_12 ldstr "MyStruct292::Method4.MI.2317()#" + "MyStruct292::Method5.MI.2319()#" + "MyStruct292::Method6.MI.2321<System.Object>()#" + "MyStruct292::Method7.MI.2323<System.Object>()#" call void Generated242::M.MyStruct292.B.B<valuetype MyStruct292`2<class BaseClass1,class BaseClass1>>(!!0,string) leave.s LV11 } catch [mscorlib]System.Security.VerificationException { pop leave.s LV11} LV11: ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static void CalliTest() cil managed { .maxstack 10 .locals init (object V_0) ldstr "========================== Method Calli Test ==========================" call void [mscorlib]System.Console::WriteLine(string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass0> V_13) ldloca V_13 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod578() calli default string(object) ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod579() calli default string(object) ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod580<object>() calli default string(object) ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ClassMethod581<object>() calli default string(object) ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldnull ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance bool valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass0>::ToString() calli default string(object) pop ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldloc V_13 box valuetype MyStruct292`2<class BaseClass0,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct292`2<class BaseClass0,class BaseClass1> V_14) ldloca V_14 initobj valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod578() calli default string(object) ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod579() calli default string(object) ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod580<object>() calli default string(object) ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ClassMethod581<object>() calli default string(object) ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldnull ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance bool valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass0,class BaseClass1>::ToString() calli default string(object) pop ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldloc V_14 box valuetype MyStruct292`2<class BaseClass0,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass0,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass0> V_15) ldloca V_15 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod578() calli default string(object) ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod579() calli default string(object) ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod580<object>() calli default string(object) ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ClassMethod581<object>() calli default string(object) ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldnull ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance bool valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::Equals(object) calli default bool(object,object) pop ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance int32 valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::GetHashCode() calli default int32(object) pop ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass0>::ToString() calli default string(object) pop ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldloc V_15 box valuetype MyStruct292`2<class BaseClass1,class BaseClass0> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass0>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) .locals init (valuetype MyStruct292`2<class BaseClass1,class BaseClass1> V_16) ldloca V_16 initobj valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method4() calli default string(object) ldstr "MyStruct292::Method4.2316()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method5() calli default string(object) ldstr "MyStruct292::Method5.2318()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.2320<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.2322<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod578() calli default string(object) ldstr "MyStruct292::ClassMethod578.2324()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod579() calli default string(object) ldstr "MyStruct292::ClassMethod579.2325()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod580<object>() calli default string(object) ldstr "MyStruct292::ClassMethod580.2326<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ClassMethod581<object>() calli default string(object) ldstr "MyStruct292::ClassMethod581.2327<System.Object>()" ldstr "valuetype MyStruct292`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldnull ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance bool valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::Equals(object) calli default bool(object,object) pop ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance int32 valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::GetHashCode() calli default int32(object) pop ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string valuetype MyStruct292`2<class BaseClass1,class BaseClass1>::ToString() calli default string(object) pop ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method4() calli default string(object) ldstr "MyStruct292::Method4.MI.2317()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method5() calli default string(object) ldstr "MyStruct292::Method5.MI.2319()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase1`1<class BaseClass0>::Method6<object>() calli default string(object) ldstr "MyStruct292::Method6.MI.2321<System.Object>()" ldstr "class IBase1`1<class BaseClass0> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass1,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass1,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldloc V_16 box valuetype MyStruct292`2<class BaseClass1,class BaseClass1> ldvirtftn instance string class IBase2`2<class BaseClass0,class BaseClass1>::Method7<object>() calli default string(object) ldstr "MyStruct292::Method7.MI.2323<System.Object>()" ldstr "class IBase2`2<class BaseClass0,class BaseClass1> on type valuetype MyStruct292`2<class BaseClass1,class BaseClass1>" call void [TestFramework]TestFramework::MethodCallTest(string,string,string) ldstr "========================================================================\n\n" call void [mscorlib]System.Console::WriteLine(string) ret } .method public hidebysig static int32 Main() cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint .maxstack 10 call void Generated242::MethodCallingTest() call void Generated242::ConstrainedCallsTest() call void Generated242::StructConstrainedInterfaceCallsTest() call void Generated242::CalliTest() ldc.i4 100 ret } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/tests/JIT/CodeGenBringUpTests/FPFillArray_d.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="FPFillArray.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="FPFillArray.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Memory/tests/ReadOnlySpan/SequenceCompareTo.bool.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.SpanTests { public static partial class ReadOnlySpanTests { [Fact] public static void ZeroLengthSequenceCompareTo_Bool() { var a = new bool[3]; var first = new ReadOnlySpan<bool>(a, 1, 0); var second = new ReadOnlySpan<bool>(a, 2, 0); int result = first.SequenceCompareTo<bool>(second); Assert.Equal(0, result); } [Fact] public static void SameSpanSequenceCompareTo_Bool() { bool[] a = { true, true, false }; var span = new ReadOnlySpan<bool>(a); int result = span.SequenceCompareTo<bool>(span); Assert.Equal(0, result); } [Fact] public static void SequenceCompareToArrayImplicit_Bool() { bool[] a = { true, true, false }; var first = new ReadOnlySpan<bool>(a, 0, 3); int result = first.SequenceCompareTo<bool>(a); Assert.Equal(0, result); } [Fact] public static void SequenceCompareToArraySegmentImplicit_Bool() { bool[] src = { true, true, true }; bool[] dst = { false, true, true, true, false }; var segment = new ArraySegment<bool>(dst, 1, 3); var first = new ReadOnlySpan<bool>(src, 0, 3); int result = first.SequenceCompareTo<bool>(segment); Assert.Equal(0, result); } [Fact] public static void LengthMismatchSequenceCompareTo_Bool() { bool[] a = { true, true, false }; var first = new ReadOnlySpan<bool>(a, 0, 2); var second = new ReadOnlySpan<bool>(a, 0, 3); int result = first.SequenceCompareTo<bool>(second); Assert.True(result < 0); result = second.SequenceCompareTo<bool>(first); Assert.True(result > 0); // one sequence is empty first = new ReadOnlySpan<bool>(a, 1, 0); result = first.SequenceCompareTo<bool>(second); Assert.True(result < 0); result = second.SequenceCompareTo<bool>(first); Assert.True(result > 0); } [Fact] public static void SequenceCompareToWithSingleMismatch_Bool() { for (int length = 1; length < 32; length++) { for (int mismatchIndex = 0; mismatchIndex < length; mismatchIndex++) { var first = new bool[length]; var second = new bool[length]; for (int i = 0; i < length; i++) { first[i] = second[i] = true; } second[mismatchIndex] = !second[mismatchIndex]; var firstSpan = new ReadOnlySpan<bool>(first); var secondSpan = new ReadOnlySpan<bool>(second); int result = firstSpan.SequenceCompareTo<bool>(secondSpan); Assert.True(result > 0); result = secondSpan.SequenceCompareTo<bool>(firstSpan); Assert.True(result < 0); } } } [Fact] public static void SequenceCompareToNoMatch_Bool() { for (int length = 1; length < 32; length++) { var first = new bool[length]; var second = new bool[length]; for (int i = 0; i < length; i++) { first[i] = (i % 2 != 0); second[i] = (i % 2 == 0); } var firstSpan = new ReadOnlySpan<bool>(first); var secondSpan = new ReadOnlySpan<bool>(second); int result = firstSpan.SequenceCompareTo<bool>(secondSpan); Assert.True(result < 0); result = secondSpan.SequenceCompareTo<bool>(firstSpan); Assert.True(result > 0); } } [Fact] public static void MakeSureNoSequenceCompareToChecksGoOutOfRange_Bool() { for (int length = 0; length < 100; length++) { var first = new bool[length + 2]; first[0] = true; for (int k = 1; k <= length; k++) first[k] = false; first[length + 1] = true; var second = new bool[length + 2]; second[0] = false; for (int k = 1; k <= length; k++) second[k] = false; second[length + 1] = false; var span1 = new ReadOnlySpan<bool>(first, 1, length); var span2 = new ReadOnlySpan<bool>(second, 1, length); int result = span1.SequenceCompareTo<bool>(span2); Assert.Equal(0, result); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.SpanTests { public static partial class ReadOnlySpanTests { [Fact] public static void ZeroLengthSequenceCompareTo_Bool() { var a = new bool[3]; var first = new ReadOnlySpan<bool>(a, 1, 0); var second = new ReadOnlySpan<bool>(a, 2, 0); int result = first.SequenceCompareTo<bool>(second); Assert.Equal(0, result); } [Fact] public static void SameSpanSequenceCompareTo_Bool() { bool[] a = { true, true, false }; var span = new ReadOnlySpan<bool>(a); int result = span.SequenceCompareTo<bool>(span); Assert.Equal(0, result); } [Fact] public static void SequenceCompareToArrayImplicit_Bool() { bool[] a = { true, true, false }; var first = new ReadOnlySpan<bool>(a, 0, 3); int result = first.SequenceCompareTo<bool>(a); Assert.Equal(0, result); } [Fact] public static void SequenceCompareToArraySegmentImplicit_Bool() { bool[] src = { true, true, true }; bool[] dst = { false, true, true, true, false }; var segment = new ArraySegment<bool>(dst, 1, 3); var first = new ReadOnlySpan<bool>(src, 0, 3); int result = first.SequenceCompareTo<bool>(segment); Assert.Equal(0, result); } [Fact] public static void LengthMismatchSequenceCompareTo_Bool() { bool[] a = { true, true, false }; var first = new ReadOnlySpan<bool>(a, 0, 2); var second = new ReadOnlySpan<bool>(a, 0, 3); int result = first.SequenceCompareTo<bool>(second); Assert.True(result < 0); result = second.SequenceCompareTo<bool>(first); Assert.True(result > 0); // one sequence is empty first = new ReadOnlySpan<bool>(a, 1, 0); result = first.SequenceCompareTo<bool>(second); Assert.True(result < 0); result = second.SequenceCompareTo<bool>(first); Assert.True(result > 0); } [Fact] public static void SequenceCompareToWithSingleMismatch_Bool() { for (int length = 1; length < 32; length++) { for (int mismatchIndex = 0; mismatchIndex < length; mismatchIndex++) { var first = new bool[length]; var second = new bool[length]; for (int i = 0; i < length; i++) { first[i] = second[i] = true; } second[mismatchIndex] = !second[mismatchIndex]; var firstSpan = new ReadOnlySpan<bool>(first); var secondSpan = new ReadOnlySpan<bool>(second); int result = firstSpan.SequenceCompareTo<bool>(secondSpan); Assert.True(result > 0); result = secondSpan.SequenceCompareTo<bool>(firstSpan); Assert.True(result < 0); } } } [Fact] public static void SequenceCompareToNoMatch_Bool() { for (int length = 1; length < 32; length++) { var first = new bool[length]; var second = new bool[length]; for (int i = 0; i < length; i++) { first[i] = (i % 2 != 0); second[i] = (i % 2 == 0); } var firstSpan = new ReadOnlySpan<bool>(first); var secondSpan = new ReadOnlySpan<bool>(second); int result = firstSpan.SequenceCompareTo<bool>(secondSpan); Assert.True(result < 0); result = secondSpan.SequenceCompareTo<bool>(firstSpan); Assert.True(result > 0); } } [Fact] public static void MakeSureNoSequenceCompareToChecksGoOutOfRange_Bool() { for (int length = 0; length < 100; length++) { var first = new bool[length + 2]; first[0] = true; for (int k = 1; k <= length; k++) first[k] = false; first[length + 1] = true; var second = new bool[length + 2]; second[0] = false; for (int k = 1; k <= length; k++) second[k] = false; second[length + 1] = false; var span1 = new ReadOnlySpan<bool>(first, 1, length); var span2 = new ReadOnlySpan<bool>(second, 1, length); int result = span1.SequenceCompareTo<bool>(span2); Assert.Equal(0, result); } } } }
-1
dotnet/runtime
66,019
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows
fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
hwoodiwiss
2022-03-01T19:11:55Z
2022-03-29T16:19:44Z
d2d22812bf403b145d7eae1729754104d2c5d90f
0eccdba3ad269ac09dceb9d53d9ed63e19d5134a
Improve `QuicImplementationProviders.MsQuic.IsSupported` for TLS1.3 On Windows. fixes #55237 Adds a registry check to detect whether TLS1.3 Has been disabled in the registry on windows. Adds this check to MsQuic.IsSupported
./src/libraries/System.Private.CoreLib/src/System/Numerics/Plane.cs
// 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.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Numerics { /// <summary>Represents a plane in three-dimensional space.</summary> /// <remarks><format type="text/markdown"><![CDATA[ /// [!INCLUDE[vectors-are-rows-paragraph](~/includes/system-numerics-vectors-are-rows.md)] /// ]]></format></remarks> [Intrinsic] public struct Plane : IEquatable<Plane> { private const float NormalizeEpsilon = 1.192092896e-07f; // smallest such that 1.0+NormalizeEpsilon != 1.0 /// <summary>The normal vector of the plane.</summary> public Vector3 Normal; /// <summary>The distance of the plane along its normal from the origin.</summary> public float D; /// <summary>Creates a <see cref="System.Numerics.Plane" /> object from the X, Y, and Z components of its normal, and its distance from the origin on that normal.</summary> /// <param name="x">The X component of the normal.</param> /// <param name="y">The Y component of the normal.</param> /// <param name="z">The Z component of the normal.</param> /// <param name="d">The distance of the plane along its normal from the origin.</param> public Plane(float x, float y, float z, float d) { Normal = new Vector3(x, y, z); D = d; } /// <summary>Creates a <see cref="System.Numerics.Plane" /> object from a specified normal and the distance along the normal from the origin.</summary> /// <param name="normal">The plane's normal vector.</param> /// <param name="d">The plane's distance from the origin along its normal vector.</param> public Plane(Vector3 normal, float d) { Normal = normal; D = d; } /// <summary>Creates a <see cref="System.Numerics.Plane" /> object from a specified four-dimensional vector.</summary> /// <param name="value">A vector whose first three elements describe the normal vector, and whose <see cref="System.Numerics.Vector4.W" /> defines the distance along that normal from the origin.</param> public Plane(Vector4 value) { Normal = new Vector3(value.X, value.Y, value.Z); D = value.W; } /// <summary>Creates a <see cref="System.Numerics.Plane" /> object that contains three specified points.</summary> /// <param name="point1">The first point defining the plane.</param> /// <param name="point2">The second point defining the plane.</param> /// <param name="point3">The third point defining the plane.</param> /// <returns>The plane containing the three points.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane CreateFromVertices(Vector3 point1, Vector3 point2, Vector3 point3) { if (Vector.IsHardwareAccelerated) { Vector3 a = point2 - point1; Vector3 b = point3 - point1; // N = Cross(a, b) Vector3 n = Vector3.Cross(a, b); Vector3 normal = Vector3.Normalize(n); // D = - Dot(N, point1) float d = -Vector3.Dot(normal, point1); return new Plane(normal, d); } else { float ax = point2.X - point1.X; float ay = point2.Y - point1.Y; float az = point2.Z - point1.Z; float bx = point3.X - point1.X; float by = point3.Y - point1.Y; float bz = point3.Z - point1.Z; // N=Cross(a,b) float nx = ay * bz - az * by; float ny = az * bx - ax * bz; float nz = ax * by - ay * bx; // Normalize(N) float ls = nx * nx + ny * ny + nz * nz; float invNorm = 1.0f / MathF.Sqrt(ls); Vector3 normal = new Vector3( nx * invNorm, ny * invNorm, nz * invNorm); return new Plane( normal, -(normal.X * point1.X + normal.Y * point1.Y + normal.Z * point1.Z)); } } /// <summary>Calculates the dot product of a plane and a 4-dimensional vector.</summary> /// <param name="plane">The plane.</param> /// <param name="value">The four-dimensional vector.</param> /// <returns>The dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Plane plane, Vector4 value) { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D * value.W; } /// <summary>Returns the dot product of a specified three-dimensional vector and the normal vector of this plane plus the distance (<see cref="System.Numerics.Plane.D" />) value of the plane.</summary> /// <param name="plane">The plane.</param> /// <param name="value">The 3-dimensional vector.</param> /// <returns>The dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotCoordinate(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value) + plane.D; } else { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D; } } /// <summary>Returns the dot product of a specified three-dimensional vector and the <see cref="System.Numerics.Plane.Normal" /> vector of this plane.</summary> /// <param name="plane">The plane.</param> /// <param name="value">The three-dimensional vector.</param> /// <returns>The dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotNormal(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value); } else { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z; } } /// <summary>Creates a new <see cref="System.Numerics.Plane" /> object whose normal vector is the source plane's normal vector normalized.</summary> /// <param name="value">The source plane.</param> /// <returns>The normalized plane.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Normalize(Plane value) { if (Vector.IsHardwareAccelerated) { float normalLengthSquared = value.Normal.LengthSquared(); if (MathF.Abs(normalLengthSquared - 1.0f) < NormalizeEpsilon) { // It already normalized, so we don't need to farther process. return value; } float normalLength = MathF.Sqrt(normalLengthSquared); return new Plane( value.Normal / normalLength, value.D / normalLength); } else { float f = value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z; if (MathF.Abs(f - 1.0f) < NormalizeEpsilon) { return value; // It already normalized, so we don't need to further process. } float fInv = 1.0f / MathF.Sqrt(f); return new Plane( value.Normal.X * fInv, value.Normal.Y * fInv, value.Normal.Z * fInv, value.D * fInv); } } /// <summary>Transforms a normalized plane by a 4x4 matrix.</summary> /// <param name="plane">The normalized plane to transform.</param> /// <param name="matrix">The transformation matrix to apply to <paramref name="plane" />.</param> /// <returns>The transformed plane.</returns> /// <remarks><paramref name="plane" /> must already be normalized so that its <see cref="System.Numerics.Plane.Normal" /> vector is of unit length before this method is called.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Matrix4x4 matrix) { Matrix4x4.Invert(matrix, out Matrix4x4 m); float x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z, w = plane.D; return new Plane( x * m.M11 + y * m.M12 + z * m.M13 + w * m.M14, x * m.M21 + y * m.M22 + z * m.M23 + w * m.M24, x * m.M31 + y * m.M32 + z * m.M33 + w * m.M34, x * m.M41 + y * m.M42 + z * m.M43 + w * m.M44); } /// <summary>Transforms a normalized plane by a Quaternion rotation.</summary> /// <param name="plane">The normalized plane to transform.</param> /// <param name="rotation">The Quaternion rotation to apply to the plane.</param> /// <returns>A new plane that results from applying the Quaternion rotation.</returns> /// <remarks><paramref name="plane" /> must already be normalized so that its <see cref="System.Numerics.Plane.Normal" /> vector is of unit length before this method is called.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Quaternion rotation) { // Compute rotation matrix. float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wx2 = rotation.W * x2; float wy2 = rotation.W * y2; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float xz2 = rotation.X * z2; float yy2 = rotation.Y * y2; float yz2 = rotation.Y * z2; float zz2 = rotation.Z * z2; float m11 = 1.0f - yy2 - zz2; float m21 = xy2 - wz2; float m31 = xz2 + wy2; float m12 = xy2 + wz2; float m22 = 1.0f - xx2 - zz2; float m32 = yz2 - wx2; float m13 = xz2 - wy2; float m23 = yz2 + wx2; float m33 = 1.0f - xx2 - yy2; float x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z; return new Plane( x * m11 + y * m21 + z * m31, x * m12 + y * m22 + z * m32, x * m13 + y * m23 + z * m33, plane.D); } /// <summary>Returns a value that indicates whether two planes are equal.</summary> /// <param name="value1">The first plane to compare.</param> /// <param name="value2">The second plane to compare.</param> /// <returns><see langword="true" /> if <paramref name="value1" /> and <paramref name="value2" /> are equal; otherwise, <see langword="false" />.</returns> /// <remarks>Two <see cref="System.Numerics.Plane" /> objects are equal if their <see cref="System.Numerics.Plane.Normal" /> and <see cref="System.Numerics.Plane.D" /> fields are equal. /// The <see cref="System.Numerics.Plane.op_Equality" /> method defines the operation of the equality operator for <see cref="System.Numerics.Plane" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Plane value1, Plane value2) { return (value1.Normal.X == value2.Normal.X && value1.Normal.Y == value2.Normal.Y && value1.Normal.Z == value2.Normal.Z && value1.D == value2.D); } /// <summary>Returns a value that indicates whether two planes are not equal.</summary> /// <param name="value1">The first plane to compare.</param> /// <param name="value2">The second plane to compare.</param> /// <returns><see langword="true" /> if <paramref name="value1" /> and <paramref name="value2" /> are not equal; otherwise, <see langword="false" />.</returns> /// <remarks>The <see cref="System.Numerics.Plane.op_Inequality" /> method defines the operation of the inequality operator for <see cref="System.Numerics.Plane" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Plane value1, Plane value2) { return !(value1 == value2); } /// <summary>Returns a value that indicates whether this instance and a specified object are equal.</summary> /// <param name="obj">The object to compare with the current instance.</param> /// <returns><see langword="true" /> if the current instance and <paramref name="obj" /> are equal; otherwise, <see langword="false" />. If <paramref name="obj" /> is <see langword="null" />, the method returns <see langword="false" />.</returns> /// <remarks>The current instance and <paramref name="obj" /> are equal if <paramref name="obj" /> is a <see cref="System.Numerics.Plane" /> object and their <see cref="System.Numerics.Plane.Normal" /> and <see cref="System.Numerics.Plane.D" /> fields are equal.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { return (obj is Plane other) && Equals(other); } /// <summary>Returns a value that indicates whether this instance and another plane object are equal.</summary> /// <param name="other">The other plane.</param> /// <returns><see langword="true" /> if the two planes are equal; otherwise, <see langword="false" />.</returns> /// <remarks>Two <see cref="System.Numerics.Plane" /> objects are equal if their <see cref="System.Numerics.Plane.Normal" /> and <see cref="System.Numerics.Plane.D" /> fields are equal.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly bool Equals(Plane other) { if (Vector.IsHardwareAccelerated) { return Normal.Equals(other.Normal) && D == other.D; } else { return (Normal.X == other.Normal.X && Normal.Y == other.Normal.Y && Normal.Z == other.Normal.Z && D == other.D); } } /// <summary>Returns the hash code for this instance.</summary> /// <returns>The hash code.</returns> public override readonly int GetHashCode() { return Normal.GetHashCode() + D.GetHashCode(); } /// <summary>Returns the string representation of this plane object.</summary> /// <returns>A string that represents this <see cref="System.Numerics.Plane" /> object.</returns> /// <remarks>The string representation of a <see cref="System.Numerics.Plane" /> object use the formatting conventions of the current culture to format the numeric values in the returned string. For example, a <see cref="System.Numerics.Plane" /> object whose string representation is formatted by using the conventions of the en-US culture might appear as <c>{Normal:&lt;1.1, 2.2, 3.3&gt; D:4.4}</c>.</remarks> public override readonly string ToString() => $"{{Normal:{Normal} D:{D}}}"; } }
// 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.CodeAnalysis; using System.Globalization; using System.Runtime.CompilerServices; namespace System.Numerics { /// <summary>Represents a plane in three-dimensional space.</summary> /// <remarks><format type="text/markdown"><![CDATA[ /// [!INCLUDE[vectors-are-rows-paragraph](~/includes/system-numerics-vectors-are-rows.md)] /// ]]></format></remarks> [Intrinsic] public struct Plane : IEquatable<Plane> { private const float NormalizeEpsilon = 1.192092896e-07f; // smallest such that 1.0+NormalizeEpsilon != 1.0 /// <summary>The normal vector of the plane.</summary> public Vector3 Normal; /// <summary>The distance of the plane along its normal from the origin.</summary> public float D; /// <summary>Creates a <see cref="System.Numerics.Plane" /> object from the X, Y, and Z components of its normal, and its distance from the origin on that normal.</summary> /// <param name="x">The X component of the normal.</param> /// <param name="y">The Y component of the normal.</param> /// <param name="z">The Z component of the normal.</param> /// <param name="d">The distance of the plane along its normal from the origin.</param> public Plane(float x, float y, float z, float d) { Normal = new Vector3(x, y, z); D = d; } /// <summary>Creates a <see cref="System.Numerics.Plane" /> object from a specified normal and the distance along the normal from the origin.</summary> /// <param name="normal">The plane's normal vector.</param> /// <param name="d">The plane's distance from the origin along its normal vector.</param> public Plane(Vector3 normal, float d) { Normal = normal; D = d; } /// <summary>Creates a <see cref="System.Numerics.Plane" /> object from a specified four-dimensional vector.</summary> /// <param name="value">A vector whose first three elements describe the normal vector, and whose <see cref="System.Numerics.Vector4.W" /> defines the distance along that normal from the origin.</param> public Plane(Vector4 value) { Normal = new Vector3(value.X, value.Y, value.Z); D = value.W; } /// <summary>Creates a <see cref="System.Numerics.Plane" /> object that contains three specified points.</summary> /// <param name="point1">The first point defining the plane.</param> /// <param name="point2">The second point defining the plane.</param> /// <param name="point3">The third point defining the plane.</param> /// <returns>The plane containing the three points.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane CreateFromVertices(Vector3 point1, Vector3 point2, Vector3 point3) { if (Vector.IsHardwareAccelerated) { Vector3 a = point2 - point1; Vector3 b = point3 - point1; // N = Cross(a, b) Vector3 n = Vector3.Cross(a, b); Vector3 normal = Vector3.Normalize(n); // D = - Dot(N, point1) float d = -Vector3.Dot(normal, point1); return new Plane(normal, d); } else { float ax = point2.X - point1.X; float ay = point2.Y - point1.Y; float az = point2.Z - point1.Z; float bx = point3.X - point1.X; float by = point3.Y - point1.Y; float bz = point3.Z - point1.Z; // N=Cross(a,b) float nx = ay * bz - az * by; float ny = az * bx - ax * bz; float nz = ax * by - ay * bx; // Normalize(N) float ls = nx * nx + ny * ny + nz * nz; float invNorm = 1.0f / MathF.Sqrt(ls); Vector3 normal = new Vector3( nx * invNorm, ny * invNorm, nz * invNorm); return new Plane( normal, -(normal.X * point1.X + normal.Y * point1.Y + normal.Z * point1.Z)); } } /// <summary>Calculates the dot product of a plane and a 4-dimensional vector.</summary> /// <param name="plane">The plane.</param> /// <param name="value">The four-dimensional vector.</param> /// <returns>The dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Plane plane, Vector4 value) { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D * value.W; } /// <summary>Returns the dot product of a specified three-dimensional vector and the normal vector of this plane plus the distance (<see cref="System.Numerics.Plane.D" />) value of the plane.</summary> /// <param name="plane">The plane.</param> /// <param name="value">The 3-dimensional vector.</param> /// <returns>The dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotCoordinate(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value) + plane.D; } else { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D; } } /// <summary>Returns the dot product of a specified three-dimensional vector and the <see cref="System.Numerics.Plane.Normal" /> vector of this plane.</summary> /// <param name="plane">The plane.</param> /// <param name="value">The three-dimensional vector.</param> /// <returns>The dot product.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotNormal(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value); } else { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z; } } /// <summary>Creates a new <see cref="System.Numerics.Plane" /> object whose normal vector is the source plane's normal vector normalized.</summary> /// <param name="value">The source plane.</param> /// <returns>The normalized plane.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Normalize(Plane value) { if (Vector.IsHardwareAccelerated) { float normalLengthSquared = value.Normal.LengthSquared(); if (MathF.Abs(normalLengthSquared - 1.0f) < NormalizeEpsilon) { // It already normalized, so we don't need to farther process. return value; } float normalLength = MathF.Sqrt(normalLengthSquared); return new Plane( value.Normal / normalLength, value.D / normalLength); } else { float f = value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z; if (MathF.Abs(f - 1.0f) < NormalizeEpsilon) { return value; // It already normalized, so we don't need to further process. } float fInv = 1.0f / MathF.Sqrt(f); return new Plane( value.Normal.X * fInv, value.Normal.Y * fInv, value.Normal.Z * fInv, value.D * fInv); } } /// <summary>Transforms a normalized plane by a 4x4 matrix.</summary> /// <param name="plane">The normalized plane to transform.</param> /// <param name="matrix">The transformation matrix to apply to <paramref name="plane" />.</param> /// <returns>The transformed plane.</returns> /// <remarks><paramref name="plane" /> must already be normalized so that its <see cref="System.Numerics.Plane.Normal" /> vector is of unit length before this method is called.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Matrix4x4 matrix) { Matrix4x4.Invert(matrix, out Matrix4x4 m); float x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z, w = plane.D; return new Plane( x * m.M11 + y * m.M12 + z * m.M13 + w * m.M14, x * m.M21 + y * m.M22 + z * m.M23 + w * m.M24, x * m.M31 + y * m.M32 + z * m.M33 + w * m.M34, x * m.M41 + y * m.M42 + z * m.M43 + w * m.M44); } /// <summary>Transforms a normalized plane by a Quaternion rotation.</summary> /// <param name="plane">The normalized plane to transform.</param> /// <param name="rotation">The Quaternion rotation to apply to the plane.</param> /// <returns>A new plane that results from applying the Quaternion rotation.</returns> /// <remarks><paramref name="plane" /> must already be normalized so that its <see cref="System.Numerics.Plane.Normal" /> vector is of unit length before this method is called.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Quaternion rotation) { // Compute rotation matrix. float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wx2 = rotation.W * x2; float wy2 = rotation.W * y2; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float xz2 = rotation.X * z2; float yy2 = rotation.Y * y2; float yz2 = rotation.Y * z2; float zz2 = rotation.Z * z2; float m11 = 1.0f - yy2 - zz2; float m21 = xy2 - wz2; float m31 = xz2 + wy2; float m12 = xy2 + wz2; float m22 = 1.0f - xx2 - zz2; float m32 = yz2 - wx2; float m13 = xz2 - wy2; float m23 = yz2 + wx2; float m33 = 1.0f - xx2 - yy2; float x = plane.Normal.X, y = plane.Normal.Y, z = plane.Normal.Z; return new Plane( x * m11 + y * m21 + z * m31, x * m12 + y * m22 + z * m32, x * m13 + y * m23 + z * m33, plane.D); } /// <summary>Returns a value that indicates whether two planes are equal.</summary> /// <param name="value1">The first plane to compare.</param> /// <param name="value2">The second plane to compare.</param> /// <returns><see langword="true" /> if <paramref name="value1" /> and <paramref name="value2" /> are equal; otherwise, <see langword="false" />.</returns> /// <remarks>Two <see cref="System.Numerics.Plane" /> objects are equal if their <see cref="System.Numerics.Plane.Normal" /> and <see cref="System.Numerics.Plane.D" /> fields are equal. /// The <see cref="System.Numerics.Plane.op_Equality" /> method defines the operation of the equality operator for <see cref="System.Numerics.Plane" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Plane value1, Plane value2) { return (value1.Normal.X == value2.Normal.X && value1.Normal.Y == value2.Normal.Y && value1.Normal.Z == value2.Normal.Z && value1.D == value2.D); } /// <summary>Returns a value that indicates whether two planes are not equal.</summary> /// <param name="value1">The first plane to compare.</param> /// <param name="value2">The second plane to compare.</param> /// <returns><see langword="true" /> if <paramref name="value1" /> and <paramref name="value2" /> are not equal; otherwise, <see langword="false" />.</returns> /// <remarks>The <see cref="System.Numerics.Plane.op_Inequality" /> method defines the operation of the inequality operator for <see cref="System.Numerics.Plane" /> objects.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Plane value1, Plane value2) { return !(value1 == value2); } /// <summary>Returns a value that indicates whether this instance and a specified object are equal.</summary> /// <param name="obj">The object to compare with the current instance.</param> /// <returns><see langword="true" /> if the current instance and <paramref name="obj" /> are equal; otherwise, <see langword="false" />. If <paramref name="obj" /> is <see langword="null" />, the method returns <see langword="false" />.</returns> /// <remarks>The current instance and <paramref name="obj" /> are equal if <paramref name="obj" /> is a <see cref="System.Numerics.Plane" /> object and their <see cref="System.Numerics.Plane.Normal" /> and <see cref="System.Numerics.Plane.D" /> fields are equal.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { return (obj is Plane other) && Equals(other); } /// <summary>Returns a value that indicates whether this instance and another plane object are equal.</summary> /// <param name="other">The other plane.</param> /// <returns><see langword="true" /> if the two planes are equal; otherwise, <see langword="false" />.</returns> /// <remarks>Two <see cref="System.Numerics.Plane" /> objects are equal if their <see cref="System.Numerics.Plane.Normal" /> and <see cref="System.Numerics.Plane.D" /> fields are equal.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly bool Equals(Plane other) { if (Vector.IsHardwareAccelerated) { return Normal.Equals(other.Normal) && D == other.D; } else { return (Normal.X == other.Normal.X && Normal.Y == other.Normal.Y && Normal.Z == other.Normal.Z && D == other.D); } } /// <summary>Returns the hash code for this instance.</summary> /// <returns>The hash code.</returns> public override readonly int GetHashCode() { return Normal.GetHashCode() + D.GetHashCode(); } /// <summary>Returns the string representation of this plane object.</summary> /// <returns>A string that represents this <see cref="System.Numerics.Plane" /> object.</returns> /// <remarks>The string representation of a <see cref="System.Numerics.Plane" /> object use the formatting conventions of the current culture to format the numeric values in the returned string. For example, a <see cref="System.Numerics.Plane" /> object whose string representation is formatted by using the conventions of the en-US culture might appear as <c>{Normal:&lt;1.1, 2.2, 3.3&gt; D:4.4}</c>.</remarks> public override readonly string ToString() => $"{{Normal:{Normal} D:{D}}}"; } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Compile Include="System\Collections\HashtableExtensions.cs" /> <Compile Include="System\Collections\Generic\ValueListBuilder.Pop.cs" /> <Compile Include="System\Threading\StackHelper.cs" /> <Compile Include="System\Text\SegmentStringBuilder.cs" /> <Compile Include="System\Text\RegularExpressions\Capture.cs" /> <Compile Include="System\Text\RegularExpressions\CaptureCollection.cs" /> <Compile Include="System\Text\RegularExpressions\CollectionDebuggerProxy.cs" /> <Compile Include="System\Text\RegularExpressions\Group.cs" /> <Compile Include="System\Text\RegularExpressions\GroupCollection.cs" /> <Compile Include="System\Text\RegularExpressions\Match.cs" /> <Compile Include="System\Text\RegularExpressions\MatchCollection.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Cache.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Count.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Debug.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Match.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Replace.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Split.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Timeout.cs" /> <Compile Include="System\Text\RegularExpressions\RegexCharClass.cs" /> <Compile Include="System\Text\RegularExpressions\RegexCharClass.MappingTable.cs" /> <Compile Include="System\Text\RegularExpressions\RegexCompilationInfo.cs" /> <Compile Include="System\Text\RegularExpressions\RegexFindOptimizations.cs" /> <Compile Include="System\Text\RegularExpressions\RegexGeneratorAttribute.cs" /> <Compile Include="System\Text\RegularExpressions\RegexInterpreter.cs" /> <Compile Include="System\Text\RegularExpressions\RegexInterpreterCode.cs" /> <Compile Include="System\Text\RegularExpressions\RegexMatchTimeoutException.cs" /> <Compile Include="System\Text\RegularExpressions\RegexNode.cs" /> <Compile Include="System\Text\RegularExpressions\RegexNodeKind.cs" /> <Compile Include="System\Text\RegularExpressions\RegexOpcode.cs" /> <Compile Include="System\Text\RegularExpressions\RegexOptions.cs" /> <Compile Include="System\Text\RegularExpressions\RegexParseError.cs" /> <Compile Include="System\Text\RegularExpressions\RegexParseException.cs" /> <Compile Include="System\Text\RegularExpressions\RegexParser.cs" /> <Compile Include="System\Text\RegularExpressions\RegexPrefixAnalyzer.cs" /> <Compile Include="System\Text\RegularExpressions\RegexReplacement.cs" /> <Compile Include="System\Text\RegularExpressions\RegexRunner.cs" /> <Compile Include="System\Text\RegularExpressions\RegexRunnerFactory.cs" /> <Compile Include="System\Text\RegularExpressions\RegexTree.cs" /> <Compile Include="System\Text\RegularExpressions\RegexTreeAnalyzer.cs" /> <Compile Include="System\Text\RegularExpressions\RegexWriter.cs" /> <Compile Include="System\Text\RegularExpressions\ThrowHelper.cs" /> <!-- RegexOptions.Compiled --> <Compile Include="System\Text\RegularExpressions\CompiledRegexRunnerFactory.cs" /> <Compile Include="System\Text\RegularExpressions\CompiledRegexRunner.cs" /> <Compile Include="System\Text\RegularExpressions\RegexCompiler.cs" /> <Compile Include="System\Text\RegularExpressions\RegexLWCGCompiler.cs" /> <!-- RegexOptions.NonBacktracking --> <Compile Include="System\Text\RegularExpressions\Symbolic\BooleanClassifier.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\CharKind.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\DerivativeEffect.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\DfaMatchingState.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\MintermClassifier.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\RegexNodeConverter.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SparseIntMap.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicMatch.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicNFA.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexBuilder.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexNode.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexKind.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexInfo.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexMatcher.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexRunnerFactory.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexSampler.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexSet.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\TransitionRegex.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\TransitionRegexKind.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\BDD.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\BDDAlgebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\BDDRangeConverter.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\BV.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\BV64Algebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\BVAlgebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\CharSetSolver.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\IBooleanAlgebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\ICharAlgebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Algebras\MintermGenerator.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Dgml\DgmlWriter.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Dgml\IAutomaton.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Dgml\Move.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Dgml\RegexAutomaton.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\GeneratorHelper.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\IgnoreCaseRelation.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\IgnoreCaseRelationGenerator.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\IgnoreCaseTransformer.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\UnicodeCategoryRanges.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\UnicodeCategoryRangesGenerator.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\UnicodeCategoryTheory.cs" /> <!-- Common or Common-branched source files --> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> <Compile Include="$(CommonPath)System\NotImplemented.cs" Link="Common\System\NotImplemented.cs" /> <Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs" Link="Common\System\Text\ValueStringBuilder.cs" /> <Compile Include="$(CoreLibSharedDir)System\Collections\Generic\ValueListBuilder.cs" Link="Common\System\Collections\Generic\ValueListBuilder.cs" /> </ItemGroup> <ItemGroup> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" /> <Reference Include="System.Memory" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.Extensions" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Threading" /> <!-- References required for RegexOptions.Compiled --> <Reference Include="System.Reflection.Emit" /> <Reference Include="System.Reflection.Emit.ILGeneration" /> <Reference Include="System.Reflection.Emit.Lightweight" /> <Reference Include="System.Reflection.Primitives" /> <!-- Adding the source generator as an analyzer reference --> <AnalyzerReference Include="..\gen\System.Text.RegularExpressions.Generator.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <Compile Include="System\Collections\HashtableExtensions.cs" /> <Compile Include="System\Collections\Generic\ValueListBuilder.Pop.cs" /> <Compile Include="System\Threading\StackHelper.cs" /> <Compile Include="System\Text\SegmentStringBuilder.cs" /> <Compile Include="System\Text\RegularExpressions\Capture.cs" /> <Compile Include="System\Text\RegularExpressions\CaptureCollection.cs" /> <Compile Include="System\Text\RegularExpressions\CollectionDebuggerProxy.cs" /> <Compile Include="System\Text\RegularExpressions\Group.cs" /> <Compile Include="System\Text\RegularExpressions\GroupCollection.cs" /> <Compile Include="System\Text\RegularExpressions\Match.cs" /> <Compile Include="System\Text\RegularExpressions\MatchCollection.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Cache.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Count.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Debug.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Match.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Replace.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Split.cs" /> <Compile Include="System\Text\RegularExpressions\Regex.Timeout.cs" /> <Compile Include="System\Text\RegularExpressions\RegexCharClass.cs" /> <Compile Include="System\Text\RegularExpressions\RegexCharClass.MappingTable.cs" /> <Compile Include="System\Text\RegularExpressions\RegexCompilationInfo.cs" /> <Compile Include="System\Text\RegularExpressions\RegexFindOptimizations.cs" /> <Compile Include="System\Text\RegularExpressions\RegexGeneratorAttribute.cs" /> <Compile Include="System\Text\RegularExpressions\RegexInterpreter.cs" /> <Compile Include="System\Text\RegularExpressions\RegexInterpreterCode.cs" /> <Compile Include="System\Text\RegularExpressions\RegexMatchTimeoutException.cs" /> <Compile Include="System\Text\RegularExpressions\RegexNode.cs" /> <Compile Include="System\Text\RegularExpressions\RegexNodeKind.cs" /> <Compile Include="System\Text\RegularExpressions\RegexOpcode.cs" /> <Compile Include="System\Text\RegularExpressions\RegexOptions.cs" /> <Compile Include="System\Text\RegularExpressions\RegexParseError.cs" /> <Compile Include="System\Text\RegularExpressions\RegexParseException.cs" /> <Compile Include="System\Text\RegularExpressions\RegexParser.cs" /> <Compile Include="System\Text\RegularExpressions\RegexPrefixAnalyzer.cs" /> <Compile Include="System\Text\RegularExpressions\RegexReplacement.cs" /> <Compile Include="System\Text\RegularExpressions\RegexRunner.cs" /> <Compile Include="System\Text\RegularExpressions\RegexRunnerFactory.cs" /> <Compile Include="System\Text\RegularExpressions\RegexTree.cs" /> <Compile Include="System\Text\RegularExpressions\RegexTreeAnalyzer.cs" /> <Compile Include="System\Text\RegularExpressions\RegexWriter.cs" /> <Compile Include="System\Text\RegularExpressions\ThrowHelper.cs" /> <!-- RegexOptions.Compiled --> <Compile Include="System\Text\RegularExpressions\CompiledRegexRunnerFactory.cs" /> <Compile Include="System\Text\RegularExpressions\CompiledRegexRunner.cs" /> <Compile Include="System\Text\RegularExpressions\RegexCompiler.cs" /> <Compile Include="System\Text\RegularExpressions\RegexLWCGCompiler.cs" /> <!-- RegexOptions.NonBacktracking --> <Compile Include="System\Text\RegularExpressions\Symbolic\BDD.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\BDDAlgebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\BDDRangeConverter.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\BooleanClassifier.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\BitVector.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\BitVector64Algebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\BitVectorAlgebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\CharKind.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\CharSetSolver.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\DerivativeEffect.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\DfaMatchingState.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\IBooleanAlgebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\ICharAlgebra.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\MintermClassifier.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\MintermGenerator.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\RegexNodeConverter.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SparseIntMap.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicMatch.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicNFA.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexBuilder.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexNode.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexKind.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexInfo.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexMatcher.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexRunnerFactory.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexSampler.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\SymbolicRegexSet.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\TransitionRegex.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\TransitionRegexKind.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Dgml\DgmlWriter.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Dgml\IAutomaton.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Dgml\Move.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Dgml\RegexAutomaton.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\GeneratorHelper.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\IgnoreCaseRelation.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\IgnoreCaseRelationGenerator.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\IgnoreCaseTransformer.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\UnicodeCategoryRanges.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\UnicodeCategoryRangesGenerator.cs" /> <Compile Include="System\Text\RegularExpressions\Symbolic\Unicode\UnicodeCategoryTheory.cs" /> <!-- Common or Common-branched source files --> <Compile Include="$(CommonPath)System\HexConverter.cs" Link="Common\System\HexConverter.cs" /> <Compile Include="$(CommonPath)System\NotImplemented.cs" Link="Common\System\NotImplemented.cs" /> <Compile Include="$(CommonPath)System\Obsoletions.cs" Link="Common\System\Obsoletions.cs" /> <Compile Include="$(CommonPath)System\Text\ValueStringBuilder.cs" Link="Common\System\Text\ValueStringBuilder.cs" /> <Compile Include="$(CoreLibSharedDir)System\Collections\Generic\ValueListBuilder.cs" Link="Common\System\Collections\Generic\ValueListBuilder.cs" /> </ItemGroup> <ItemGroup> <Reference Include="System.Collections" /> <Reference Include="System.Collections.Concurrent" /> <Reference Include="System.Memory" /> <Reference Include="System.Runtime" /> <Reference Include="System.Runtime.Extensions" /> <Reference Include="System.Runtime.InteropServices" /> <Reference Include="System.Threading" /> <!-- References required for RegexOptions.Compiled --> <Reference Include="System.Reflection.Emit" /> <Reference Include="System.Reflection.Emit.ILGeneration" /> <Reference Include="System.Reflection.Emit.Lightweight" /> <Reference Include="System.Reflection.Primitives" /> <!-- Adding the source generator as an analyzer reference --> <AnalyzerReference Include="..\gen\System.Text.RegularExpressions.Generator.csproj" /> </ItemGroup> </Project>
1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/RegexNodeConverter.cs
// 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; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text.RegularExpressions.Symbolic.Unicode; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Provides functionality to convert <see cref="RegexNode"/>s to corresponding <see cref="SymbolicRegexNode{S}"/>s.</summary> internal sealed class RegexNodeConverter { /// <summary>The culture to use for IgnoreCase comparisons.</summary> private readonly CultureInfo _culture; /// <summary>Capture information.</summary> private readonly Hashtable? _captureSparseMapping; /// <summary>The builder to use to create the <see cref="SymbolicRegexNode{S}"/> nodes.</summary> internal readonly SymbolicRegexBuilder<BDD> _builder; /// <summary>Cache of BDDs created to represent <see cref="RegexCharClass"/> set strings.</summary> /// <remarks>This cache is useful iff the same character class is used multiple times in the same regex, but that's fairly common.</remarks> private Dictionary<(bool IgnoreCase, string Set), BDD>? _setBddCache; /// <summary>Constructs a regex to symbolic finite automata converter</summary> public RegexNodeConverter(CultureInfo culture, Hashtable? captureSparseMapping) { _culture = culture; _captureSparseMapping = captureSparseMapping; _builder = new SymbolicRegexBuilder<BDD>(CharSetSolver.Instance); } /// <summary>Converts a <see cref="RegexNode"/> into its corresponding <see cref="SymbolicRegexNode{S}"/>.</summary> /// <param name="node">The node to convert.</param> /// <param name="tryCreateFixedLengthMarker">Whether we should attempt to create a fixed length marker after this node.</param> /// <returns>The generated <see cref="SymbolicRegexNode{S}"/> that corresponds to the supplied <paramref name="node"/>.</returns> public SymbolicRegexNode<BDD> ConvertToSymbolicRegexNode(RegexNode node, bool tryCreateFixedLengthMarker) { // We're processing the node tree recursively and need to avoid stack overflows for really deep trees. // To achieve this, if we detect we're too deep on the stack, we fork off the handling of this node // to another thread and block this thread until it completes. if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(ConvertToSymbolicRegexNode, node, tryCreateFixedLengthMarker); } // Handle each node kind as-is appropriate. switch (node.Kind) { // Singletons and multis case RegexNodeKind.One: return _builder.CreateSingleton(CharSetSolver.Instance.CharConstraint(node.Ch, (node.Options & RegexOptions.IgnoreCase) != 0, _culture.Name)); case RegexNodeKind.Notone: return _builder.CreateSingleton(CharSetSolver.Instance.Not(CharSetSolver.Instance.CharConstraint(node.Ch, (node.Options & RegexOptions.IgnoreCase) != 0, _culture.Name))); case RegexNodeKind.Set: return ConvertSet(node); case RegexNodeKind.Multi: { // Create a BDD for each character in the string and concatenate them. string? str = node.Str; Debug.Assert(str is not null); bool ignoreCase = (node.Options & RegexOptions.IgnoreCase) != 0; var nodes = new SymbolicRegexNode<BDD>[str.Length]; for (int i = 0; i < nodes.Length; i++) { nodes[i] = _builder.CreateSingleton(CharSetSolver.Instance.CharConstraint(str[i], ignoreCase, _culture.Name)); } return _builder.CreateConcat(nodes, tryCreateFixedLengthMarker); } // Joins case RegexNodeKind.Concatenate: { var children = new SymbolicRegexNode<BDD>[node.ChildCount()]; for (int i = 0; i < children.Length; ++i) { children[i] = ConvertToSymbolicRegexNode(node.Child(i), tryCreateFixedLengthMarker: false); } return _builder.CreateConcat(children, tryCreateFixedLengthMarker); } case RegexNodeKind.Alternate: { // Alternations are created by creating an Or of all of its children. // This Or needs to be "ordered" to achieve the same semantics as the backtracking engines. var branches = new SymbolicRegexNode<BDD>[node.ChildCount()]; for (int i = 0; i < branches.Length; i++) { branches[i] = ConvertToSymbolicRegexNode(node.Child(i), tryCreateFixedLengthMarker); } return _builder.OrderedOr(branches); } // Loops case RegexNodeKind.Oneloop: case RegexNodeKind.Onelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notonelazy: { // Create a BDD that represents the character, then create a loop around it. bool ignoreCase = (node.Options & RegexOptions.IgnoreCase) != 0; BDD bdd = CharSetSolver.Instance.CharConstraint(node.Ch, ignoreCase, _culture.Name); if (node.IsNotoneFamily) { bdd = CharSetSolver.Instance.Not(bdd); } return _builder.CreateLoop(_builder.CreateSingleton(bdd), node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy, node.M, node.N); } case RegexNodeKind.Setloop: case RegexNodeKind.Setlazy: { // Create a BDD that represents the set string, then create a loop around it. string? set = node.Str; Debug.Assert(set is not null); BDD setBdd = CreateBDDFromSetString((node.Options & RegexOptions.IgnoreCase) != 0, set); return _builder.CreateLoop(_builder.CreateSingleton(setBdd), node.Kind == RegexNodeKind.Setlazy, node.M, node.N); } case RegexNodeKind.Loop: case RegexNodeKind.Lazyloop: return _builder.CreateLoop(ConvertToSymbolicRegexNode(node.Child(0), tryCreateFixedLengthMarker: false), node.Kind == RegexNodeKind.Lazyloop, node.M, node.N); // Other constructs case RegexNodeKind.Capture when node.N == -1: // N == -1 because balancing groups aren't supported int captureNum = RegexParser.MapCaptureNumber(node.M, _captureSparseMapping); return _builder.CreateCapture(ConvertToSymbolicRegexNode(node.Child(0), tryCreateFixedLengthMarker), captureNum); case RegexNodeKind.Empty: case RegexNodeKind.UpdateBumpalong: // UpdateBumpalong is a directive relevant only to backtracking and can be ignored just like Empty return _builder.Epsilon; case RegexNodeKind.Nothing: return _builder._nothing; // Anchors case RegexNodeKind.Beginning: return _builder.BeginningAnchor; case RegexNodeKind.Bol: EnsureNewlinePredicateInitialized(); return _builder.BolAnchor; case RegexNodeKind.End: // \z anchor return _builder.EndAnchor; case RegexNodeKind.EndZ: // \Z anchor EnsureNewlinePredicateInitialized(); return _builder.EndAnchorZ; case RegexNodeKind.Eol: EnsureNewlinePredicateInitialized(); return _builder.EolAnchor; case RegexNodeKind.Boundary: EnsureWordLetterPredicateInitialized(); return _builder.BoundaryAnchor; case RegexNodeKind.NonBoundary: EnsureWordLetterPredicateInitialized(); return _builder.NonBoundaryAnchor; // Experimental / unsupported #if DEBUG case RegexNodeKind.ExpressionConditional: // Try to extract the special case representing complement or intersection if (IsComplementedNode(node)) { return _builder.Not(ConvertToSymbolicRegexNode(node.Child(0), tryCreateFixedLengthMarker: false)); } if (TryGetIntersection(node, out List<RegexNode>? conjuncts)) { var nested = new SymbolicRegexNode<BDD>[conjuncts.Count]; for (int i = 0; i < nested.Length; i++) { nested[i] = ConvertToSymbolicRegexNode(conjuncts[i], tryCreateFixedLengthMarker: false); } return _builder.And(nested); } goto default; #endif default: throw new NotSupportedException(SR.Format(SR.NotSupported_NonBacktrackingConflictingExpression, node.Kind switch { RegexNodeKind.Atomic or RegexNodeKind.Setloopatomic or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic => SR.ExpressionDescription_AtomicSubexpressions, RegexNodeKind.Backreference => SR.ExpressionDescription_Backreference, RegexNodeKind.BackreferenceConditional => SR.ExpressionDescription_Conditional, RegexNodeKind.Capture => SR.ExpressionDescription_BalancingGroup, RegexNodeKind.ExpressionConditional => SR.ExpressionDescription_IfThenElse, RegexNodeKind.NegativeLookaround => SR.ExpressionDescription_NegativeLookaround, RegexNodeKind.PositiveLookaround => SR.ExpressionDescription_PositiveLookaround, RegexNodeKind.Start => SR.ExpressionDescription_ContiguousMatches, _ => UnexpectedNodeType(node) })); static string UnexpectedNodeType(RegexNode node) { // The default should never arise, since other node types are either supported // or have been removed (e.g. Group) from the final parse tree. string description = $"Unexpected ({nameof(RegexNodeKind)}: {node.Kind})"; Debug.Fail(description); return description; } } void EnsureNewlinePredicateInitialized() { // Update the \n predicate in the builder if it has not been updated already if (_builder._newLinePredicate.Equals(_builder._solver.False)) { _builder._newLinePredicate = _builder._solver.CharConstraint('\n'); } } void EnsureWordLetterPredicateInitialized() { // Update the word letter predicate based on the Unicode definition of it if it was not updated already if (_builder._wordLetterPredicateForAnchors.Equals(_builder._solver.False)) { // Use the predicate including joiner and non joiner _builder._wordLetterPredicateForAnchors = UnicodeCategoryConditions.WordLetterForAnchors; } } SymbolicRegexNode<BDD> ConvertSet(RegexNode node) { Debug.Assert(node.Kind == RegexNodeKind.Set); string? set = node.Str; Debug.Assert(set is not null); return _builder.CreateSingleton(CreateBDDFromSetString((node.Options & RegexOptions.IgnoreCase) != 0, set)); } #if DEBUG // TODO-NONBACKTRACKING: recognizing strictly only [] (RegexNode.Nothing), for example [0-[0]] would not be recognized bool IsNothing(RegexNode node) => node.Kind == RegexNodeKind.Nothing || (node.Kind == RegexNodeKind.Set && ConvertSet(node).IsNothing); bool IsDotStar(RegexNode node) => node.Kind == RegexNodeKind.Setloop && ConvertToSymbolicRegexNode(node, tryCreateFixedLengthMarker: false).IsAnyStar; bool IsIntersect(RegexNode node) => node.Kind == RegexNodeKind.ExpressionConditional && IsNothing(node.Child(2)); bool TryGetIntersection(RegexNode node, [Diagnostics.CodeAnalysis.NotNullWhen(true)] out List<RegexNode>? conjuncts) { if (!IsIntersect(node)) { conjuncts = null; return false; } conjuncts = new(); conjuncts.Add(node.Child(0)); node = node.Child(1); while (IsIntersect(node)) { conjuncts.Add(node.Child(0)); node = node.Child(1); } conjuncts.Add(node); return true; } bool IsComplementedNode(RegexNode node) => IsNothing(node.Child(1)) && IsDotStar(node.Child(2)); #endif } /// <summary>Creates a BDD from the <see cref="RegexCharClass"/> set string to determine whether a char is in the set.</summary> /// <param name="ignoreCase">true if the RegexOptions.IgnoreCase option is set; otherwise, false.</param> /// <param name="set">The RegexCharClass set string.</param> /// <returns>A BDD that, when queried with a char, answers whether that char is in the specified set.</returns> private BDD CreateBDDFromSetString(bool ignoreCase, string set) { // If we're too deep on the stack, continue any recursion on another thread. if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(CreateBDDFromSetString, ignoreCase, set); } // Lazily-initialize the set cache on first use, since some expressions may not have character classes in them. _setBddCache ??= new(); // Try to get the cached BDD for the combined ignoreCase+set key. // If one doesn't yet exist, compute and populate it. ref BDD? result = ref CollectionsMarshal.GetValueRefOrAddDefault(_setBddCache, (ignoreCase, set), out _); return result ??= Compute(ignoreCase, set); // <summary>Parses the RegexCharClass set string and creates a BDD that represents the same condition.</summary> BDD Compute(bool ignoreCase, string set) { List<BDD> conditions = new(); // The set string is composed of four parts: flags (which today are just for negation), ranges (a list // of pairs of values representing the ranges a character that matches the set could fall in (or if it's // negated, fall out of), categories (a list of codes based on UnicodeCategory values), and then optionally // another entire set string that's subtracted from the outer set string. We parse each of those pieces // to build up a BDD that will return true if a char matches the set string, and otherwise false. This // BDD then is functionally equivalent to RegexCharClass.CharInClass. bool negate = RegexCharClass.IsNegated(set); // Handle ranges // A BDD is created for each range, and is then negated if the set is negated. All of the BDDs for // all of the ranges are stored in a set of these "conditions", which will later have all of the BDDs // and'd (conjunction) together if the set is negated, or or'd (disjunction) together if not negated. List<(char First, char Last)>? ranges = RegexCharClass.ComputeRanges(set); if (ranges is not null) { foreach ((char first, char last) in ranges) { BDD bdd = CharSetSolver.Instance.RangeConstraint(first, last, ignoreCase, _culture.Name); if (negate) { bdd = CharSetSolver.Instance.Not(bdd); } conditions.Add(bdd); } } // Handle categories int setLength = set[RegexCharClass.SetLengthIndex]; int catLength = set[RegexCharClass.CategoryLengthIndex]; int catStart = setLength + RegexCharClass.SetStartIndex; int i = catStart; while (i < catStart + catLength) { // TODO: This logic should really be part of RegexCharClass, as it's parsing a set // string and ideally such logic would be internal to RegexCharClass. It could expose // a helper that returns the set of specified UnicodeCategory's and whether they're negated. // Singleton categories are stored as values whose code is 1 + the UnicodeCategory value. // Thus -1 is applied to extract the actual code of the category. The category itself may be // negated, e.g. \D instead of \d. short categoryCode = (short)set[i++]; if (categoryCode != 0) { // Create a BDD for the UnicodeCategory. If the category code is negative, the category // is negated, but the whole set string may also be negated, so we need to negate the condition // if one and only one of these negations occurs. BDD cond = MapCategoryCodeToCondition((UnicodeCategory)(Math.Abs(categoryCode) - 1)); if ((categoryCode < 0) ^ negate) { cond = CharSetSolver.Instance.Not(cond); } conditions.Add(cond); continue; } // Special case for a whole group G of categories surrounded by 0's. // Essentially 0 C1 C2 ... Cn 0 ==> G = (C1 | C2 | ... | Cn) categoryCode = (short)set[i++]; if (categoryCode == 0) { continue; // empty set of categories } // If the first catCode is negated, the group as a whole is negated bool negatedGroup = categoryCode < 0; // Collect individual category codes var categoryCodes = new HashSet<UnicodeCategory>(); while (categoryCode != 0) { categoryCodes.Add((UnicodeCategory)Math.Abs((int)categoryCode) - 1); categoryCode = (short)set[i++]; } // Create a BDD that represents all of the categories or'd (disjunction) together (C1 | C2 | ... | Cn), // then negate the result if necessary (noting that two negations cancel each other out... if the set // is negated but then the group itself is also negated). And add the resulting BDD to our set of conditions. BDD bdd = MapCategoryCodeSetToCondition(categoryCodes); if (negate ^ negatedGroup) { bdd = CharSetSolver.Instance.Not(bdd); } conditions.Add(bdd); } // Handle subtraction BDD? subtractorCond = null; if (set.Length > i) { // The set has a subtractor-set at the end. // All characters in the subtractor-set are excluded from the set. // Note that the subtractor sets may be nested, e.g. in r=[a-z-[b-g-[cd]]] // the subtractor set [b-g-[cd]] has itself a subtractor set [cd]. // Thus r is the set of characters between a..z except b,e,f,g subtractorCond = CreateBDDFromSetString(ignoreCase, set.Substring(i)); } // If there are no ranges and no groups then there are no conditions. // This situation arises in particular for RegexOptions.SingleLine with a . (dot), // which translates into a set string that accepts everything. BDD result = conditions.Count == 0 ? (negate ? CharSetSolver.Instance.False : CharSetSolver.Instance.True) : (negate ? CharSetSolver.Instance.And(conditions) : CharSetSolver.Instance.Or(conditions)); // Now apply the subtracted condition if there is one. As a subtly of Regex semantics, // the subtractor is not within the scope of the negation (if there is any negation). // Thus we subtract after applying any negation above rather than before. Subtraction // is achieved by negating the subtraction (such that the result of the negation represents // things still to be accepted after subtraction) and then and'ing it with the result, effectively // masking off anything matched by the subtraction set. if (subtractorCond is not null) { result = CharSetSolver.Instance.And(result, CharSetSolver.Instance.Not(subtractorCond)); } return result; // <summary>Creates a BDD that matches when a character is part of any of the specified UnicodeCategory values.</summary> BDD MapCategoryCodeSetToCondition(HashSet<UnicodeCategory> catCodes) { Debug.Assert(catCodes.Count > 0); // \w is so common, to help speed up construction we special-case it by using // the combined \w predicate rather than an or (disjunction) of the component categories. // This is done by validating that all of the categories for \w are there, and then removing // them all if they are and instead starting our BDD off as \w. BDD? result = null; if (catCodes.Contains(UnicodeCategory.UppercaseLetter) && catCodes.Contains(UnicodeCategory.LowercaseLetter) && catCodes.Contains(UnicodeCategory.TitlecaseLetter) && catCodes.Contains(UnicodeCategory.ModifierLetter) && catCodes.Contains(UnicodeCategory.OtherLetter) && catCodes.Contains(UnicodeCategory.NonSpacingMark) && catCodes.Contains(UnicodeCategory.DecimalDigitNumber) && catCodes.Contains(UnicodeCategory.ConnectorPunctuation)) { catCodes.Remove(UnicodeCategory.UppercaseLetter); catCodes.Remove(UnicodeCategory.LowercaseLetter); catCodes.Remove(UnicodeCategory.TitlecaseLetter); catCodes.Remove(UnicodeCategory.ModifierLetter); catCodes.Remove(UnicodeCategory.OtherLetter); catCodes.Remove(UnicodeCategory.NonSpacingMark); catCodes.Remove(UnicodeCategory.DecimalDigitNumber); catCodes.Remove(UnicodeCategory.ConnectorPunctuation); result = UnicodeCategoryConditions.WordLetter; } // For any remaining categories, create a condition for each and // or that into the resulting BDD. foreach (UnicodeCategory cat in catCodes) { BDD cond = MapCategoryCodeToCondition(cat); result = result is null ? cond : CharSetSolver.Instance.Or(result, cond); } Debug.Assert(result is not null); return result; } // Gets the BDD for evaluating whether a character is part of the specified category. BDD MapCategoryCodeToCondition(UnicodeCategory code) { Debug.Assert(Enum.IsDefined(code) || code == (UnicodeCategory)(RegexCharClass.SpaceConst - 1), $"Unknown category: {code}"); return code == (UnicodeCategory)(RegexCharClass.SpaceConst - 1) ? UnicodeCategoryConditions.WhiteSpace : UnicodeCategoryConditions.GetCategory(code); } } } } }
// 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; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text.RegularExpressions.Symbolic.Unicode; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Provides functionality to convert <see cref="RegexNode"/>s to corresponding <see cref="SymbolicRegexNode{S}"/>s.</summary> internal sealed class RegexNodeConverter { /// <summary>The culture to use for IgnoreCase comparisons.</summary> private readonly CultureInfo _culture; /// <summary>Capture information.</summary> private readonly Hashtable? _captureSparseMapping; /// <summary>The builder to use to create the <see cref="SymbolicRegexNode{S}"/> nodes.</summary> internal readonly SymbolicRegexBuilder<BDD> _builder; /// <summary>Cache of BDDs created to represent <see cref="RegexCharClass"/> set strings.</summary> /// <remarks>This cache is useful iff the same character class is used multiple times in the same regex, but that's fairly common.</remarks> private Dictionary<(bool IgnoreCase, string Set), BDD>? _setBddCache; /// <summary>Constructs a regex to symbolic finite automata converter</summary> public RegexNodeConverter(CultureInfo culture, Hashtable? captureSparseMapping) { _culture = culture; _captureSparseMapping = captureSparseMapping; _builder = new SymbolicRegexBuilder<BDD>(CharSetSolver.Instance); } /// <summary>Converts a <see cref="RegexNode"/> into its corresponding <see cref="SymbolicRegexNode{S}"/>.</summary> /// <param name="node">The node to convert.</param> /// <param name="tryCreateFixedLengthMarker">Whether we should attempt to create a fixed length marker after this node.</param> /// <returns>The generated <see cref="SymbolicRegexNode{S}"/> that corresponds to the supplied <paramref name="node"/>.</returns> public SymbolicRegexNode<BDD> ConvertToSymbolicRegexNode(RegexNode node, bool tryCreateFixedLengthMarker) { // We're processing the node tree recursively and need to avoid stack overflows for really deep trees. // To achieve this, if we detect we're too deep on the stack, we fork off the handling of this node // to another thread and block this thread until it completes. if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(ConvertToSymbolicRegexNode, node, tryCreateFixedLengthMarker); } // Handle each node kind as-is appropriate. switch (node.Kind) { // Singletons and multis case RegexNodeKind.One: return _builder.CreateSingleton(CharSetSolver.Instance.CharConstraint(node.Ch, (node.Options & RegexOptions.IgnoreCase) != 0, _culture.Name)); case RegexNodeKind.Notone: return _builder.CreateSingleton(CharSetSolver.Instance.Not(CharSetSolver.Instance.CharConstraint(node.Ch, (node.Options & RegexOptions.IgnoreCase) != 0, _culture.Name))); case RegexNodeKind.Set: return ConvertSet(node); case RegexNodeKind.Multi: { // Create a BDD for each character in the string and concatenate them. string? str = node.Str; Debug.Assert(str is not null); bool ignoreCase = (node.Options & RegexOptions.IgnoreCase) != 0; var nodes = new SymbolicRegexNode<BDD>[str.Length]; for (int i = 0; i < nodes.Length; i++) { nodes[i] = _builder.CreateSingleton(CharSetSolver.Instance.CharConstraint(str[i], ignoreCase, _culture.Name)); } return _builder.CreateConcat(nodes, tryCreateFixedLengthMarker); } // Joins case RegexNodeKind.Concatenate: { var children = new SymbolicRegexNode<BDD>[node.ChildCount()]; for (int i = 0; i < children.Length; ++i) { children[i] = ConvertToSymbolicRegexNode(node.Child(i), tryCreateFixedLengthMarker: false); } return _builder.CreateConcat(children, tryCreateFixedLengthMarker); } case RegexNodeKind.Alternate: { // Alternations are created by creating an Or of all of its children. // This Or needs to be "ordered" to achieve the same semantics as the backtracking engines. var branches = new SymbolicRegexNode<BDD>[node.ChildCount()]; for (int i = 0; i < branches.Length; i++) { branches[i] = ConvertToSymbolicRegexNode(node.Child(i), tryCreateFixedLengthMarker); } return _builder.OrderedOr(branches); } // Loops case RegexNodeKind.Oneloop: case RegexNodeKind.Onelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notonelazy: { // Create a BDD that represents the character, then create a loop around it. bool ignoreCase = (node.Options & RegexOptions.IgnoreCase) != 0; BDD bdd = CharSetSolver.Instance.CharConstraint(node.Ch, ignoreCase, _culture.Name); if (node.IsNotoneFamily) { bdd = CharSetSolver.Instance.Not(bdd); } return _builder.CreateLoop(_builder.CreateSingleton(bdd), node.Kind is RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy, node.M, node.N); } case RegexNodeKind.Setloop: case RegexNodeKind.Setlazy: { // Create a BDD that represents the set string, then create a loop around it. string? set = node.Str; Debug.Assert(set is not null); BDD setBdd = CreateBDDFromSetString((node.Options & RegexOptions.IgnoreCase) != 0, set); return _builder.CreateLoop(_builder.CreateSingleton(setBdd), node.Kind == RegexNodeKind.Setlazy, node.M, node.N); } case RegexNodeKind.Loop: case RegexNodeKind.Lazyloop: return _builder.CreateLoop(ConvertToSymbolicRegexNode(node.Child(0), tryCreateFixedLengthMarker: false), node.Kind == RegexNodeKind.Lazyloop, node.M, node.N); // Other constructs case RegexNodeKind.Capture when node.N == -1: // N == -1 because balancing groups aren't supported int captureNum = RegexParser.MapCaptureNumber(node.M, _captureSparseMapping); return _builder.CreateCapture(ConvertToSymbolicRegexNode(node.Child(0), tryCreateFixedLengthMarker), captureNum); case RegexNodeKind.Empty: case RegexNodeKind.UpdateBumpalong: // UpdateBumpalong is a directive relevant only to backtracking and can be ignored just like Empty return _builder.Epsilon; case RegexNodeKind.Nothing: return _builder._nothing; // Anchors case RegexNodeKind.Beginning: return _builder.BeginningAnchor; case RegexNodeKind.Bol: EnsureNewlinePredicateInitialized(); return _builder.BolAnchor; case RegexNodeKind.End: // \z anchor return _builder.EndAnchor; case RegexNodeKind.EndZ: // \Z anchor EnsureNewlinePredicateInitialized(); return _builder.EndAnchorZ; case RegexNodeKind.Eol: EnsureNewlinePredicateInitialized(); return _builder.EolAnchor; case RegexNodeKind.Boundary: EnsureWordLetterPredicateInitialized(); return _builder.BoundaryAnchor; case RegexNodeKind.NonBoundary: EnsureWordLetterPredicateInitialized(); return _builder.NonBoundaryAnchor; // Experimental / unsupported #if DEBUG case RegexNodeKind.ExpressionConditional: // Try to extract the special case representing complement or intersection if (IsComplementedNode(node)) { return _builder.Not(ConvertToSymbolicRegexNode(node.Child(0), tryCreateFixedLengthMarker: false)); } if (TryGetIntersection(node, out List<RegexNode>? conjuncts)) { var nested = new SymbolicRegexNode<BDD>[conjuncts.Count]; for (int i = 0; i < nested.Length; i++) { nested[i] = ConvertToSymbolicRegexNode(conjuncts[i], tryCreateFixedLengthMarker: false); } return _builder.And(nested); } goto default; #endif default: throw new NotSupportedException(SR.Format(SR.NotSupported_NonBacktrackingConflictingExpression, node.Kind switch { RegexNodeKind.Atomic or RegexNodeKind.Setloopatomic or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic => SR.ExpressionDescription_AtomicSubexpressions, RegexNodeKind.Backreference => SR.ExpressionDescription_Backreference, RegexNodeKind.BackreferenceConditional => SR.ExpressionDescription_Conditional, RegexNodeKind.Capture => SR.ExpressionDescription_BalancingGroup, RegexNodeKind.ExpressionConditional => SR.ExpressionDescription_IfThenElse, RegexNodeKind.NegativeLookaround => SR.ExpressionDescription_NegativeLookaround, RegexNodeKind.PositiveLookaround => SR.ExpressionDescription_PositiveLookaround, RegexNodeKind.Start => SR.ExpressionDescription_ContiguousMatches, _ => UnexpectedNodeType(node) })); static string UnexpectedNodeType(RegexNode node) { // The default should never arise, since other node types are either supported // or have been removed (e.g. Group) from the final parse tree. string description = $"Unexpected ({nameof(RegexNodeKind)}: {node.Kind})"; Debug.Fail(description); return description; } } void EnsureNewlinePredicateInitialized() { // Update the \n predicate in the builder if it has not been updated already if (_builder._newLinePredicate.Equals(_builder._solver.False)) { _builder._newLinePredicate = _builder._solver.CharConstraint('\n'); } } void EnsureWordLetterPredicateInitialized() { // Update the word letter predicate based on the Unicode definition of it if it was not updated already if (_builder._wordLetterPredicateForAnchors.Equals(_builder._solver.False)) { // Use the predicate including joiner and non joiner _builder._wordLetterPredicateForAnchors = UnicodeCategoryConditions.WordLetterForAnchors; } } SymbolicRegexNode<BDD> ConvertSet(RegexNode node) { Debug.Assert(node.Kind == RegexNodeKind.Set); string? set = node.Str; Debug.Assert(set is not null); return _builder.CreateSingleton(CreateBDDFromSetString((node.Options & RegexOptions.IgnoreCase) != 0, set)); } #if DEBUG // TODO-NONBACKTRACKING: recognizing strictly only [] (RegexNode.Nothing), for example [0-[0]] would not be recognized bool IsNothing(RegexNode node) => node.Kind == RegexNodeKind.Nothing || (node.Kind == RegexNodeKind.Set && ConvertSet(node).IsNothing); bool IsDotStar(RegexNode node) => node.Kind == RegexNodeKind.Setloop && ConvertToSymbolicRegexNode(node, tryCreateFixedLengthMarker: false).IsAnyStar; bool IsIntersect(RegexNode node) => node.Kind == RegexNodeKind.ExpressionConditional && IsNothing(node.Child(2)); bool TryGetIntersection(RegexNode node, [Diagnostics.CodeAnalysis.NotNullWhen(true)] out List<RegexNode>? conjuncts) { if (!IsIntersect(node)) { conjuncts = null; return false; } conjuncts = new(); conjuncts.Add(node.Child(0)); node = node.Child(1); while (IsIntersect(node)) { conjuncts.Add(node.Child(0)); node = node.Child(1); } conjuncts.Add(node); return true; } bool IsComplementedNode(RegexNode node) => IsNothing(node.Child(1)) && IsDotStar(node.Child(2)); #endif } /// <summary>Creates a BDD from the <see cref="RegexCharClass"/> set string to determine whether a char is in the set.</summary> /// <param name="ignoreCase">true if the RegexOptions.IgnoreCase option is set; otherwise, false.</param> /// <param name="set">The RegexCharClass set string.</param> /// <returns>A BDD that, when queried with a char, answers whether that char is in the specified set.</returns> private BDD CreateBDDFromSetString(bool ignoreCase, string set) { // If we're too deep on the stack, continue any recursion on another thread. if (!StackHelper.TryEnsureSufficientExecutionStack()) { return StackHelper.CallOnEmptyStack(CreateBDDFromSetString, ignoreCase, set); } // Lazily-initialize the set cache on first use, since some expressions may not have character classes in them. _setBddCache ??= new(); // Try to get the cached BDD for the combined ignoreCase+set key. // If one doesn't yet exist, compute and populate it. ref BDD? result = ref CollectionsMarshal.GetValueRefOrAddDefault(_setBddCache, (ignoreCase, set), out _); return result ??= Compute(ignoreCase, set); // <summary>Parses the RegexCharClass set string and creates a BDD that represents the same condition.</summary> BDD Compute(bool ignoreCase, string set) { List<BDD> conditions = new(); // The set string is composed of four parts: flags (which today are just for negation), ranges (a list // of pairs of values representing the ranges a character that matches the set could fall in (or if it's // negated, fall out of), categories (a list of codes based on UnicodeCategory values), and then optionally // another entire set string that's subtracted from the outer set string. We parse each of those pieces // to build up a BDD that will return true if a char matches the set string, and otherwise false. This // BDD then is functionally equivalent to RegexCharClass.CharInClass. bool negate = RegexCharClass.IsNegated(set); // Handle ranges // A BDD is created for each range, and is then negated if the set is negated. All of the BDDs for // all of the ranges are stored in a set of these "conditions", which will later have all of the BDDs // and'd (conjunction) together if the set is negated, or or'd (disjunction) together if not negated. List<(char First, char Last)>? ranges = RegexCharClass.ComputeRanges(set); if (ranges is not null) { foreach ((char first, char last) in ranges) { BDD bdd = CharSetSolver.Instance.RangeConstraint(first, last, ignoreCase, _culture.Name); if (negate) { bdd = CharSetSolver.Instance.Not(bdd); } conditions.Add(bdd); } } // Handle categories int setLength = set[RegexCharClass.SetLengthIndex]; int catLength = set[RegexCharClass.CategoryLengthIndex]; int catStart = setLength + RegexCharClass.SetStartIndex; int i = catStart; while (i < catStart + catLength) { // TODO: This logic should really be part of RegexCharClass, as it's parsing a set // string and ideally such logic would be internal to RegexCharClass. It could expose // a helper that returns the set of specified UnicodeCategory's and whether they're negated. // Singleton categories are stored as values whose code is 1 + the UnicodeCategory value. // Thus -1 is applied to extract the actual code of the category. The category itself may be // negated, e.g. \D instead of \d. short categoryCode = (short)set[i++]; if (categoryCode != 0) { // Create a BDD for the UnicodeCategory. If the category code is negative, the category // is negated, but the whole set string may also be negated, so we need to negate the condition // if one and only one of these negations occurs. BDD cond = MapCategoryCodeToCondition((UnicodeCategory)(Math.Abs(categoryCode) - 1)); if ((categoryCode < 0) ^ negate) { cond = CharSetSolver.Instance.Not(cond); } conditions.Add(cond); continue; } // Special case for a whole group G of categories surrounded by 0's. // Essentially 0 C1 C2 ... Cn 0 ==> G = (C1 | C2 | ... | Cn) categoryCode = (short)set[i++]; if (categoryCode == 0) { continue; // empty set of categories } // If the first catCode is negated, the group as a whole is negated bool negatedGroup = categoryCode < 0; // Collect individual category codes var categoryCodes = new HashSet<UnicodeCategory>(); while (categoryCode != 0) { categoryCodes.Add((UnicodeCategory)Math.Abs((int)categoryCode) - 1); categoryCode = (short)set[i++]; } // Create a BDD that represents all of the categories or'd (disjunction) together (C1 | C2 | ... | Cn), // then negate the result if necessary (noting that two negations cancel each other out... if the set // is negated but then the group itself is also negated). And add the resulting BDD to our set of conditions. BDD bdd = MapCategoryCodeSetToCondition(categoryCodes); if (negate ^ negatedGroup) { bdd = CharSetSolver.Instance.Not(bdd); } conditions.Add(bdd); } // Handle subtraction BDD? subtractorCond = null; if (set.Length > i) { // The set has a subtractor-set at the end. // All characters in the subtractor-set are excluded from the set. // Note that the subtractor sets may be nested, e.g. in r=[a-z-[b-g-[cd]]] // the subtractor set [b-g-[cd]] has itself a subtractor set [cd]. // Thus r is the set of characters between a..z except b,e,f,g subtractorCond = CreateBDDFromSetString(ignoreCase, set.Substring(i)); } // If there are no ranges and no groups then there are no conditions. // This situation arises in particular for RegexOptions.SingleLine with a . (dot), // which translates into a set string that accepts everything. BDD result = conditions.Count == 0 ? (negate ? CharSetSolver.Instance.False : CharSetSolver.Instance.True) : (negate ? CharSetSolver.Instance.And(CollectionsMarshal.AsSpan(conditions)) : CharSetSolver.Instance.Or(CollectionsMarshal.AsSpan(conditions))); // Now apply the subtracted condition if there is one. As a subtly of Regex semantics, // the subtractor is not within the scope of the negation (if there is any negation). // Thus we subtract after applying any negation above rather than before. Subtraction // is achieved by negating the subtraction (such that the result of the negation represents // things still to be accepted after subtraction) and then and'ing it with the result, effectively // masking off anything matched by the subtraction set. if (subtractorCond is not null) { result = CharSetSolver.Instance.And(result, CharSetSolver.Instance.Not(subtractorCond)); } return result; // <summary>Creates a BDD that matches when a character is part of any of the specified UnicodeCategory values.</summary> BDD MapCategoryCodeSetToCondition(HashSet<UnicodeCategory> catCodes) { Debug.Assert(catCodes.Count > 0); // \w is so common, to help speed up construction we special-case it by using // the combined \w predicate rather than an or (disjunction) of the component categories. // This is done by validating that all of the categories for \w are there, and then removing // them all if they are and instead starting our BDD off as \w. BDD? result = null; if (catCodes.Contains(UnicodeCategory.UppercaseLetter) && catCodes.Contains(UnicodeCategory.LowercaseLetter) && catCodes.Contains(UnicodeCategory.TitlecaseLetter) && catCodes.Contains(UnicodeCategory.ModifierLetter) && catCodes.Contains(UnicodeCategory.OtherLetter) && catCodes.Contains(UnicodeCategory.NonSpacingMark) && catCodes.Contains(UnicodeCategory.DecimalDigitNumber) && catCodes.Contains(UnicodeCategory.ConnectorPunctuation)) { catCodes.Remove(UnicodeCategory.UppercaseLetter); catCodes.Remove(UnicodeCategory.LowercaseLetter); catCodes.Remove(UnicodeCategory.TitlecaseLetter); catCodes.Remove(UnicodeCategory.ModifierLetter); catCodes.Remove(UnicodeCategory.OtherLetter); catCodes.Remove(UnicodeCategory.NonSpacingMark); catCodes.Remove(UnicodeCategory.DecimalDigitNumber); catCodes.Remove(UnicodeCategory.ConnectorPunctuation); result = UnicodeCategoryConditions.WordLetter; } // For any remaining categories, create a condition for each and // or that into the resulting BDD. foreach (UnicodeCategory cat in catCodes) { BDD cond = MapCategoryCodeToCondition(cat); result = result is null ? cond : CharSetSolver.Instance.Or(result, cond); } Debug.Assert(result is not null); return result; } // Gets the BDD for evaluating whether a character is part of the specified category. BDD MapCategoryCodeToCondition(UnicodeCategory code) { Debug.Assert(Enum.IsDefined(code) || code == (UnicodeCategory)(RegexCharClass.SpaceConst - 1), $"Unknown category: {code}"); return code == (UnicodeCategory)(RegexCharClass.SpaceConst - 1) ? UnicodeCategoryConditions.WhiteSpace : UnicodeCategoryConditions.GetCategory(code); } } } } }
1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexMatcher.cs
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents a regex matching engine that performs regex matching using symbolic derivatives.</summary> internal abstract class SymbolicRegexMatcher { #if DEBUG /// <summary>Unwind the regex of the matcher and save the resulting state graph in DGML</summary> /// <param name="bound">roughly the maximum number of states, 0 means no bound</param> /// <param name="hideStateInfo">if true then hide state info</param> /// <param name="addDotStar">if true then pretend that there is a .* at the beginning</param> /// <param name="inReverse">if true then unwind the regex backwards (addDotStar is then ignored)</param> /// <param name="onlyDFAinfo">if true then compute and save only genral DFA info</param> /// <param name="writer">dgml output is written here</param> /// <param name="maxLabelLength">maximum length of labels in nodes anything over that length is indicated with .. </param> /// <param name="asNFA">if true creates NFA instead of DFA</param> public abstract void SaveDGML(TextWriter writer, int bound, bool hideStateInfo, bool addDotStar, bool inReverse, bool onlyDFAinfo, int maxLabelLength, bool asNFA); /// <summary> /// Generates up to k random strings matched by the regex /// </summary> /// <param name="k">upper bound on the number of generated strings</param> /// <param name="randomseed">random seed for the generator, 0 means no random seed</param> /// <param name="negative">if true then generate inputs that do not match</param> /// <returns></returns> public abstract IEnumerable<string> GenerateRandomMembers(int k, int randomseed, bool negative); #endif } /// <summary>Represents a regex matching engine that performs regex matching using symbolic derivatives.</summary> /// <typeparam name="TSetType">Character set type.</typeparam> internal sealed class SymbolicRegexMatcher<TSetType> : SymbolicRegexMatcher where TSetType : notnull { /// <summary>Maximum number of built states before switching over to NFA mode.</summary> /// <remarks> /// By default, all matching starts out using DFAs, where every state transitions to one and only one /// state for any minterm (each character maps to one minterm). Some regular expressions, however, can result /// in really, really large DFA state graphs, much too big to actually store. Instead of failing when we /// encounter such state graphs, at some point we instead switch from processing as a DFA to processing as /// an NFA. As an NFA, we instead track all of the states we're in at any given point, and transitioning /// from one "state" to the next really means for every constituent state that composes our current "state", /// we find all possible states that transitioning out of each of them could result in, and the union of /// all of those is our new "state". This constant represents the size of the graph after which we start /// processing as an NFA instead of as a DFA. This processing doesn't change immediately, however. All /// processing starts out in DFA mode, even if we've previously triggered NFA mode for the same regex. /// We switch over into NFA mode the first time a given traversal (match operation) results in us needing /// to create a new node and the graph is already or newly beyond this threshold. /// </remarks> internal const int NfaThreshold = 10_000; /// <summary>Sentinel value used internally by the matcher to indicate no match exists.</summary> private const int NoMatchExists = -2; /// <summary>Builder used to create <see cref="SymbolicRegexNode{S}"/>s while matching.</summary> /// <remarks> /// The builder is used to build up the DFA state space lazily, which means we need to be able to /// produce new <see cref="SymbolicRegexNode{S}"/>s as we match. Once in NFA mode, we also use /// the builder to produce new NFA states. The builder maintains a cache of all DFA and NFA states. /// </remarks> internal readonly SymbolicRegexBuilder<TSetType> _builder; /// <summary>Maps every character to its corresponding minterm ID.</summary> private readonly MintermClassifier _mintermClassifier; /// <summary><see cref="_pattern"/> prefixed with [0-0xFFFF]*</summary> /// <remarks> /// The matching engine first uses <see cref="_dotStarredPattern"/> to find whether there is a match /// and where that match might end. Prepending the .* prefix onto the original pattern provides the DFA /// with the ability to continue to process input characters even if those characters aren't part of /// the match. If Regex.IsMatch is used, nothing further is needed beyond this prefixed pattern. If, however, /// other matching operations are performed that require knowing the exact start and end of the match, /// the engine then needs to process the pattern in reverse to find where the match actually started; /// for that, it uses the <see cref="_reversePattern"/> and walks backwards through the input characters /// from where <see cref="_dotStarredPattern"/> left off. At this point we know that there was a match, /// where it started, and where it could have ended, but that ending point could be influenced by the /// selection of the starting point. So, to find the actual ending point, the original <see cref="_pattern"/> /// is then used from that starting point to walk forward through the input characters again to find the /// actual end point used for the match. /// </remarks> internal readonly SymbolicRegexNode<TSetType> _dotStarredPattern; /// <summary>The original regex pattern.</summary> internal readonly SymbolicRegexNode<TSetType> _pattern; /// <summary>The reverse of <see cref="_pattern"/>.</summary> /// <remarks> /// Determining that there is a match and where the match ends requires only <see cref="_pattern"/>. /// But from there determining where the match began requires reversing the pattern and running /// the matcher again, starting from the ending position. This <see cref="_reversePattern"/> caches /// that reversed pattern used for extracting match start. /// </remarks> internal readonly SymbolicRegexNode<TSetType> _reversePattern; /// <summary>true iff timeout checking is enabled.</summary> private readonly bool _checkTimeout; /// <summary>Timeout in milliseconds. This is only used if <see cref="_checkTimeout"/> is true.</summary> private readonly int _timeout; /// <summary>Data and routines for skipping ahead to the next place a match could potentially start.</summary> private readonly RegexFindOptimizations? _findOpts; /// <summary>The initial states for the original pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _initialStates; /// <summary>The initial states for the dot-star pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _dotstarredInitialStates; /// <summary>The initial states for the reverse pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _reverseInitialStates; /// <summary>Lookup table to quickly determine the character kind for ASCII characters.</summary> /// <remarks>Non-null iff the pattern contains anchors; otherwise, it's unused.</remarks> private readonly uint[]? _asciiCharKinds; /// <summary>Number of capture groups.</summary> private readonly int _capsize; /// <summary>Fixed-length of any possible match.</summary> /// <remarks>This will be null if matches may be of varying lengths or if a fixed-length couldn't otherwise be computed.</remarks> private readonly int? _fixedMatchLength; /// <summary>Gets whether the regular expression contains captures (beyond the implicit root-level capture).</summary> /// <remarks>This determines whether the matcher uses the special capturing NFA simulation mode.</remarks> internal bool HasSubcaptures => _capsize > 1; /// <summary>Get the minterm of <paramref name="c"/>.</summary> /// <param name="c">character code</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private TSetType GetMinterm(int c) { Debug.Assert(_builder._minterms is not null); return _builder._minterms[_mintermClassifier.GetMintermID(c)]; } /// <summary>Constructs matcher for given symbolic regex.</summary> internal SymbolicRegexMatcher(SymbolicRegexNode<TSetType> sr, RegexTree regexTree, BDD[] minterms, TimeSpan matchTimeout) { Debug.Assert(sr._builder._solver is BV64Algebra or BVAlgebra or CharSetSolver, $"Unsupported algebra: {sr._builder._solver}"); _pattern = sr; _builder = sr._builder; _checkTimeout = Regex.InfiniteMatchTimeout != matchTimeout; _timeout = (int)(matchTimeout.TotalMilliseconds + 0.5); // Round up, so it will be at least 1ms _mintermClassifier = _builder._solver switch { BV64Algebra bv64 => bv64._classifier, BVAlgebra bv => bv._classifier, _ => new MintermClassifier((CharSetSolver)(object)_builder._solver, minterms), }; _capsize = regexTree.CaptureCount; if (regexTree.FindOptimizations.MinRequiredLength == regexTree.FindOptimizations.MaxPossibleLength) { _fixedMatchLength = regexTree.FindOptimizations.MinRequiredLength; } if (regexTree.FindOptimizations.FindMode != FindNextStartingPositionMode.NoSearch && regexTree.FindOptimizations.LeadingAnchor == 0) // If there are any anchors, we're better off letting the DFA quickly do its job of determining whether there's a match. { _findOpts = regexTree.FindOptimizations; } // Determine the number of initial states. If there's no anchor, only the default previous // character kind 0 is ever going to be used for all initial states. int statesCount = _pattern._info.ContainsSomeAnchor ? CharKind.CharKindCount : 1; // Create the initial states for the original pattern. var initialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < initialStates.Length; i++) { initialStates[i] = _builder.CreateState(_pattern, i, capturing: HasSubcaptures); } _initialStates = initialStates; // Create the dot-star pattern (a concatenation of any* with the original pattern) // and all of its initial states. SymbolicRegexNode<TSetType> unorderedPattern = _pattern.IgnoreOrOrderAndLazyness(); _dotStarredPattern = _builder.CreateConcat(_builder._anyStar, unorderedPattern); var dotstarredInitialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < dotstarredInitialStates.Length; i++) { // Used to detect if initial state was reentered, // but observe that the behavior from the state may ultimately depend on the previous // input char e.g. possibly causing nullability of \b or \B or of a start-of-line anchor, // in that sense there can be several "versions" (not more than StateCount) of the initial state. DfaMatchingState<TSetType> state = _builder.CreateState(_dotStarredPattern, i, capturing: false); state.IsInitialState = true; dotstarredInitialStates[i] = state; } _dotstarredInitialStates = dotstarredInitialStates; // Create the reverse pattern (the original pattern in reverse order) and all of its // initial states. _reversePattern = unorderedPattern.Reverse(); var reverseInitialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < reverseInitialStates.Length; i++) { reverseInitialStates[i] = _builder.CreateState(_reversePattern, i, capturing: false); } _reverseInitialStates = reverseInitialStates; // Initialize our fast-lookup for determining the character kind of ASCII characters. // This is only required when the pattern contains anchors, as otherwise there's only // ever a single kind used. if (_pattern._info.ContainsSomeAnchor) { var asciiCharKinds = new uint[128]; for (int i = 0; i < asciiCharKinds.Length; i++) { TSetType predicate2; uint charKind; if (i == '\n') { predicate2 = _builder._newLinePredicate; charKind = CharKind.Newline; } else { predicate2 = _builder._wordLetterPredicateForAnchors; charKind = CharKind.WordLetter; } asciiCharKinds[i] = _builder._solver.And(GetMinterm(i), predicate2).Equals(_builder._solver.False) ? 0 : charKind; } _asciiCharKinds = asciiCharKinds; } } /// <summary> /// Create a PerThreadData with the appropriate parts initialized for this matcher's pattern. /// </summary> internal PerThreadData CreatePerThreadData() => new PerThreadData(_builder, _capsize); /// <summary>Compute the target state for the source state and input[i] character and transition to it.</summary> /// <param name="builder">The associated builder.</param> /// <param name="input">The input text.</param> /// <param name="i">The index into <paramref name="input"/> at which the target character lives.</param> /// <param name="state">The current state being transitioned from. Upon return it's the new state if the transition succeeded.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryTakeTransition<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, int i, ref CurrentState state) where TStateHandler : struct, IStateHandler { int c = input[i]; int mintermId = c == '\n' && i == input.Length - 1 && TStateHandler.StartsWithLineAnchor(ref state) ? builder._minterms!.Length : // mintermId = minterms.Length represents \Z (last \n) _mintermClassifier.GetMintermID(c); return TStateHandler.TakeTransition(builder, ref state, mintermId); } private List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)> CreateNewCapturingTransitions(DfaMatchingState<TSetType> state, TSetType minterm, int offset) { Debug.Assert(_builder._capturingDelta is not null); lock (this) { // Get the next state if it exists. The caller should have already tried and found it null (not yet created), // but in the interim another thread could have created it. List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)>? p = _builder._capturingDelta[offset]; if (p is null) { // Build the new state and store it into the array. p = state.NfaEagerNextWithEffects(minterm); Volatile.Write(ref _builder._capturingDelta[offset], p); } return p; } } private void DoCheckTimeout(int timeoutOccursAt) { // This logic is identical to RegexRunner.DoCheckTimeout, with the exception of check skipping. RegexRunner calls // DoCheckTimeout potentially on every iteration of a loop, whereas this calls it only once per transition. int currentMillis = Environment.TickCount; if (currentMillis >= timeoutOccursAt && (0 <= timeoutOccursAt || 0 >= currentMillis)) { throw new RegexMatchTimeoutException(string.Empty, string.Empty, TimeSpan.FromMilliseconds(_timeout)); } } /// <summary>Find a match.</summary> /// <param name="isMatch">Whether to return once we know there's a match without determining where exactly it matched.</param> /// <param name="input">The input span</param> /// <param name="startat">The position to start search in the input span.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan<char> input, int startat, PerThreadData perThreadData) { Debug.Assert(startat >= 0 && startat <= input.Length, $"{nameof(startat)} == {startat}, {nameof(input.Length)} == {input.Length}"); Debug.Assert(perThreadData is not null); // If we need to perform timeout checks, store the absolute timeout value. int timeoutOccursAt = 0; if (_checkTimeout) { // Using Environment.TickCount for efficiency instead of Stopwatch -- as in the non-DFA case. timeoutOccursAt = Environment.TickCount + (int)(_timeout + 0.5); } // If we're starting at the end of the input, we don't need to do any work other than // determine whether an empty match is valid, i.e. whether the pattern is "nullable" // given the kinds of characters at and just before the end. if (startat == input.Length) { // TODO https://github.com/dotnet/runtime/issues/65606: Handle capture groups. uint prevKind = GetCharKind(input, startat - 1); uint nextKind = GetCharKind(input, startat); return _pattern.IsNullableFor(CharKind.Context(prevKind, nextKind)) ? new SymbolicMatch(startat, 0) : SymbolicMatch.NoMatch; } // Phase 1: // Determine whether there is a match by finding the first final state position. This only tells // us whether there is a match but needn't give us the longest possible match. This may return -1 as // a legitimate value when the initial state is nullable and startat == 0. It returns NoMatchExists (-2) // when there is no match. As an example, consider the pattern a{5,10}b* run against an input // of aaaaaaaaaaaaaaabbbc: phase 1 will find the position of the first b: aaaaaaaaaaaaaaab. int i = FindFinalStatePosition(input, startat, timeoutOccursAt, out int matchStartLowBoundary, out int matchStartLengthMarker, perThreadData); // If there wasn't a match, we're done. if (i == NoMatchExists) { return SymbolicMatch.NoMatch; } // A match exists. If we don't need further details, because IsMatch was used (and thus we don't // need the exact bounds of the match, captures, etc.), we're done. if (isMatch) { return SymbolicMatch.QuickMatch; } // Phase 2: // Match backwards through the input matching against the reverse of the pattern, looking for the earliest // start position. That tells us the actual starting position of the match. We can skip this phase if we // recorded a fixed-length marker for the portion of the pattern that matched, as we can then jump that // exact number of positions backwards. Continuing the previous example, phase 2 will walk backwards from // that first b until it finds the 6th a: aaaaaaaaaab. int matchStart; if (matchStartLengthMarker >= 0) { matchStart = i - matchStartLengthMarker + 1; } else { Debug.Assert(i >= startat - 1); matchStart = i < startat ? startat : FindStartPosition(input, i, matchStartLowBoundary, perThreadData); } // Phase 3: // Match again, this time from the computed start position, to find the latest end position. That start // and end then represent the bounds of the match. If the pattern has subcaptures (captures other than // the top-level capture for the whole match), we need to do more work to compute their exact bounds, so we // take a faster path if captures aren't required. Further, if captures aren't needed, and if any possible // match of the whole pattern is a fixed length, we can skip this phase as well, just using that fixed-length // to compute the ending position based on the starting position. Continuing the previous example, phase 3 // will walk forwards from the 6th a until it finds the end of the match: aaaaaaaaaabbb. if (!HasSubcaptures) { if (_fixedMatchLength.HasValue) { return new SymbolicMatch(matchStart, _fixedMatchLength.GetValueOrDefault()); } int matchEnd = FindEndPosition(input, matchStart, perThreadData); return new SymbolicMatch(matchStart, matchEnd + 1 - matchStart); } else { int matchEnd = FindEndPositionCapturing(input, matchStart, out Registers endRegisters, perThreadData); return new SymbolicMatch(matchStart, matchEnd + 1 - matchStart, endRegisters.CaptureStarts, endRegisters.CaptureEnds); } } /// <summary>Phase 3 of matching. From a found starting position, find the ending position of the match using the original pattern.</summary> /// <remarks> /// The ending position is known to exist; this function just needs to determine exactly what it is. /// We need to find the longest possible match and thus the latest valid ending position. /// </remarks> /// <param name="input">The input text.</param> /// <param name="i">The starting position of the match.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The found ending position of the match.</returns> private int FindEndPosition(ReadOnlySpan<char> input, int i, PerThreadData perThreadData) { // Get the starting state based on the current context. DfaMatchingState<TSetType> dfaStartState = _initialStates[GetCharKind(input, i - 1)]; // If the starting state is nullable (accepts the empty string), then it's a valid // match and we need to record the position as a possible end, but keep going looking // for a better one. int end = input.Length; // invalid sentinel value if (dfaStartState.IsNullable(GetCharKind(input, i))) { // Empty match exists because the initial state is accepting. end = i - 1; } if ((uint)i < (uint)input.Length) { // Iterate from the starting state until we've found the best ending state. SymbolicRegexBuilder<TSetType> builder = dfaStartState.Node._builder; var currentState = new CurrentState(dfaStartState); while (true) { // Run the DFA or NFA traversal backwards from the current point using the current state. bool done = currentState.NfaState is not null ? FindEndPositionDeltas<NfaStateHandler>(builder, input, ref i, ref currentState, ref end) : FindEndPositionDeltas<DfaStateHandler>(builder, input, ref i, ref currentState, ref end); // If we successfully found the ending position, we're done. if (done || (uint)i >= (uint)input.Length) { break; } // We exited out of the inner processing loop, but we didn't hit a dead end or run out // of input, and that should only happen if we failed to transition from one state to // the next, which should only happen if we were in DFA mode and we tried to create // a new state and exceeded the graph size. Upgrade to NFA mode and continue; Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } } // Return the found ending position. Debug.Assert(end < input.Length, "Expected to find an ending position but didn't"); return end; } /// <summary> /// Workhorse inner loop for <see cref="FindEndPosition"/>. Consumes the <paramref name="input"/> character by character, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> private bool FindEndPositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, ref CurrentState currentState, ref int endingIndex) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Repeatedly read the next character from the input and use it to transition the current state to the next. // We're looking for the furthest final state we can find. while ((uint)pos < (uint)input.Length && TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos + 1))) { // If the new state accepts the empty string, we found an ending state. Record the position. endingIndex = pos; } else if (TStateHandler.IsDeadend(ref state)) { // If the new state is a dead end, the match ended the last time endingIndex was updated. currentState = state; i = pos; return true; } // We successfully transitioned to the next state and consumed the current character, // so move along to the next. pos++; } // We either ran out of input, in which case we successfully recorded an ending index, // or we failed to transition to the next state due to the graph becoming too large. currentState = state; i = pos; return false; } /// <summary>Find match end position using the original pattern, end position is known to exist. This version also produces captures.</summary> /// <param name="input">input span</param> /// <param name="i">inclusive start position</param> /// <param name="resultRegisters">out parameter for the final register values, which indicate capture starts and ends</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>the match end position</returns> private int FindEndPositionCapturing(ReadOnlySpan<char> input, int i, out Registers resultRegisters, PerThreadData perThreadData) { int i_end = input.Length; Registers endRegisters = default; DfaMatchingState<TSetType>? endState = null; // Pick the correct start state based on previous character kind. DfaMatchingState<TSetType> initialState = _initialStates[GetCharKind(input, i - 1)]; Registers initialRegisters = perThreadData.InitialRegisters; // Initialize registers with -1, which means "not seen yet" Array.Fill(initialRegisters.CaptureStarts, -1); Array.Fill(initialRegisters.CaptureEnds, -1); if (initialState.IsNullable(GetCharKind(input, i))) { // Empty match exists because the initial state is accepting. i_end = i - 1; endRegisters.Assign(initialRegisters); endState = initialState; } // Use two maps from state IDs to register values for the current and next set of states. // Note that these maps use insertion order, which is used to maintain priorities between states in a way // that matches the order the backtracking engines visit paths. Debug.Assert(perThreadData.Current is not null && perThreadData.Next is not null); SparseIntMap<Registers> current = perThreadData.Current, next = perThreadData.Next; current.Clear(); next.Clear(); current.Add(initialState.Id, initialRegisters); SymbolicRegexBuilder<TSetType> builder = _builder; while ((uint)i < (uint)input.Length) { Debug.Assert(next.Count == 0); int c = input[i]; int normalMintermId = _mintermClassifier.GetMintermID(c); foreach ((int sourceId, Registers sourceRegisters) in current.Values) { Debug.Assert(builder._capturingStateArray is not null); DfaMatchingState<TSetType> sourceState = builder._capturingStateArray[sourceId]; // Find the minterm, handling the special case for the last \n int mintermId = c == '\n' && i == input.Length - 1 && sourceState.StartsWithLineAnchor ? builder._minterms!.Length : normalMintermId; // mintermId = minterms.Length represents \Z (last \n) TSetType minterm = builder.GetMinterm(mintermId); // Get or create the transitions int offset = (sourceId << builder._mintermsLog) | mintermId; Debug.Assert(builder._capturingDelta is not null); List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)>? transitions = builder._capturingDelta[offset] ?? CreateNewCapturingTransitions(sourceState, minterm, offset); // Take the transitions in their prioritized order for (int j = 0; j < transitions.Count; ++j) { (DfaMatchingState<TSetType> targetState, List<DerivativeEffect> effects) = transitions[j]; if (targetState.IsDeadend) continue; // Try to add the state and handle the case where it didn't exist before. If the state already // exists, then the transition can be safely ignored, as the existing state was generated by a // higher priority transition. if (next.Add(targetState.Id, out int index)) { // Avoid copying the registers on the last transition from this state, reusing the registers instead Registers newRegisters = j != transitions.Count - 1 ? sourceRegisters.Clone() : sourceRegisters; newRegisters.ApplyEffects(effects, i); next.Update(index, targetState.Id, newRegisters); if (targetState.IsNullable(GetCharKind(input, i + 1))) { // Accepting state has been reached. Record the position. i_end = i; endRegisters.Assign(newRegisters); endState = targetState; // No lower priority transitions from this or other source states are taken because the // backtracking engines would return the match ending here. goto BreakNullable; } } } } BreakNullable: if (next.Count == 0) { // If all states died out some nullable state must have been seen before break; } // Swap the state sets and prepare for the next character SparseIntMap<Registers> tmp = current; current = next; next = tmp; next.Clear(); i++; } Debug.Assert(i_end != input.Length && endState is not null); // Apply effects for finishing at the stored end state endState.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i_end + 1), CharKind.Context(endState.PrevCharKind, GetCharKind(input, i_end + 1))); resultRegisters = endRegisters; return i_end; } /// <summary> /// Phase 2 of matching. From a found ending position, walk in reverse through the input using the reverse pattern to find the /// start position of match. /// </summary> /// <remarks> /// The start position is known to exist; this function just needs to determine exactly what it is. /// We need to find the earliest (lowest index) starting position that's not earlier than <paramref name="matchStartBoundary"/>. /// </remarks> /// <param name="input">The input text.</param> /// <param name="i">The ending position to walk backwards from. <paramref name="i"/> points at the last character of the match.</param> /// <param name="matchStartBoundary">The initial starting location discovered in phase 1, a point we must not walk earlier than.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The found starting position for the match.</returns> private int FindStartPosition(ReadOnlySpan<char> input, int i, int matchStartBoundary, PerThreadData perThreadData) { Debug.Assert(i >= 0, $"{nameof(i)} == {i}"); Debug.Assert(matchStartBoundary >= 0 && matchStartBoundary < input.Length, $"{nameof(matchStartBoundary)} == {matchStartBoundary}"); Debug.Assert(i >= matchStartBoundary, $"Expected {i} >= {matchStartBoundary}."); // Get the starting state for the reverse pattern. This depends on previous character (which, because we're // going backwards, is character number i + 1). var currentState = new CurrentState(_reverseInitialStates[GetCharKind(input, i + 1)]); // If the initial state is nullable, meaning it accepts the empty string, then we've already discovered // a valid starting position, and we just need to keep looking for an earlier one in case there is one. int lastStart = -1; // invalid sentinel value if (currentState.DfaState!.IsNullable(GetCharKind(input, i))) { lastStart = i + 1; } // Walk backwards to the furthest accepting state of the reverse pattern but no earlier than matchStartBoundary. SymbolicRegexBuilder<TSetType> builder = currentState.DfaState.Node._builder; while (true) { // Run the DFA or NFA traversal backwards from the current point using the current state. bool done = currentState.NfaState is not null ? FindStartPositionDeltas<NfaStateHandler>(builder, input, ref i, matchStartBoundary, ref currentState, ref lastStart) : FindStartPositionDeltas<DfaStateHandler>(builder, input, ref i, matchStartBoundary, ref currentState, ref lastStart); // If we found the starting position, we're done. if (done) { break; } // We didn't find the starting position but we did exit out of the backwards traversal. That should only happen // if we were unable to transition, which should only happen if we were in DFA mode and exceeded our graph size. // Upgrade to NFA mode and continue. Debug.Assert(i >= matchStartBoundary); Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } Debug.Assert(lastStart != -1, "We expected to find a starting position but didn't."); return lastStart; } /// <summary> /// Workhorse inner loop for <see cref="FindStartPosition"/>. Consumes the <paramref name="input"/> character by character in reverse, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> private bool FindStartPositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, int startThreshold, ref CurrentState currentState, ref int lastStart) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Loop backwards through each character in the input, transitioning from state to state for each. while (TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { // We successfully transitioned. If the new state is a dead end, we're done, as we must have already seen // and recorded a larger lastStart value that was the earliest valid starting position. if (TStateHandler.IsDeadend(ref state)) { Debug.Assert(lastStart != -1); currentState = state; i = pos; return true; } // If the new state accepts the empty string, we found a valid starting position. Record it and keep going, // since we're looking for the earliest one to occur within bounds. if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos - 1))) { lastStart = pos; } // Since we successfully transitioned, update our current index to match the fact that we consumed the previous character in the input. pos--; // If doing so now puts us below the start threshold, bail; we should have already found a valid starting location. if (pos < startThreshold) { Debug.Assert(lastStart != -1); currentState = state; i = pos; return true; } } // Unable to transition further. currentState = state; i = pos; return false; } /// <summary>Performs the initial Phase 1 match to find the first final state encountered.</summary> /// <param name="input">The input text.</param> /// <param name="i">The starting position in <paramref name="input"/>.</param> /// <param name="timeoutOccursAt">The time at which timeout occurs, if timeouts are being checked.</param> /// <param name="initialStateIndex">The last position the initial state of <see cref="_dotStarredPattern"/> was visited.</param> /// <param name="matchLength">Length of the match if there's a match; otherwise, -1.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The index into input that matches the final state, or NoMatchExists if no match exists. It returns -1 when i=0 and the initial state is nullable.</returns> private int FindFinalStatePosition(ReadOnlySpan<char> input, int i, int timeoutOccursAt, out int initialStateIndex, out int matchLength, PerThreadData perThreadData) { matchLength = -1; initialStateIndex = i; // Start with the start state of the dot-star pattern, which in general depends on the previous character kind in the input in order to handle anchors. // If the starting state is a dead end, then no match exists. var currentState = new CurrentState(_dotstarredInitialStates[GetCharKind(input, i - 1)]); if (currentState.DfaState!.IsNothing) { // This can happen, for example, when the original regex starts with a beginning anchor but the previous char kind is not Beginning. return NoMatchExists; } // If the starting state accepts the empty string in this context (factoring in anchors), we're done. if (currentState.DfaState.IsNullable(GetCharKind(input, i))) { // The initial state is nullable in this context so at least an empty match exists. // The last position of the match is i - 1 because the match is empty. // This value is -1 if i == 0. return i - 1; } // Otherwise, start searching from the current position until the end of the input. if ((uint)i < (uint)input.Length) { SymbolicRegexBuilder<TSetType> builder = currentState.DfaState.Node._builder; while (true) { // If we're at an initial state, try to search ahead for the next possible match location // using any find optimizations that may have previously been computed. if (currentState.DfaState is { IsInitialState: true }) { // i is the most recent position in the input when the dot-star pattern is in the initial state initialStateIndex = i; if (_findOpts is RegexFindOptimizations findOpts) { // Find the first position i that matches with some likely character. if (!findOpts.TryFindNextStartingPosition(input, ref i, 0, 0, input.Length)) { // no match was found return NoMatchExists; } initialStateIndex = i; // Update the starting state based on where TryFindNextStartingPosition moved us to. // As with the initial starting state, if it's a dead end, no match exists. currentState = new CurrentState(_dotstarredInitialStates[GetCharKind(input, i - 1)]); if (currentState.DfaState!.IsNothing) { return NoMatchExists; } } } // Now run the DFA or NFA traversal from the current point using the current state. int finalStatePosition; int findResult = currentState.NfaState is not null ? FindFinalStatePositionDeltas<NfaStateHandler>(builder, input, ref i, ref currentState, ref matchLength, out finalStatePosition) : FindFinalStatePositionDeltas<DfaStateHandler>(builder, input, ref i, ref currentState, ref matchLength, out finalStatePosition); // If we reached a final or deadend state, we're done. if (findResult > 0) { return finalStatePosition; } // We're not at an end state, so we either ran out of input (in which case no match exists), hit an initial state (in which case // we want to loop around to apply our initial state processing logic and optimizations), or failed to transition (which should // only happen if we were in DFA mode and need to switch over to NFA mode). If we exited because we hit an initial state, // find result will be 0, otherwise negative. if (findResult < 0) { if ((uint)i >= (uint)input.Length) { // We ran out of input. No match. break; } // We failed to transition. Upgrade to DFA mode. Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } // Check for a timeout before continuing. if (_checkTimeout) { DoCheckTimeout(timeoutOccursAt); } } } // No match was found. return NoMatchExists; } /// <summary> /// Workhorse inner loop for <see cref="FindFinalStatePosition"/>. Consumes the <paramref name="input"/> character by character, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> /// <remarks> /// The <typeparamref name="TStateHandler"/> supplies the actual transitioning logic, controlling whether processing is /// performed in DFA mode or in NFA mode. However, it expects <paramref name="currentState"/> to be configured to match, /// so for example if <typeparamref name="TStateHandler"/> is a <see cref="DfaStateHandler"/>, it expects the <paramref name="currentState"/>'s /// <see cref="CurrentState.DfaState"/> to be non-null and its <see cref="CurrentState.NfaState"/> to be null; vice versa for /// <see cref="NfaStateHandler"/>. /// </remarks> /// <returns> /// A positive value if iteration completed because it reached a nullable or deadend state. /// 0 if iteration completed because we reached an initial state. /// A negative value if iteration completed because we ran out of input or we failed to transition. /// </returns> private int FindFinalStatePositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, ref CurrentState currentState, ref int matchLength, out int finalStatePosition) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Loop through each character in the input, transitioning from state to state for each. while ((uint)pos < (uint)input.Length && TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { // We successfully transitioned for the character at index i. If the new state is nullable for // the next character, meaning it accepts the empty string, we found a final state and are done! if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos + 1))) { // Check whether there's a fixed-length marker for the current state. If there is, we can // use that length to optimize subsequent matching phases. matchLength = TStateHandler.FixedLength(ref state); currentState = state; i = pos; finalStatePosition = pos; return 1; } // If the new state is a dead end, such that we didn't match and we can't transition anywhere // else, then no match exists. if (TStateHandler.IsDeadend(ref state)) { currentState = state; i = pos; finalStatePosition = NoMatchExists; return 1; } // We successfully transitioned, so update our current input index to match. pos++; // Now that currentState and our position are coherent, check if currentState represents an initial state. // If it does, we exit out in order to allow our find optimizations to kick in to hopefully more quickly // find the next possible starting location. if (TStateHandler.IsInitialState(ref state)) { currentState = state; i = pos; finalStatePosition = 0; return 0; } } currentState = state; i = pos; finalStatePosition = 0; return -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private uint GetCharKind(ReadOnlySpan<char> input, int i) { return !_pattern._info.ContainsSomeAnchor ? CharKind.General : // The previous character kind is irrelevant when anchors are not used. GetCharKindWithAnchor(input, i); uint GetCharKindWithAnchor(ReadOnlySpan<char> input, int i) { Debug.Assert(_asciiCharKinds is not null); if ((uint)i >= (uint)input.Length) { return CharKind.BeginningEnd; } char nextChar = input[i]; if (nextChar == '\n') { return _builder._newLinePredicate.Equals(_builder._solver.False) ? 0 : // ignore \n i == 0 || i == input.Length - 1 ? CharKind.NewLineS : // very first or very last \n. Detection of very first \n is needed for rev(\Z). CharKind.Newline; } uint[] asciiCharKinds = _asciiCharKinds; return nextChar < (uint)asciiCharKinds.Length ? asciiCharKinds[nextChar] : _builder._solver.And(GetMinterm(nextChar), _builder._wordLetterPredicateForAnchors).Equals(_builder._solver.False) ? 0 : //apply the wordletter predicate to compute the kind of the next character CharKind.WordLetter; } } /// <summary>Stores additional data for tracking capture start and end positions.</summary> /// <remarks>The NFA simulation based third phase has one of these for each current state in the current set of live states.</remarks> internal struct Registers { public Registers(int[] captureStarts, int[] captureEnds) { CaptureStarts = captureStarts; CaptureEnds = captureEnds; } public int[] CaptureStarts { get; set; } public int[] CaptureEnds { get; set; } /// <summary> /// Applies a list of effects in order to these registers at the provided input position. The order of effects /// should not matter though, as multiple effects to the same capture start or end do not arise. /// </summary> /// <param name="effects">list of effects to be applied</param> /// <param name="pos">the current input position to record</param> public void ApplyEffects(List<DerivativeEffect> effects, int pos) { foreach (DerivativeEffect effect in effects) { ApplyEffect(effect, pos); } } /// <summary> /// Apply a single effect to these registers at the provided input position. /// </summary> /// <param name="effect">the effecto to be applied</param> /// <param name="pos">the current input position to record</param> public void ApplyEffect(DerivativeEffect effect, int pos) { switch (effect.Kind) { case DerivativeEffectKind.CaptureStart: CaptureStarts[effect.CaptureNumber] = pos; break; case DerivativeEffectKind.CaptureEnd: CaptureEnds[effect.CaptureNumber] = pos; break; } } /// <summary> /// Make a copy of this set of registers. /// </summary> /// <returns>Registers pointing to copies of this set of registers</returns> public Registers Clone() => new Registers((int[])CaptureStarts.Clone(), (int[])CaptureEnds.Clone()); /// <summary> /// Copy register values from another set of registers, possibly allocating new arrays if they were not yet allocated. /// </summary> /// <param name="other">the registers to copy from</param> public void Assign(Registers other) { if (CaptureStarts is not null && CaptureEnds is not null) { Debug.Assert(CaptureStarts.Length == other.CaptureStarts.Length); Debug.Assert(CaptureEnds.Length == other.CaptureEnds.Length); Array.Copy(other.CaptureStarts, CaptureStarts, CaptureStarts.Length); Array.Copy(other.CaptureEnds, CaptureEnds, CaptureEnds.Length); } else { CaptureStarts = (int[])other.CaptureStarts.Clone(); CaptureEnds = (int[])other.CaptureEnds.Clone(); } } } /// <summary> /// Per thread data to be held by the regex runner and passed into every call to FindMatch. This is used to /// avoid repeated memory allocation. /// </summary> internal sealed class PerThreadData { public readonly NfaMatchingState NfaState; /// <summary>Maps used for the capturing third phase.</summary> public readonly SparseIntMap<Registers>? Current, Next; /// <summary>Registers used for the capturing third phase.</summary> public readonly Registers InitialRegisters; public PerThreadData(SymbolicRegexBuilder<TSetType> builder, int capsize) { NfaState = new NfaMatchingState(builder); // Only create data used for capturing mode if there are subcaptures if (capsize > 1) { Current = new(); Next = new(); InitialRegisters = new Registers(new int[capsize], new int[capsize]); } } } /// <summary>Stores the state that represents a current state in NFA mode.</summary> /// <remarks>The entire state is composed of a list of individual states.</remarks> internal sealed class NfaMatchingState { /// <summary>The associated builder used to lazily add new DFA or NFA nodes to the graph.</summary> public readonly SymbolicRegexBuilder<TSetType> Builder; /// <summary>Ordered set used to store the current NFA states.</summary> /// <remarks>The value is unused. The type is used purely for its keys.</remarks> public SparseIntMap<int> NfaStateSet = new(); /// <summary>Scratch set to swap with <see cref="NfaStateSet"/> on each transition.</summary> /// <remarks> /// On each transition, <see cref="NfaStateSetScratch"/> is cleared and filled with the next /// states computed from the current states in <see cref="NfaStateSet"/>, and then the sets /// are swapped so the scratch becomes the current and the current becomes the scratch. /// </remarks> public SparseIntMap<int> NfaStateSetScratch = new(); /// <summary>Create the instance.</summary> /// <remarks>New instances should only be created once per runner.</remarks> public NfaMatchingState(SymbolicRegexBuilder<TSetType> builder) => Builder = builder; /// <summary>Resets this NFA state to represent the supplied DFA state.</summary> /// <param name="dfaMatchingState">The DFA state to use to initialize the NFA state.</param> public void InitializeFrom(DfaMatchingState<TSetType> dfaMatchingState) { NfaStateSet.Clear(); // If the DFA state is a union of multiple DFA states, loop through all of them // adding an NFA state for each. if (dfaMatchingState.Node.Kind is SymbolicRegexNodeKind.Or) { Debug.Assert(dfaMatchingState.Node._alts is not null); foreach (SymbolicRegexNode<TSetType> node in dfaMatchingState.Node._alts) { // Create (possibly new) NFA states for all the members. // Add their IDs to the current set of NFA states and into the list. int nfaState = Builder.CreateNfaState(node, dfaMatchingState.PrevCharKind); NfaStateSet.Add(nfaState, out _); } } else { // Otherwise, just add an NFA state for the singular DFA state. SymbolicRegexNode<TSetType> node = dfaMatchingState.Node; int nfaState = Builder.CreateNfaState(node, dfaMatchingState.PrevCharKind); NfaStateSet.Add(nfaState, out _); } } } /// <summary>Represents a current state in a DFA or NFA graph walk while processing a regular expression.</summary> /// <remarks>This is a discriminated union between a DFA state and an NFA state. One and only one will be non-null.</remarks> private struct CurrentState { /// <summary>Initializes the state as a DFA state.</summary> public CurrentState(DfaMatchingState<TSetType> dfaState) { DfaState = dfaState; NfaState = null; } /// <summary>Initializes the state as an NFA state.</summary> public CurrentState(NfaMatchingState nfaState) { DfaState = null; NfaState = nfaState; } /// <summary>The DFA state.</summary> public DfaMatchingState<TSetType>? DfaState; /// <summary>The NFA state.</summary> public NfaMatchingState? NfaState; } /// <summary>Represents a set of routines for operating over a <see cref="CurrentState"/>.</summary> private interface IStateHandler { #pragma warning disable CA2252 // This API requires opting into preview features public static abstract bool StartsWithLineAnchor(ref CurrentState state); public static abstract bool IsNullable(ref CurrentState state, uint nextCharKind); public static abstract bool IsDeadend(ref CurrentState state); public static abstract int FixedLength(ref CurrentState state); public static abstract bool IsInitialState(ref CurrentState state); public static abstract bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId); #pragma warning restore CA2252 // This API requires opting into preview features } /// <summary>An <see cref="IStateHandler"/> for operating over <see cref="CurrentState"/> instances configured as DFA states.</summary> private readonly struct DfaStateHandler : IStateHandler { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWithLineAnchor(ref CurrentState state) => state.DfaState!.StartsWithLineAnchor; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullable(ref CurrentState state, uint nextCharKind) => state.DfaState!.IsNullable(nextCharKind); /// <summary>Gets whether this is a dead-end state, meaning there are no transitions possible out of the state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDeadend(ref CurrentState state) => state.DfaState!.IsDeadend; /// <summary>Gets the length of any fixed-length marker that exists for this state, or -1 if there is none.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FixedLength(ref CurrentState state) => state.DfaState!.FixedLength; /// <summary>Gets whether this is an initial state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInitialState(ref CurrentState state) => state.DfaState!.IsInitialState; /// <summary>Take the transition to the next DFA state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId) { Debug.Assert(state.DfaState is not null, $"Expected non-null {nameof(state.DfaState)}."); Debug.Assert(state.NfaState is null, $"Expected null {nameof(state.NfaState)}."); Debug.Assert(builder._delta is not null); // Get the current state. DfaMatchingState<TSetType> dfaMatchingState = state.DfaState!; // Use the mintermId for the character being read to look up which state to transition to. // If that state has already been materialized, move to it, and we're done. If that state // hasn't been materialized, try to create it; if we can, move to it, and we're done. int dfaOffset = (dfaMatchingState.Id << builder._mintermsLog) | mintermId; DfaMatchingState<TSetType>? nextState = builder._delta[dfaOffset]; if (nextState is not null || builder.TryCreateNewTransition(dfaMatchingState, mintermId, dfaOffset, checkThreshold: true, out nextState)) { // There was an existing state for this transition or we were able to create one. Move to it and // return that we're still operating as a DFA and can keep going. state.DfaState = nextState; return true; } return false; } } /// <summary>An <see cref="IStateHandler"/> for operating over <see cref="CurrentState"/> instances configured as NFA states.</summary> private readonly struct NfaStateHandler : IStateHandler { /// <summary>Check if any underlying core state starts with a line anchor.</summary> public static bool StartsWithLineAnchor(ref CurrentState state) { SymbolicRegexBuilder<TSetType> builder = state.NfaState!.Builder; foreach (ref KeyValuePair<int, int> nfaState in CollectionsMarshal.AsSpan(state.NfaState!.NfaStateSet.Values)) { if (builder.GetCoreState(nfaState.Key).StartsWithLineAnchor) { return true; } } return false; } /// <summary>Check if any underlying core state is nullable.</summary> public static bool IsNullable(ref CurrentState state, uint nextCharKind) { SymbolicRegexBuilder<TSetType> builder = state.NfaState!.Builder; foreach (ref KeyValuePair<int, int> nfaState in CollectionsMarshal.AsSpan(state.NfaState!.NfaStateSet.Values)) { if (builder.GetCoreState(nfaState.Key).IsNullable(nextCharKind)) { return true; } } return false; } /// <summary>Gets whether this is a dead-end state, meaning there are no transitions possible out of the state.</summary> /// <remarks>In NFA mode, an empty set of states means that it is a dead end.</remarks> public static bool IsDeadend(ref CurrentState state) => state.NfaState!.NfaStateSet.Count == 0; /// <summary>Gets the length of any fixed-length marker that exists for this state, or -1 if there is none.</summary> /// <summary>In NFA mode, there are no fixed-length markers.</summary> public static int FixedLength(ref CurrentState state) => -1; /// <summary>Gets whether this is an initial state.</summary> /// <summary>In NFA mode, no set of states qualifies as an initial state.</summary> public static bool IsInitialState(ref CurrentState state) => false; /// <summary>Take the transition to the next NFA state.</summary> public static bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId) { Debug.Assert(state.DfaState is null, $"Expected null {nameof(state.DfaState)}."); Debug.Assert(state.NfaState is not null, $"Expected non-null {nameof(state.NfaState)}."); NfaMatchingState nfaState = state.NfaState!; // Grab the sets, swapping the current active states set with the scratch set. SparseIntMap<int> nextStates = nfaState.NfaStateSetScratch; SparseIntMap<int> sourceStates = nfaState.NfaStateSet; nfaState.NfaStateSet = nextStates; nfaState.NfaStateSetScratch = sourceStates; // Compute the set of all unique next states from the current source states and the mintermId. nextStates.Clear(); if (sourceStates.Count == 1) { // We have a single source state. We know its next states are already deduped, // so we can just add them directly to the destination states list. foreach (int nextState in GetNextStates(sourceStates.Values[0].Key, mintermId, builder)) { nextStates.Add(nextState, out _); } } else { // We have multiple source states, so we need to potentially dedup across each of // their next states. For each source state, get its next states, adding each into // our set (which exists purely for deduping purposes), and if we successfully added // to the set, then add the known-unique state to the destination list. foreach (ref KeyValuePair<int, int> sourceState in CollectionsMarshal.AsSpan(sourceStates.Values)) { foreach (int nextState in GetNextStates(sourceState.Key, mintermId, builder)) { nextStates.Add(nextState, out _); } } } return true; [MethodImpl(MethodImplOptions.AggressiveInlining)] static int[] GetNextStates(int sourceState, int mintermId, SymbolicRegexBuilder<TSetType> builder) { // Calculate the offset into the NFA transition table. int nfaOffset = (sourceState << builder._mintermsLog) | mintermId; // Get the next NFA state. return builder._nfaDelta[nfaOffset] ?? builder.CreateNewNfaTransition(sourceState, mintermId, nfaOffset); } } } #if DEBUG public override void SaveDGML(TextWriter writer, int bound, bool hideStateInfo, bool addDotStar, bool inReverse, bool onlyDFAinfo, int maxLabelLength, bool asNFA) { var graph = new DGML.RegexAutomaton<TSetType>(this, bound, addDotStar, inReverse, asNFA); var dgml = new DGML.DgmlWriter(writer, hideStateInfo, maxLabelLength, onlyDFAinfo); dgml.Write(graph); } public override IEnumerable<string> GenerateRandomMembers(int k, int randomseed, bool negative) => new SymbolicRegexSampler<TSetType>(_pattern, randomseed, negative).GenerateRandomMembers(k); #endif } }
// 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.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace System.Text.RegularExpressions.Symbolic { /// <summary>Represents a regex matching engine that performs regex matching using symbolic derivatives.</summary> internal abstract class SymbolicRegexMatcher { #if DEBUG /// <summary>Unwind the regex of the matcher and save the resulting state graph in DGML</summary> /// <param name="bound">roughly the maximum number of states, 0 means no bound</param> /// <param name="hideStateInfo">if true then hide state info</param> /// <param name="addDotStar">if true then pretend that there is a .* at the beginning</param> /// <param name="inReverse">if true then unwind the regex backwards (addDotStar is then ignored)</param> /// <param name="onlyDFAinfo">if true then compute and save only genral DFA info</param> /// <param name="writer">dgml output is written here</param> /// <param name="maxLabelLength">maximum length of labels in nodes anything over that length is indicated with .. </param> /// <param name="asNFA">if true creates NFA instead of DFA</param> public abstract void SaveDGML(TextWriter writer, int bound, bool hideStateInfo, bool addDotStar, bool inReverse, bool onlyDFAinfo, int maxLabelLength, bool asNFA); /// <summary> /// Generates up to k random strings matched by the regex /// </summary> /// <param name="k">upper bound on the number of generated strings</param> /// <param name="randomseed">random seed for the generator, 0 means no random seed</param> /// <param name="negative">if true then generate inputs that do not match</param> /// <returns></returns> public abstract IEnumerable<string> GenerateRandomMembers(int k, int randomseed, bool negative); #endif } /// <summary>Represents a regex matching engine that performs regex matching using symbolic derivatives.</summary> /// <typeparam name="TSetType">Character set type.</typeparam> internal sealed class SymbolicRegexMatcher<TSetType> : SymbolicRegexMatcher where TSetType : notnull { /// <summary>Maximum number of built states before switching over to NFA mode.</summary> /// <remarks> /// By default, all matching starts out using DFAs, where every state transitions to one and only one /// state for any minterm (each character maps to one minterm). Some regular expressions, however, can result /// in really, really large DFA state graphs, much too big to actually store. Instead of failing when we /// encounter such state graphs, at some point we instead switch from processing as a DFA to processing as /// an NFA. As an NFA, we instead track all of the states we're in at any given point, and transitioning /// from one "state" to the next really means for every constituent state that composes our current "state", /// we find all possible states that transitioning out of each of them could result in, and the union of /// all of those is our new "state". This constant represents the size of the graph after which we start /// processing as an NFA instead of as a DFA. This processing doesn't change immediately, however. All /// processing starts out in DFA mode, even if we've previously triggered NFA mode for the same regex. /// We switch over into NFA mode the first time a given traversal (match operation) results in us needing /// to create a new node and the graph is already or newly beyond this threshold. /// </remarks> internal const int NfaThreshold = 10_000; /// <summary>Sentinel value used internally by the matcher to indicate no match exists.</summary> private const int NoMatchExists = -2; /// <summary>Builder used to create <see cref="SymbolicRegexNode{S}"/>s while matching.</summary> /// <remarks> /// The builder is used to build up the DFA state space lazily, which means we need to be able to /// produce new <see cref="SymbolicRegexNode{S}"/>s as we match. Once in NFA mode, we also use /// the builder to produce new NFA states. The builder maintains a cache of all DFA and NFA states. /// </remarks> internal readonly SymbolicRegexBuilder<TSetType> _builder; /// <summary>Maps every character to its corresponding minterm ID.</summary> private readonly MintermClassifier _mintermClassifier; /// <summary><see cref="_pattern"/> prefixed with [0-0xFFFF]*</summary> /// <remarks> /// The matching engine first uses <see cref="_dotStarredPattern"/> to find whether there is a match /// and where that match might end. Prepending the .* prefix onto the original pattern provides the DFA /// with the ability to continue to process input characters even if those characters aren't part of /// the match. If Regex.IsMatch is used, nothing further is needed beyond this prefixed pattern. If, however, /// other matching operations are performed that require knowing the exact start and end of the match, /// the engine then needs to process the pattern in reverse to find where the match actually started; /// for that, it uses the <see cref="_reversePattern"/> and walks backwards through the input characters /// from where <see cref="_dotStarredPattern"/> left off. At this point we know that there was a match, /// where it started, and where it could have ended, but that ending point could be influenced by the /// selection of the starting point. So, to find the actual ending point, the original <see cref="_pattern"/> /// is then used from that starting point to walk forward through the input characters again to find the /// actual end point used for the match. /// </remarks> internal readonly SymbolicRegexNode<TSetType> _dotStarredPattern; /// <summary>The original regex pattern.</summary> internal readonly SymbolicRegexNode<TSetType> _pattern; /// <summary>The reverse of <see cref="_pattern"/>.</summary> /// <remarks> /// Determining that there is a match and where the match ends requires only <see cref="_pattern"/>. /// But from there determining where the match began requires reversing the pattern and running /// the matcher again, starting from the ending position. This <see cref="_reversePattern"/> caches /// that reversed pattern used for extracting match start. /// </remarks> internal readonly SymbolicRegexNode<TSetType> _reversePattern; /// <summary>true iff timeout checking is enabled.</summary> private readonly bool _checkTimeout; /// <summary>Timeout in milliseconds. This is only used if <see cref="_checkTimeout"/> is true.</summary> private readonly int _timeout; /// <summary>Data and routines for skipping ahead to the next place a match could potentially start.</summary> private readonly RegexFindOptimizations? _findOpts; /// <summary>The initial states for the original pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _initialStates; /// <summary>The initial states for the dot-star pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _dotstarredInitialStates; /// <summary>The initial states for the reverse pattern, keyed off of the previous character kind.</summary> /// <remarks>If the pattern doesn't contain any anchors, there will only be a single initial state.</remarks> private readonly DfaMatchingState<TSetType>[] _reverseInitialStates; /// <summary>Lookup table to quickly determine the character kind for ASCII characters.</summary> /// <remarks>Non-null iff the pattern contains anchors; otherwise, it's unused.</remarks> private readonly uint[]? _asciiCharKinds; /// <summary>Number of capture groups.</summary> private readonly int _capsize; /// <summary>Fixed-length of any possible match.</summary> /// <remarks>This will be null if matches may be of varying lengths or if a fixed-length couldn't otherwise be computed.</remarks> private readonly int? _fixedMatchLength; /// <summary>Gets whether the regular expression contains captures (beyond the implicit root-level capture).</summary> /// <remarks>This determines whether the matcher uses the special capturing NFA simulation mode.</remarks> internal bool HasSubcaptures => _capsize > 1; /// <summary>Get the minterm of <paramref name="c"/>.</summary> /// <param name="c">character code</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private TSetType GetMinterm(int c) { Debug.Assert(_builder._minterms is not null); return _builder._minterms[_mintermClassifier.GetMintermID(c)]; } /// <summary>Constructs matcher for given symbolic regex.</summary> internal SymbolicRegexMatcher(SymbolicRegexNode<TSetType> sr, RegexTree regexTree, BDD[] minterms, TimeSpan matchTimeout) { Debug.Assert(sr._builder._solver is BitVector64Algebra or BitVectorAlgebra or CharSetSolver, $"Unsupported algebra: {sr._builder._solver}"); _pattern = sr; _builder = sr._builder; _checkTimeout = Regex.InfiniteMatchTimeout != matchTimeout; _timeout = (int)(matchTimeout.TotalMilliseconds + 0.5); // Round up, so it will be at least 1ms _mintermClassifier = _builder._solver switch { BitVector64Algebra bv64 => bv64._classifier, BitVectorAlgebra bv => bv._classifier, _ => new MintermClassifier((CharSetSolver)(object)_builder._solver, minterms), }; _capsize = regexTree.CaptureCount; if (regexTree.FindOptimizations.MinRequiredLength == regexTree.FindOptimizations.MaxPossibleLength) { _fixedMatchLength = regexTree.FindOptimizations.MinRequiredLength; } if (regexTree.FindOptimizations.FindMode != FindNextStartingPositionMode.NoSearch && regexTree.FindOptimizations.LeadingAnchor == 0) // If there are any anchors, we're better off letting the DFA quickly do its job of determining whether there's a match. { _findOpts = regexTree.FindOptimizations; } // Determine the number of initial states. If there's no anchor, only the default previous // character kind 0 is ever going to be used for all initial states. int statesCount = _pattern._info.ContainsSomeAnchor ? CharKind.CharKindCount : 1; // Create the initial states for the original pattern. var initialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < initialStates.Length; i++) { initialStates[i] = _builder.CreateState(_pattern, i, capturing: HasSubcaptures); } _initialStates = initialStates; // Create the dot-star pattern (a concatenation of any* with the original pattern) // and all of its initial states. SymbolicRegexNode<TSetType> unorderedPattern = _pattern.IgnoreOrOrderAndLazyness(); _dotStarredPattern = _builder.CreateConcat(_builder._anyStar, unorderedPattern); var dotstarredInitialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < dotstarredInitialStates.Length; i++) { // Used to detect if initial state was reentered, // but observe that the behavior from the state may ultimately depend on the previous // input char e.g. possibly causing nullability of \b or \B or of a start-of-line anchor, // in that sense there can be several "versions" (not more than StateCount) of the initial state. DfaMatchingState<TSetType> state = _builder.CreateState(_dotStarredPattern, i, capturing: false); state.IsInitialState = true; dotstarredInitialStates[i] = state; } _dotstarredInitialStates = dotstarredInitialStates; // Create the reverse pattern (the original pattern in reverse order) and all of its // initial states. _reversePattern = unorderedPattern.Reverse(); var reverseInitialStates = new DfaMatchingState<TSetType>[statesCount]; for (uint i = 0; i < reverseInitialStates.Length; i++) { reverseInitialStates[i] = _builder.CreateState(_reversePattern, i, capturing: false); } _reverseInitialStates = reverseInitialStates; // Initialize our fast-lookup for determining the character kind of ASCII characters. // This is only required when the pattern contains anchors, as otherwise there's only // ever a single kind used. if (_pattern._info.ContainsSomeAnchor) { var asciiCharKinds = new uint[128]; for (int i = 0; i < asciiCharKinds.Length; i++) { TSetType predicate2; uint charKind; if (i == '\n') { predicate2 = _builder._newLinePredicate; charKind = CharKind.Newline; } else { predicate2 = _builder._wordLetterPredicateForAnchors; charKind = CharKind.WordLetter; } asciiCharKinds[i] = _builder._solver.And(GetMinterm(i), predicate2).Equals(_builder._solver.False) ? 0 : charKind; } _asciiCharKinds = asciiCharKinds; } } /// <summary> /// Create a PerThreadData with the appropriate parts initialized for this matcher's pattern. /// </summary> internal PerThreadData CreatePerThreadData() => new PerThreadData(_builder, _capsize); /// <summary>Compute the target state for the source state and input[i] character and transition to it.</summary> /// <param name="builder">The associated builder.</param> /// <param name="input">The input text.</param> /// <param name="i">The index into <paramref name="input"/> at which the target character lives.</param> /// <param name="state">The current state being transitioned from. Upon return it's the new state if the transition succeeded.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryTakeTransition<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, int i, ref CurrentState state) where TStateHandler : struct, IStateHandler { int c = input[i]; int mintermId = c == '\n' && i == input.Length - 1 && TStateHandler.StartsWithLineAnchor(ref state) ? builder._minterms!.Length : // mintermId = minterms.Length represents \Z (last \n) _mintermClassifier.GetMintermID(c); return TStateHandler.TakeTransition(builder, ref state, mintermId); } private List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)> CreateNewCapturingTransitions(DfaMatchingState<TSetType> state, TSetType minterm, int offset) { Debug.Assert(_builder._capturingDelta is not null); lock (this) { // Get the next state if it exists. The caller should have already tried and found it null (not yet created), // but in the interim another thread could have created it. List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)>? p = _builder._capturingDelta[offset]; if (p is null) { // Build the new state and store it into the array. p = state.NfaEagerNextWithEffects(minterm); Volatile.Write(ref _builder._capturingDelta[offset], p); } return p; } } private void DoCheckTimeout(int timeoutOccursAt) { // This logic is identical to RegexRunner.DoCheckTimeout, with the exception of check skipping. RegexRunner calls // DoCheckTimeout potentially on every iteration of a loop, whereas this calls it only once per transition. int currentMillis = Environment.TickCount; if (currentMillis >= timeoutOccursAt && (0 <= timeoutOccursAt || 0 >= currentMillis)) { throw new RegexMatchTimeoutException(string.Empty, string.Empty, TimeSpan.FromMilliseconds(_timeout)); } } /// <summary>Find a match.</summary> /// <param name="isMatch">Whether to return once we know there's a match without determining where exactly it matched.</param> /// <param name="input">The input span</param> /// <param name="startat">The position to start search in the input span.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> public SymbolicMatch FindMatch(bool isMatch, ReadOnlySpan<char> input, int startat, PerThreadData perThreadData) { Debug.Assert(startat >= 0 && startat <= input.Length, $"{nameof(startat)} == {startat}, {nameof(input.Length)} == {input.Length}"); Debug.Assert(perThreadData is not null); // If we need to perform timeout checks, store the absolute timeout value. int timeoutOccursAt = 0; if (_checkTimeout) { // Using Environment.TickCount for efficiency instead of Stopwatch -- as in the non-DFA case. timeoutOccursAt = Environment.TickCount + (int)(_timeout + 0.5); } // If we're starting at the end of the input, we don't need to do any work other than // determine whether an empty match is valid, i.e. whether the pattern is "nullable" // given the kinds of characters at and just before the end. if (startat == input.Length) { // TODO https://github.com/dotnet/runtime/issues/65606: Handle capture groups. uint prevKind = GetCharKind(input, startat - 1); uint nextKind = GetCharKind(input, startat); return _pattern.IsNullableFor(CharKind.Context(prevKind, nextKind)) ? new SymbolicMatch(startat, 0) : SymbolicMatch.NoMatch; } // Phase 1: // Determine whether there is a match by finding the first final state position. This only tells // us whether there is a match but needn't give us the longest possible match. This may return -1 as // a legitimate value when the initial state is nullable and startat == 0. It returns NoMatchExists (-2) // when there is no match. As an example, consider the pattern a{5,10}b* run against an input // of aaaaaaaaaaaaaaabbbc: phase 1 will find the position of the first b: aaaaaaaaaaaaaaab. int i = FindFinalStatePosition(input, startat, timeoutOccursAt, out int matchStartLowBoundary, out int matchStartLengthMarker, perThreadData); // If there wasn't a match, we're done. if (i == NoMatchExists) { return SymbolicMatch.NoMatch; } // A match exists. If we don't need further details, because IsMatch was used (and thus we don't // need the exact bounds of the match, captures, etc.), we're done. if (isMatch) { return SymbolicMatch.QuickMatch; } // Phase 2: // Match backwards through the input matching against the reverse of the pattern, looking for the earliest // start position. That tells us the actual starting position of the match. We can skip this phase if we // recorded a fixed-length marker for the portion of the pattern that matched, as we can then jump that // exact number of positions backwards. Continuing the previous example, phase 2 will walk backwards from // that first b until it finds the 6th a: aaaaaaaaaab. int matchStart; if (matchStartLengthMarker >= 0) { matchStart = i - matchStartLengthMarker + 1; } else { Debug.Assert(i >= startat - 1); matchStart = i < startat ? startat : FindStartPosition(input, i, matchStartLowBoundary, perThreadData); } // Phase 3: // Match again, this time from the computed start position, to find the latest end position. That start // and end then represent the bounds of the match. If the pattern has subcaptures (captures other than // the top-level capture for the whole match), we need to do more work to compute their exact bounds, so we // take a faster path if captures aren't required. Further, if captures aren't needed, and if any possible // match of the whole pattern is a fixed length, we can skip this phase as well, just using that fixed-length // to compute the ending position based on the starting position. Continuing the previous example, phase 3 // will walk forwards from the 6th a until it finds the end of the match: aaaaaaaaaabbb. if (!HasSubcaptures) { if (_fixedMatchLength.HasValue) { return new SymbolicMatch(matchStart, _fixedMatchLength.GetValueOrDefault()); } int matchEnd = FindEndPosition(input, matchStart, perThreadData); return new SymbolicMatch(matchStart, matchEnd + 1 - matchStart); } else { int matchEnd = FindEndPositionCapturing(input, matchStart, out Registers endRegisters, perThreadData); return new SymbolicMatch(matchStart, matchEnd + 1 - matchStart, endRegisters.CaptureStarts, endRegisters.CaptureEnds); } } /// <summary>Phase 3 of matching. From a found starting position, find the ending position of the match using the original pattern.</summary> /// <remarks> /// The ending position is known to exist; this function just needs to determine exactly what it is. /// We need to find the longest possible match and thus the latest valid ending position. /// </remarks> /// <param name="input">The input text.</param> /// <param name="i">The starting position of the match.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The found ending position of the match.</returns> private int FindEndPosition(ReadOnlySpan<char> input, int i, PerThreadData perThreadData) { // Get the starting state based on the current context. DfaMatchingState<TSetType> dfaStartState = _initialStates[GetCharKind(input, i - 1)]; // If the starting state is nullable (accepts the empty string), then it's a valid // match and we need to record the position as a possible end, but keep going looking // for a better one. int end = input.Length; // invalid sentinel value if (dfaStartState.IsNullable(GetCharKind(input, i))) { // Empty match exists because the initial state is accepting. end = i - 1; } if ((uint)i < (uint)input.Length) { // Iterate from the starting state until we've found the best ending state. SymbolicRegexBuilder<TSetType> builder = dfaStartState.Node._builder; var currentState = new CurrentState(dfaStartState); while (true) { // Run the DFA or NFA traversal backwards from the current point using the current state. bool done = currentState.NfaState is not null ? FindEndPositionDeltas<NfaStateHandler>(builder, input, ref i, ref currentState, ref end) : FindEndPositionDeltas<DfaStateHandler>(builder, input, ref i, ref currentState, ref end); // If we successfully found the ending position, we're done. if (done || (uint)i >= (uint)input.Length) { break; } // We exited out of the inner processing loop, but we didn't hit a dead end or run out // of input, and that should only happen if we failed to transition from one state to // the next, which should only happen if we were in DFA mode and we tried to create // a new state and exceeded the graph size. Upgrade to NFA mode and continue; Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } } // Return the found ending position. Debug.Assert(end < input.Length, "Expected to find an ending position but didn't"); return end; } /// <summary> /// Workhorse inner loop for <see cref="FindEndPosition"/>. Consumes the <paramref name="input"/> character by character, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> private bool FindEndPositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, ref CurrentState currentState, ref int endingIndex) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Repeatedly read the next character from the input and use it to transition the current state to the next. // We're looking for the furthest final state we can find. while ((uint)pos < (uint)input.Length && TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos + 1))) { // If the new state accepts the empty string, we found an ending state. Record the position. endingIndex = pos; } else if (TStateHandler.IsDeadend(ref state)) { // If the new state is a dead end, the match ended the last time endingIndex was updated. currentState = state; i = pos; return true; } // We successfully transitioned to the next state and consumed the current character, // so move along to the next. pos++; } // We either ran out of input, in which case we successfully recorded an ending index, // or we failed to transition to the next state due to the graph becoming too large. currentState = state; i = pos; return false; } /// <summary>Find match end position using the original pattern, end position is known to exist. This version also produces captures.</summary> /// <param name="input">input span</param> /// <param name="i">inclusive start position</param> /// <param name="resultRegisters">out parameter for the final register values, which indicate capture starts and ends</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>the match end position</returns> private int FindEndPositionCapturing(ReadOnlySpan<char> input, int i, out Registers resultRegisters, PerThreadData perThreadData) { int i_end = input.Length; Registers endRegisters = default; DfaMatchingState<TSetType>? endState = null; // Pick the correct start state based on previous character kind. DfaMatchingState<TSetType> initialState = _initialStates[GetCharKind(input, i - 1)]; Registers initialRegisters = perThreadData.InitialRegisters; // Initialize registers with -1, which means "not seen yet" Array.Fill(initialRegisters.CaptureStarts, -1); Array.Fill(initialRegisters.CaptureEnds, -1); if (initialState.IsNullable(GetCharKind(input, i))) { // Empty match exists because the initial state is accepting. i_end = i - 1; endRegisters.Assign(initialRegisters); endState = initialState; } // Use two maps from state IDs to register values for the current and next set of states. // Note that these maps use insertion order, which is used to maintain priorities between states in a way // that matches the order the backtracking engines visit paths. Debug.Assert(perThreadData.Current is not null && perThreadData.Next is not null); SparseIntMap<Registers> current = perThreadData.Current, next = perThreadData.Next; current.Clear(); next.Clear(); current.Add(initialState.Id, initialRegisters); SymbolicRegexBuilder<TSetType> builder = _builder; while ((uint)i < (uint)input.Length) { Debug.Assert(next.Count == 0); int c = input[i]; int normalMintermId = _mintermClassifier.GetMintermID(c); foreach ((int sourceId, Registers sourceRegisters) in current.Values) { Debug.Assert(builder._capturingStateArray is not null); DfaMatchingState<TSetType> sourceState = builder._capturingStateArray[sourceId]; // Find the minterm, handling the special case for the last \n int mintermId = c == '\n' && i == input.Length - 1 && sourceState.StartsWithLineAnchor ? builder._minterms!.Length : normalMintermId; // mintermId = minterms.Length represents \Z (last \n) TSetType minterm = builder.GetMinterm(mintermId); // Get or create the transitions int offset = (sourceId << builder._mintermsLog) | mintermId; Debug.Assert(builder._capturingDelta is not null); List<(DfaMatchingState<TSetType>, List<DerivativeEffect>)>? transitions = builder._capturingDelta[offset] ?? CreateNewCapturingTransitions(sourceState, minterm, offset); // Take the transitions in their prioritized order for (int j = 0; j < transitions.Count; ++j) { (DfaMatchingState<TSetType> targetState, List<DerivativeEffect> effects) = transitions[j]; if (targetState.IsDeadend) continue; // Try to add the state and handle the case where it didn't exist before. If the state already // exists, then the transition can be safely ignored, as the existing state was generated by a // higher priority transition. if (next.Add(targetState.Id, out int index)) { // Avoid copying the registers on the last transition from this state, reusing the registers instead Registers newRegisters = j != transitions.Count - 1 ? sourceRegisters.Clone() : sourceRegisters; newRegisters.ApplyEffects(effects, i); next.Update(index, targetState.Id, newRegisters); if (targetState.IsNullable(GetCharKind(input, i + 1))) { // Accepting state has been reached. Record the position. i_end = i; endRegisters.Assign(newRegisters); endState = targetState; // No lower priority transitions from this or other source states are taken because the // backtracking engines would return the match ending here. goto BreakNullable; } } } } BreakNullable: if (next.Count == 0) { // If all states died out some nullable state must have been seen before break; } // Swap the state sets and prepare for the next character SparseIntMap<Registers> tmp = current; current = next; next = tmp; next.Clear(); i++; } Debug.Assert(i_end != input.Length && endState is not null); // Apply effects for finishing at the stored end state endState.Node.ApplyEffects(effect => endRegisters.ApplyEffect(effect, i_end + 1), CharKind.Context(endState.PrevCharKind, GetCharKind(input, i_end + 1))); resultRegisters = endRegisters; return i_end; } /// <summary> /// Phase 2 of matching. From a found ending position, walk in reverse through the input using the reverse pattern to find the /// start position of match. /// </summary> /// <remarks> /// The start position is known to exist; this function just needs to determine exactly what it is. /// We need to find the earliest (lowest index) starting position that's not earlier than <paramref name="matchStartBoundary"/>. /// </remarks> /// <param name="input">The input text.</param> /// <param name="i">The ending position to walk backwards from. <paramref name="i"/> points at the last character of the match.</param> /// <param name="matchStartBoundary">The initial starting location discovered in phase 1, a point we must not walk earlier than.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The found starting position for the match.</returns> private int FindStartPosition(ReadOnlySpan<char> input, int i, int matchStartBoundary, PerThreadData perThreadData) { Debug.Assert(i >= 0, $"{nameof(i)} == {i}"); Debug.Assert(matchStartBoundary >= 0 && matchStartBoundary < input.Length, $"{nameof(matchStartBoundary)} == {matchStartBoundary}"); Debug.Assert(i >= matchStartBoundary, $"Expected {i} >= {matchStartBoundary}."); // Get the starting state for the reverse pattern. This depends on previous character (which, because we're // going backwards, is character number i + 1). var currentState = new CurrentState(_reverseInitialStates[GetCharKind(input, i + 1)]); // If the initial state is nullable, meaning it accepts the empty string, then we've already discovered // a valid starting position, and we just need to keep looking for an earlier one in case there is one. int lastStart = -1; // invalid sentinel value if (currentState.DfaState!.IsNullable(GetCharKind(input, i))) { lastStart = i + 1; } // Walk backwards to the furthest accepting state of the reverse pattern but no earlier than matchStartBoundary. SymbolicRegexBuilder<TSetType> builder = currentState.DfaState.Node._builder; while (true) { // Run the DFA or NFA traversal backwards from the current point using the current state. bool done = currentState.NfaState is not null ? FindStartPositionDeltas<NfaStateHandler>(builder, input, ref i, matchStartBoundary, ref currentState, ref lastStart) : FindStartPositionDeltas<DfaStateHandler>(builder, input, ref i, matchStartBoundary, ref currentState, ref lastStart); // If we found the starting position, we're done. if (done) { break; } // We didn't find the starting position but we did exit out of the backwards traversal. That should only happen // if we were unable to transition, which should only happen if we were in DFA mode and exceeded our graph size. // Upgrade to NFA mode and continue. Debug.Assert(i >= matchStartBoundary); Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } Debug.Assert(lastStart != -1, "We expected to find a starting position but didn't."); return lastStart; } /// <summary> /// Workhorse inner loop for <see cref="FindStartPosition"/>. Consumes the <paramref name="input"/> character by character in reverse, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> private bool FindStartPositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, int startThreshold, ref CurrentState currentState, ref int lastStart) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Loop backwards through each character in the input, transitioning from state to state for each. while (TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { // We successfully transitioned. If the new state is a dead end, we're done, as we must have already seen // and recorded a larger lastStart value that was the earliest valid starting position. if (TStateHandler.IsDeadend(ref state)) { Debug.Assert(lastStart != -1); currentState = state; i = pos; return true; } // If the new state accepts the empty string, we found a valid starting position. Record it and keep going, // since we're looking for the earliest one to occur within bounds. if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos - 1))) { lastStart = pos; } // Since we successfully transitioned, update our current index to match the fact that we consumed the previous character in the input. pos--; // If doing so now puts us below the start threshold, bail; we should have already found a valid starting location. if (pos < startThreshold) { Debug.Assert(lastStart != -1); currentState = state; i = pos; return true; } } // Unable to transition further. currentState = state; i = pos; return false; } /// <summary>Performs the initial Phase 1 match to find the first final state encountered.</summary> /// <param name="input">The input text.</param> /// <param name="i">The starting position in <paramref name="input"/>.</param> /// <param name="timeoutOccursAt">The time at which timeout occurs, if timeouts are being checked.</param> /// <param name="initialStateIndex">The last position the initial state of <see cref="_dotStarredPattern"/> was visited.</param> /// <param name="matchLength">Length of the match if there's a match; otherwise, -1.</param> /// <param name="perThreadData">Per thread data reused between calls.</param> /// <returns>The index into input that matches the final state, or NoMatchExists if no match exists. It returns -1 when i=0 and the initial state is nullable.</returns> private int FindFinalStatePosition(ReadOnlySpan<char> input, int i, int timeoutOccursAt, out int initialStateIndex, out int matchLength, PerThreadData perThreadData) { matchLength = -1; initialStateIndex = i; // Start with the start state of the dot-star pattern, which in general depends on the previous character kind in the input in order to handle anchors. // If the starting state is a dead end, then no match exists. var currentState = new CurrentState(_dotstarredInitialStates[GetCharKind(input, i - 1)]); if (currentState.DfaState!.IsNothing) { // This can happen, for example, when the original regex starts with a beginning anchor but the previous char kind is not Beginning. return NoMatchExists; } // If the starting state accepts the empty string in this context (factoring in anchors), we're done. if (currentState.DfaState.IsNullable(GetCharKind(input, i))) { // The initial state is nullable in this context so at least an empty match exists. // The last position of the match is i - 1 because the match is empty. // This value is -1 if i == 0. return i - 1; } // Otherwise, start searching from the current position until the end of the input. if ((uint)i < (uint)input.Length) { SymbolicRegexBuilder<TSetType> builder = currentState.DfaState.Node._builder; while (true) { // If we're at an initial state, try to search ahead for the next possible match location // using any find optimizations that may have previously been computed. if (currentState.DfaState is { IsInitialState: true }) { // i is the most recent position in the input when the dot-star pattern is in the initial state initialStateIndex = i; if (_findOpts is RegexFindOptimizations findOpts) { // Find the first position i that matches with some likely character. if (!findOpts.TryFindNextStartingPosition(input, ref i, 0, 0, input.Length)) { // no match was found return NoMatchExists; } initialStateIndex = i; // Update the starting state based on where TryFindNextStartingPosition moved us to. // As with the initial starting state, if it's a dead end, no match exists. currentState = new CurrentState(_dotstarredInitialStates[GetCharKind(input, i - 1)]); if (currentState.DfaState!.IsNothing) { return NoMatchExists; } } } // Now run the DFA or NFA traversal from the current point using the current state. int finalStatePosition; int findResult = currentState.NfaState is not null ? FindFinalStatePositionDeltas<NfaStateHandler>(builder, input, ref i, ref currentState, ref matchLength, out finalStatePosition) : FindFinalStatePositionDeltas<DfaStateHandler>(builder, input, ref i, ref currentState, ref matchLength, out finalStatePosition); // If we reached a final or deadend state, we're done. if (findResult > 0) { return finalStatePosition; } // We're not at an end state, so we either ran out of input (in which case no match exists), hit an initial state (in which case // we want to loop around to apply our initial state processing logic and optimizations), or failed to transition (which should // only happen if we were in DFA mode and need to switch over to NFA mode). If we exited because we hit an initial state, // find result will be 0, otherwise negative. if (findResult < 0) { if ((uint)i >= (uint)input.Length) { // We ran out of input. No match. break; } // We failed to transition. Upgrade to DFA mode. Debug.Assert(currentState.DfaState is not null); NfaMatchingState nfaState = perThreadData.NfaState; nfaState.InitializeFrom(currentState.DfaState); currentState = new CurrentState(nfaState); } // Check for a timeout before continuing. if (_checkTimeout) { DoCheckTimeout(timeoutOccursAt); } } } // No match was found. return NoMatchExists; } /// <summary> /// Workhorse inner loop for <see cref="FindFinalStatePosition"/>. Consumes the <paramref name="input"/> character by character, /// starting at <paramref name="i"/>, for each character transitioning from one state in the DFA or NFA graph to the next state, /// lazily building out the graph as needed. /// </summary> /// <remarks> /// The <typeparamref name="TStateHandler"/> supplies the actual transitioning logic, controlling whether processing is /// performed in DFA mode or in NFA mode. However, it expects <paramref name="currentState"/> to be configured to match, /// so for example if <typeparamref name="TStateHandler"/> is a <see cref="DfaStateHandler"/>, it expects the <paramref name="currentState"/>'s /// <see cref="CurrentState.DfaState"/> to be non-null and its <see cref="CurrentState.NfaState"/> to be null; vice versa for /// <see cref="NfaStateHandler"/>. /// </remarks> /// <returns> /// A positive value if iteration completed because it reached a nullable or deadend state. /// 0 if iteration completed because we reached an initial state. /// A negative value if iteration completed because we ran out of input or we failed to transition. /// </returns> private int FindFinalStatePositionDeltas<TStateHandler>(SymbolicRegexBuilder<TSetType> builder, ReadOnlySpan<char> input, ref int i, ref CurrentState currentState, ref int matchLength, out int finalStatePosition) where TStateHandler : struct, IStateHandler { // To avoid frequent reads/writes to ref values, make and operate on local copies, which we then copy back once before returning. int pos = i; CurrentState state = currentState; // Loop through each character in the input, transitioning from state to state for each. while ((uint)pos < (uint)input.Length && TryTakeTransition<TStateHandler>(builder, input, pos, ref state)) { // We successfully transitioned for the character at index i. If the new state is nullable for // the next character, meaning it accepts the empty string, we found a final state and are done! if (TStateHandler.IsNullable(ref state, GetCharKind(input, pos + 1))) { // Check whether there's a fixed-length marker for the current state. If there is, we can // use that length to optimize subsequent matching phases. matchLength = TStateHandler.FixedLength(ref state); currentState = state; i = pos; finalStatePosition = pos; return 1; } // If the new state is a dead end, such that we didn't match and we can't transition anywhere // else, then no match exists. if (TStateHandler.IsDeadend(ref state)) { currentState = state; i = pos; finalStatePosition = NoMatchExists; return 1; } // We successfully transitioned, so update our current input index to match. pos++; // Now that currentState and our position are coherent, check if currentState represents an initial state. // If it does, we exit out in order to allow our find optimizations to kick in to hopefully more quickly // find the next possible starting location. if (TStateHandler.IsInitialState(ref state)) { currentState = state; i = pos; finalStatePosition = 0; return 0; } } currentState = state; i = pos; finalStatePosition = 0; return -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private uint GetCharKind(ReadOnlySpan<char> input, int i) { return !_pattern._info.ContainsSomeAnchor ? CharKind.General : // The previous character kind is irrelevant when anchors are not used. GetCharKindWithAnchor(input, i); uint GetCharKindWithAnchor(ReadOnlySpan<char> input, int i) { Debug.Assert(_asciiCharKinds is not null); if ((uint)i >= (uint)input.Length) { return CharKind.BeginningEnd; } char nextChar = input[i]; if (nextChar == '\n') { return _builder._newLinePredicate.Equals(_builder._solver.False) ? 0 : // ignore \n i == 0 || i == input.Length - 1 ? CharKind.NewLineS : // very first or very last \n. Detection of very first \n is needed for rev(\Z). CharKind.Newline; } uint[] asciiCharKinds = _asciiCharKinds; return nextChar < (uint)asciiCharKinds.Length ? asciiCharKinds[nextChar] : _builder._solver.And(GetMinterm(nextChar), _builder._wordLetterPredicateForAnchors).Equals(_builder._solver.False) ? 0 : //apply the wordletter predicate to compute the kind of the next character CharKind.WordLetter; } } /// <summary>Stores additional data for tracking capture start and end positions.</summary> /// <remarks>The NFA simulation based third phase has one of these for each current state in the current set of live states.</remarks> internal struct Registers { public Registers(int[] captureStarts, int[] captureEnds) { CaptureStarts = captureStarts; CaptureEnds = captureEnds; } public int[] CaptureStarts { get; set; } public int[] CaptureEnds { get; set; } /// <summary> /// Applies a list of effects in order to these registers at the provided input position. The order of effects /// should not matter though, as multiple effects to the same capture start or end do not arise. /// </summary> /// <param name="effects">list of effects to be applied</param> /// <param name="pos">the current input position to record</param> public void ApplyEffects(List<DerivativeEffect> effects, int pos) { foreach (DerivativeEffect effect in effects) { ApplyEffect(effect, pos); } } /// <summary> /// Apply a single effect to these registers at the provided input position. /// </summary> /// <param name="effect">the effecto to be applied</param> /// <param name="pos">the current input position to record</param> public void ApplyEffect(DerivativeEffect effect, int pos) { switch (effect.Kind) { case DerivativeEffectKind.CaptureStart: CaptureStarts[effect.CaptureNumber] = pos; break; case DerivativeEffectKind.CaptureEnd: CaptureEnds[effect.CaptureNumber] = pos; break; } } /// <summary> /// Make a copy of this set of registers. /// </summary> /// <returns>Registers pointing to copies of this set of registers</returns> public Registers Clone() => new Registers((int[])CaptureStarts.Clone(), (int[])CaptureEnds.Clone()); /// <summary> /// Copy register values from another set of registers, possibly allocating new arrays if they were not yet allocated. /// </summary> /// <param name="other">the registers to copy from</param> public void Assign(Registers other) { if (CaptureStarts is not null && CaptureEnds is not null) { Debug.Assert(CaptureStarts.Length == other.CaptureStarts.Length); Debug.Assert(CaptureEnds.Length == other.CaptureEnds.Length); Array.Copy(other.CaptureStarts, CaptureStarts, CaptureStarts.Length); Array.Copy(other.CaptureEnds, CaptureEnds, CaptureEnds.Length); } else { CaptureStarts = (int[])other.CaptureStarts.Clone(); CaptureEnds = (int[])other.CaptureEnds.Clone(); } } } /// <summary> /// Per thread data to be held by the regex runner and passed into every call to FindMatch. This is used to /// avoid repeated memory allocation. /// </summary> internal sealed class PerThreadData { public readonly NfaMatchingState NfaState; /// <summary>Maps used for the capturing third phase.</summary> public readonly SparseIntMap<Registers>? Current, Next; /// <summary>Registers used for the capturing third phase.</summary> public readonly Registers InitialRegisters; public PerThreadData(SymbolicRegexBuilder<TSetType> builder, int capsize) { NfaState = new NfaMatchingState(builder); // Only create data used for capturing mode if there are subcaptures if (capsize > 1) { Current = new(); Next = new(); InitialRegisters = new Registers(new int[capsize], new int[capsize]); } } } /// <summary>Stores the state that represents a current state in NFA mode.</summary> /// <remarks>The entire state is composed of a list of individual states.</remarks> internal sealed class NfaMatchingState { /// <summary>The associated builder used to lazily add new DFA or NFA nodes to the graph.</summary> public readonly SymbolicRegexBuilder<TSetType> Builder; /// <summary>Ordered set used to store the current NFA states.</summary> /// <remarks>The value is unused. The type is used purely for its keys.</remarks> public SparseIntMap<int> NfaStateSet = new(); /// <summary>Scratch set to swap with <see cref="NfaStateSet"/> on each transition.</summary> /// <remarks> /// On each transition, <see cref="NfaStateSetScratch"/> is cleared and filled with the next /// states computed from the current states in <see cref="NfaStateSet"/>, and then the sets /// are swapped so the scratch becomes the current and the current becomes the scratch. /// </remarks> public SparseIntMap<int> NfaStateSetScratch = new(); /// <summary>Create the instance.</summary> /// <remarks>New instances should only be created once per runner.</remarks> public NfaMatchingState(SymbolicRegexBuilder<TSetType> builder) => Builder = builder; /// <summary>Resets this NFA state to represent the supplied DFA state.</summary> /// <param name="dfaMatchingState">The DFA state to use to initialize the NFA state.</param> public void InitializeFrom(DfaMatchingState<TSetType> dfaMatchingState) { NfaStateSet.Clear(); // If the DFA state is a union of multiple DFA states, loop through all of them // adding an NFA state for each. if (dfaMatchingState.Node.Kind is SymbolicRegexNodeKind.Or) { Debug.Assert(dfaMatchingState.Node._alts is not null); foreach (SymbolicRegexNode<TSetType> node in dfaMatchingState.Node._alts) { // Create (possibly new) NFA states for all the members. // Add their IDs to the current set of NFA states and into the list. int nfaState = Builder.CreateNfaState(node, dfaMatchingState.PrevCharKind); NfaStateSet.Add(nfaState, out _); } } else { // Otherwise, just add an NFA state for the singular DFA state. SymbolicRegexNode<TSetType> node = dfaMatchingState.Node; int nfaState = Builder.CreateNfaState(node, dfaMatchingState.PrevCharKind); NfaStateSet.Add(nfaState, out _); } } } /// <summary>Represents a current state in a DFA or NFA graph walk while processing a regular expression.</summary> /// <remarks>This is a discriminated union between a DFA state and an NFA state. One and only one will be non-null.</remarks> private struct CurrentState { /// <summary>Initializes the state as a DFA state.</summary> public CurrentState(DfaMatchingState<TSetType> dfaState) { DfaState = dfaState; NfaState = null; } /// <summary>Initializes the state as an NFA state.</summary> public CurrentState(NfaMatchingState nfaState) { DfaState = null; NfaState = nfaState; } /// <summary>The DFA state.</summary> public DfaMatchingState<TSetType>? DfaState; /// <summary>The NFA state.</summary> public NfaMatchingState? NfaState; } /// <summary>Represents a set of routines for operating over a <see cref="CurrentState"/>.</summary> private interface IStateHandler { #pragma warning disable CA2252 // This API requires opting into preview features public static abstract bool StartsWithLineAnchor(ref CurrentState state); public static abstract bool IsNullable(ref CurrentState state, uint nextCharKind); public static abstract bool IsDeadend(ref CurrentState state); public static abstract int FixedLength(ref CurrentState state); public static abstract bool IsInitialState(ref CurrentState state); public static abstract bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId); #pragma warning restore CA2252 // This API requires opting into preview features } /// <summary>An <see cref="IStateHandler"/> for operating over <see cref="CurrentState"/> instances configured as DFA states.</summary> private readonly struct DfaStateHandler : IStateHandler { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWithLineAnchor(ref CurrentState state) => state.DfaState!.StartsWithLineAnchor; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullable(ref CurrentState state, uint nextCharKind) => state.DfaState!.IsNullable(nextCharKind); /// <summary>Gets whether this is a dead-end state, meaning there are no transitions possible out of the state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDeadend(ref CurrentState state) => state.DfaState!.IsDeadend; /// <summary>Gets the length of any fixed-length marker that exists for this state, or -1 if there is none.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int FixedLength(ref CurrentState state) => state.DfaState!.FixedLength; /// <summary>Gets whether this is an initial state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInitialState(ref CurrentState state) => state.DfaState!.IsInitialState; /// <summary>Take the transition to the next DFA state.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId) { Debug.Assert(state.DfaState is not null, $"Expected non-null {nameof(state.DfaState)}."); Debug.Assert(state.NfaState is null, $"Expected null {nameof(state.NfaState)}."); Debug.Assert(builder._delta is not null); // Get the current state. DfaMatchingState<TSetType> dfaMatchingState = state.DfaState!; // Use the mintermId for the character being read to look up which state to transition to. // If that state has already been materialized, move to it, and we're done. If that state // hasn't been materialized, try to create it; if we can, move to it, and we're done. int dfaOffset = (dfaMatchingState.Id << builder._mintermsLog) | mintermId; DfaMatchingState<TSetType>? nextState = builder._delta[dfaOffset]; if (nextState is not null || builder.TryCreateNewTransition(dfaMatchingState, mintermId, dfaOffset, checkThreshold: true, out nextState)) { // There was an existing state for this transition or we were able to create one. Move to it and // return that we're still operating as a DFA and can keep going. state.DfaState = nextState; return true; } return false; } } /// <summary>An <see cref="IStateHandler"/> for operating over <see cref="CurrentState"/> instances configured as NFA states.</summary> private readonly struct NfaStateHandler : IStateHandler { /// <summary>Check if any underlying core state starts with a line anchor.</summary> public static bool StartsWithLineAnchor(ref CurrentState state) { SymbolicRegexBuilder<TSetType> builder = state.NfaState!.Builder; foreach (ref KeyValuePair<int, int> nfaState in CollectionsMarshal.AsSpan(state.NfaState!.NfaStateSet.Values)) { if (builder.GetCoreState(nfaState.Key).StartsWithLineAnchor) { return true; } } return false; } /// <summary>Check if any underlying core state is nullable.</summary> public static bool IsNullable(ref CurrentState state, uint nextCharKind) { SymbolicRegexBuilder<TSetType> builder = state.NfaState!.Builder; foreach (ref KeyValuePair<int, int> nfaState in CollectionsMarshal.AsSpan(state.NfaState!.NfaStateSet.Values)) { if (builder.GetCoreState(nfaState.Key).IsNullable(nextCharKind)) { return true; } } return false; } /// <summary>Gets whether this is a dead-end state, meaning there are no transitions possible out of the state.</summary> /// <remarks>In NFA mode, an empty set of states means that it is a dead end.</remarks> public static bool IsDeadend(ref CurrentState state) => state.NfaState!.NfaStateSet.Count == 0; /// <summary>Gets the length of any fixed-length marker that exists for this state, or -1 if there is none.</summary> /// <summary>In NFA mode, there are no fixed-length markers.</summary> public static int FixedLength(ref CurrentState state) => -1; /// <summary>Gets whether this is an initial state.</summary> /// <summary>In NFA mode, no set of states qualifies as an initial state.</summary> public static bool IsInitialState(ref CurrentState state) => false; /// <summary>Take the transition to the next NFA state.</summary> public static bool TakeTransition(SymbolicRegexBuilder<TSetType> builder, ref CurrentState state, int mintermId) { Debug.Assert(state.DfaState is null, $"Expected null {nameof(state.DfaState)}."); Debug.Assert(state.NfaState is not null, $"Expected non-null {nameof(state.NfaState)}."); NfaMatchingState nfaState = state.NfaState!; // Grab the sets, swapping the current active states set with the scratch set. SparseIntMap<int> nextStates = nfaState.NfaStateSetScratch; SparseIntMap<int> sourceStates = nfaState.NfaStateSet; nfaState.NfaStateSet = nextStates; nfaState.NfaStateSetScratch = sourceStates; // Compute the set of all unique next states from the current source states and the mintermId. nextStates.Clear(); if (sourceStates.Count == 1) { // We have a single source state. We know its next states are already deduped, // so we can just add them directly to the destination states list. foreach (int nextState in GetNextStates(sourceStates.Values[0].Key, mintermId, builder)) { nextStates.Add(nextState, out _); } } else { // We have multiple source states, so we need to potentially dedup across each of // their next states. For each source state, get its next states, adding each into // our set (which exists purely for deduping purposes), and if we successfully added // to the set, then add the known-unique state to the destination list. foreach (ref KeyValuePair<int, int> sourceState in CollectionsMarshal.AsSpan(sourceStates.Values)) { foreach (int nextState in GetNextStates(sourceState.Key, mintermId, builder)) { nextStates.Add(nextState, out _); } } } return true; [MethodImpl(MethodImplOptions.AggressiveInlining)] static int[] GetNextStates(int sourceState, int mintermId, SymbolicRegexBuilder<TSetType> builder) { // Calculate the offset into the NFA transition table. int nfaOffset = (sourceState << builder._mintermsLog) | mintermId; // Get the next NFA state. return builder._nfaDelta[nfaOffset] ?? builder.CreateNewNfaTransition(sourceState, mintermId, nfaOffset); } } } #if DEBUG public override void SaveDGML(TextWriter writer, int bound, bool hideStateInfo, bool addDotStar, bool inReverse, bool onlyDFAinfo, int maxLabelLength, bool asNFA) { var graph = new DGML.RegexAutomaton<TSetType>(this, bound, addDotStar, inReverse, asNFA); var dgml = new DGML.DgmlWriter(writer, hideStateInfo, maxLabelLength, onlyDFAinfo); dgml.Write(graph); } public override IEnumerable<string> GenerateRandomMembers(int k, int randomseed, bool negative) => new SymbolicRegexSampler<TSetType>(_pattern, randomseed, negative).GenerateRandomMembers(k); #endif } }
1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexRunnerFactory.cs
// 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.Globalization; namespace System.Text.RegularExpressions.Symbolic { /// <summary><see cref="RegexRunnerFactory"/> for symbolic regexes.</summary> internal sealed class SymbolicRegexRunnerFactory : RegexRunnerFactory { /// <summary>A SymbolicRegexMatcher of either ulong or BV depending on the number of minterms.</summary> internal readonly SymbolicRegexMatcher _matcher; /// <summary>Initializes the factory.</summary> public SymbolicRegexRunnerFactory(RegexTree regexTree, RegexOptions options, TimeSpan matchTimeout, CultureInfo culture) { // RightToLeft and ECMAScript are currently not supported in conjunction with NonBacktracking. if ((options & (RegexOptions.RightToLeft | RegexOptions.ECMAScript)) != 0) { throw new NotSupportedException( SR.Format(SR.NotSupported_NonBacktrackingConflictingOption, (options & RegexOptions.RightToLeft) != 0 ? nameof(RegexOptions.RightToLeft) : nameof(RegexOptions.ECMAScript))); } var converter = new RegexNodeConverter(culture, regexTree.CaptureNumberSparseMapping); CharSetSolver solver = CharSetSolver.Instance; SymbolicRegexNode<BDD> root = converter.ConvertToSymbolicRegexNode(regexTree.Root, tryCreateFixedLengthMarker: true); BDD[] minterms = root.ComputeMinterms(); if (minterms.Length > 64) { // Use BV to represent a predicate var algBV = new BVAlgebra(solver, minterms); var builderBV = new SymbolicRegexBuilder<BV>(algBV) { // The default constructor sets the following predicates to False; this update happens after the fact. // It depends on whether anchors where used in the regex whether the predicates are actually different from False. _wordLetterPredicateForAnchors = algBV.ConvertFromCharSet(solver, converter._builder._wordLetterPredicateForAnchors), _newLinePredicate = algBV.ConvertFromCharSet(solver, converter._builder._newLinePredicate) }; // Convert the BDD-based AST to BV-based AST SymbolicRegexNode<BV> rootBV = converter._builder.Transform(root, builderBV, bdd => builderBV._solver.ConvertFromCharSet(solver, bdd)); _matcher = new SymbolicRegexMatcher<BV>(rootBV, regexTree, minterms, matchTimeout); } else { // Use ulong to represent a predicate var alg64 = new BV64Algebra(solver, minterms); var builder64 = new SymbolicRegexBuilder<ulong>(alg64) { // The default constructor sets the following predicates to False, this update happens after the fact // It depends on whether anchors where used in the regex whether the predicates are actually different from False _wordLetterPredicateForAnchors = alg64.ConvertFromCharSet(solver, converter._builder._wordLetterPredicateForAnchors), _newLinePredicate = alg64.ConvertFromCharSet(solver, converter._builder._newLinePredicate) }; // Convert the BDD-based AST to ulong-based AST SymbolicRegexNode<ulong> root64 = converter._builder.Transform(root, builder64, bdd => builder64._solver.ConvertFromCharSet(solver, bdd)); _matcher = new SymbolicRegexMatcher<ulong>(root64, regexTree, minterms, matchTimeout); } } /// <summary>Creates a <see cref="RegexRunner"/> object.</summary> protected internal override RegexRunner CreateInstance() => _matcher is SymbolicRegexMatcher<ulong> srmUInt64 ? new Runner<ulong>(srmUInt64) : new Runner<BV>((SymbolicRegexMatcher<BV>)_matcher); /// <summary>Runner type produced by this factory.</summary> /// <remarks> /// The wrapped <see cref="SymbolicRegexMatcher"/> is itself thread-safe and can be shared across /// all runner instances, but the runner itself has state (e.g. for captures, positions, etc.) /// and must not be shared between concurrent uses. /// </remarks> private sealed class Runner<TSetType> : RegexRunner where TSetType : notnull { /// <summary>The matching engine.</summary> /// <remarks>The matcher is stateless and may be shared by any number of threads executing concurrently.</remarks> private readonly SymbolicRegexMatcher<TSetType> _matcher; /// <summary>Runner-specific data to pass to the matching engine.</summary> /// <remarks>This state is per runner and is thus only used by one thread at a time.</remarks> private readonly SymbolicRegexMatcher<TSetType>.PerThreadData _perThreadData; internal Runner(SymbolicRegexMatcher<TSetType> matcher) { _matcher = matcher; _perThreadData = matcher.CreatePerThreadData(); } protected internal override void Scan(ReadOnlySpan<char> text) { // Perform the match. SymbolicMatch pos = _matcher.FindMatch(quick, text, runtextpos, _perThreadData); // Transfer the result back to the RegexRunner state. if (pos.Success) { // If we successfully matched, capture the match, and then jump the current position to the end of the match. int start = pos.Index; int end = start + pos.Length; if (!quick && pos.CaptureStarts != null) { Debug.Assert(pos.CaptureEnds != null); Debug.Assert(pos.CaptureStarts.Length == pos.CaptureEnds.Length); for (int cap = 0; cap < pos.CaptureStarts.Length; ++cap) { if (pos.CaptureStarts[cap] >= 0) { Debug.Assert(pos.CaptureEnds[cap] >= pos.CaptureStarts[cap]); Capture(cap, pos.CaptureStarts[cap], pos.CaptureEnds[cap]); } } } else { Capture(0, start, end); } runtextpos = end; } else { // If we failed to find a match in the entire remainder of the input, skip the current position to the end. // The calling scan loop will then exit. runtextpos = runtextend; } } } } }
// 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.Globalization; namespace System.Text.RegularExpressions.Symbolic { /// <summary><see cref="RegexRunnerFactory"/> for symbolic regexes.</summary> internal sealed class SymbolicRegexRunnerFactory : RegexRunnerFactory { /// <summary>A SymbolicRegexMatcher of either ulong or <see cref="BitVector"/> depending on the number of minterms.</summary> internal readonly SymbolicRegexMatcher _matcher; /// <summary>Initializes the factory.</summary> public SymbolicRegexRunnerFactory(RegexTree regexTree, RegexOptions options, TimeSpan matchTimeout, CultureInfo culture) { // RightToLeft and ECMAScript are currently not supported in conjunction with NonBacktracking. if ((options & (RegexOptions.RightToLeft | RegexOptions.ECMAScript)) != 0) { throw new NotSupportedException( SR.Format(SR.NotSupported_NonBacktrackingConflictingOption, (options & RegexOptions.RightToLeft) != 0 ? nameof(RegexOptions.RightToLeft) : nameof(RegexOptions.ECMAScript))); } var converter = new RegexNodeConverter(culture, regexTree.CaptureNumberSparseMapping); CharSetSolver solver = CharSetSolver.Instance; SymbolicRegexNode<BDD> root = converter.ConvertToSymbolicRegexNode(regexTree.Root, tryCreateFixedLengthMarker: true); BDD[] minterms = root.ComputeMinterms(); if (minterms.Length > 64) { // Use BitVector to represent a predicate var algebra = new BitVectorAlgebra(solver, minterms); var builder = new SymbolicRegexBuilder<BitVector>(algebra) { // The default constructor sets the following predicates to False; this update happens after the fact. // It depends on whether anchors where used in the regex whether the predicates are actually different from False. _wordLetterPredicateForAnchors = algebra.ConvertFromCharSet(solver, converter._builder._wordLetterPredicateForAnchors), _newLinePredicate = algebra.ConvertFromCharSet(solver, converter._builder._newLinePredicate) }; // Convert the BDD-based AST to BitVector-based AST SymbolicRegexNode<BitVector> rootNode = converter._builder.Transform(root, builder, bdd => builder._solver.ConvertFromCharSet(solver, bdd)); _matcher = new SymbolicRegexMatcher<BitVector>(rootNode, regexTree, minterms, matchTimeout); } else { // Use ulong to represent a predicate var algebra = new BitVector64Algebra(solver, minterms); var builder = new SymbolicRegexBuilder<ulong>(algebra) { // The default constructor sets the following predicates to False, this update happens after the fact // It depends on whether anchors where used in the regex whether the predicates are actually different from False _wordLetterPredicateForAnchors = algebra.ConvertFromCharSet(solver, converter._builder._wordLetterPredicateForAnchors), _newLinePredicate = algebra.ConvertFromCharSet(solver, converter._builder._newLinePredicate) }; // Convert the BDD-based AST to ulong-based AST SymbolicRegexNode<ulong> rootNode = converter._builder.Transform(root, builder, bdd => builder._solver.ConvertFromCharSet(solver, bdd)); _matcher = new SymbolicRegexMatcher<ulong>(rootNode, regexTree, minterms, matchTimeout); } } /// <summary>Creates a <see cref="RegexRunner"/> object.</summary> protected internal override RegexRunner CreateInstance() => _matcher is SymbolicRegexMatcher<ulong> srmUInt64 ? new Runner<ulong>(srmUInt64) : new Runner<BitVector>((SymbolicRegexMatcher<BitVector>)_matcher); /// <summary>Runner type produced by this factory.</summary> /// <remarks> /// The wrapped <see cref="SymbolicRegexMatcher"/> is itself thread-safe and can be shared across /// all runner instances, but the runner itself has state (e.g. for captures, positions, etc.) /// and must not be shared between concurrent uses. /// </remarks> private sealed class Runner<TSetType> : RegexRunner where TSetType : notnull { /// <summary>The matching engine.</summary> /// <remarks>The matcher is stateless and may be shared by any number of threads executing concurrently.</remarks> private readonly SymbolicRegexMatcher<TSetType> _matcher; /// <summary>Runner-specific data to pass to the matching engine.</summary> /// <remarks>This state is per runner and is thus only used by one thread at a time.</remarks> private readonly SymbolicRegexMatcher<TSetType>.PerThreadData _perThreadData; internal Runner(SymbolicRegexMatcher<TSetType> matcher) { _matcher = matcher; _perThreadData = matcher.CreatePerThreadData(); } protected internal override void Scan(ReadOnlySpan<char> text) { // Perform the match. SymbolicMatch pos = _matcher.FindMatch(quick, text, runtextpos, _perThreadData); // Transfer the result back to the RegexRunner state. if (pos.Success) { // If we successfully matched, capture the match, and then jump the current position to the end of the match. int start = pos.Index; int end = start + pos.Length; if (!quick && pos.CaptureStarts != null) { Debug.Assert(pos.CaptureEnds != null); Debug.Assert(pos.CaptureStarts.Length == pos.CaptureEnds.Length); for (int cap = 0; cap < pos.CaptureStarts.Length; ++cap) { if (pos.CaptureStarts[cap] >= 0) { Debug.Assert(pos.CaptureEnds[cap] >= pos.CaptureStarts[cap]); Capture(cap, pos.CaptureStarts[cap], pos.CaptureEnds[cap]); } } } else { Capture(0, start, end); } runtextpos = end; } else { // If we failed to find a match in the entire remainder of the input, skip the current position to the end. // The calling scan loop will then exit. runtextpos = runtextend; } } } } }
1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexSampler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if DEBUG using System.Collections.Generic; using System.Diagnostics; namespace System.Text.RegularExpressions.Symbolic { internal sealed class SymbolicRegexSampler<S> where S : notnull { private Random _random; private SymbolicRegexNode<S> _root; /// <summary>The used random seed</summary> public int RandomSeed { get; private set; } private BDD _asciiWordCharacters; private BDD _asciiNonWordCharacters; // omits all characters before ' ' private BDD _ascii; // omits all characters before ' ' private ICharAlgebra<S> _solver; public SymbolicRegexSampler(SymbolicRegexNode<S> root, int randomseed, bool negative) { _root = negative ? root._builder.Not(root) : root; // Treat 0 as no seed and instead choose a random seed randomly RandomSeed = randomseed == 0 ? new Random().Next() : randomseed; _random = new Random(RandomSeed); _solver = root._builder._solver; CharSetSolver bddSolver = CharSetSolver.Instance; _asciiWordCharacters = bddSolver.Or(new BDD[] { bddSolver.RangeConstraint('A', 'Z'), bddSolver.RangeConstraint('a', 'z'), bddSolver.CharConstraint('_'), bddSolver.RangeConstraint('0', '9')}); // Visible ASCII range for input character generation _ascii = bddSolver.RangeConstraint('\x20', '\x7E'); _asciiNonWordCharacters = bddSolver.And(_ascii, bddSolver.Not(_asciiWordCharacters)); } /// <summary>Generates up to k random strings accepted by the regex</summary> public IEnumerable<string> GenerateRandomMembers(int k) { for (int i = 0; i < k; i++) { // Holds the generated input so far StringBuilder input_so_far = new(); // Initially there is no previous character // Here one could also consider previous characters for example for \b, \B, and ^ anchors // and initialize input_so_far accordingly uint prevCharKind = CharKind.BeginningEnd; // This flag is set to false in the unlikely situation that generation ends up in a dead-end bool generationSucceeded = true; // Current set of states reached initially contains just the root List<SymbolicRegexNode<S>> states = new(); states.Add(_root); // Used for end suffixes List<string> possible_endings = new(); List<SymbolicRegexNode<S>> nextStates = new(); while (true) { Debug.Assert(states.Count > 0); if (CanBeFinal(states)) { // Unconditionally final state or end of the input due to \Z anchor for example if (IsFinal(states) || IsFinal(states, CharKind.Context(prevCharKind, CharKind.BeginningEnd))) { possible_endings.Add(""); } // End of line due to end-of-line anchor if (IsFinal(states, CharKind.Context(prevCharKind, CharKind.Newline))) { possible_endings.Add("\n"); } // Related to wordborder due to \b or \B if (IsFinal(states, CharKind.Context(prevCharKind, CharKind.WordLetter))) { possible_endings.Add(ChooseChar(_asciiWordCharacters).ToString()); } // Related to wordborder due to \b or \B if (IsFinal(states, CharKind.Context(prevCharKind, CharKind.General))) { possible_endings.Add(ChooseChar(_asciiNonWordCharacters).ToString()); } } // Choose to stop here based on a coin-toss if (possible_endings.Count > 0 && ChooseRandomlyTrueOrFalse()) { //Choose some suffix that allows some anchor (if any) to be nullable input_so_far.Append(Choose(possible_endings)); break; } SymbolicRegexNode<S> state = Choose(states); char c = '\0'; uint cKind = 0; // Observe that state.CreateDerivative() can be a deadend List<(S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>)> paths = new(state.CreateDerivative().EnumeratePaths(_solver.True)); if (paths.Count > 0) { (S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path = Choose(paths); // Consider a random path from some random state in states and // select a random member of the predicate on that path c = ChooseChar(ToBDD(path.Item1)); // Map the character back into the corresponding character constraint of the solver S c_pred = _solver.CharConstraint(c); // Determine the character kind of c cKind = IsNewline(c_pred) ? CharKind.Newline : (IsWordchar(c_pred) ? CharKind.WordLetter : CharKind.General); // Construct the combined context of previous and c kind uint context = CharKind.Context(prevCharKind, cKind); // Step into the next set of states nextStates.AddRange(Step(states, c_pred, context)); } // In the case that there are no next states: stop here if (nextStates.Count == 0) { if (possible_endings.Count > 0) { input_so_far.Append(Choose(possible_endings)); } else { // Ending up here is unlikely but possible for example for infeasible patterns such as @"no\bway" // or due to poor choice of c -- no anchor is enabled -- so this is a deadend generationSucceeded = false; } break; } input_so_far.Append(c); states.Clear(); possible_endings.Clear(); List<SymbolicRegexNode<S>> tmp = states; states = nextStates; nextStates = tmp; prevCharKind = cKind; } if (generationSucceeded) { yield return input_so_far.ToString(); } } } private IEnumerable<SymbolicRegexNode<S>> Step(List<SymbolicRegexNode<S>> states, S pred, uint context) { HashSet<SymbolicRegexNode<S>> seen = new(); foreach (SymbolicRegexNode<S> state in states) { foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in state.CreateDerivative().EnumeratePaths(pred)) { // Either there are no anchors or else check that the anchors are nullable in the given context if (path.Item2 is null || path.Item2.IsNullableFor(context)) { // Omit repetitions from the enumeration if (seen.Add(path.Item3)) { yield return path.Item3; } } } } } private BDD ToBDD(S pred) => _solver.ConvertToCharSet(CharSetSolver.Instance, pred); private T Choose<T>(IList<T> elems) => elems[_random.Next(elems.Count)]; private char ChooseChar((uint, uint) pair) => (char)_random.Next((int)pair.Item1, (int)pair.Item2 + 1); private char ChooseChar(BDD bdd) { Debug.Assert(!bdd.IsEmpty); // Select characters from the visible ASCII range whenever possible BDD bdd1 = CharSetSolver.Instance.And(bdd, _ascii); return ChooseChar(Choose(CharSetSolver.Instance.ToRanges(bdd1.IsEmpty ? bdd : bdd1))); } private bool ChooseRandomlyTrueOrFalse() => _random.Next(100) < 50; /// <summary>Returns true if some state is unconditionally final</summary> private bool IsFinal(IEnumerable<SymbolicRegexNode<S>> states) { foreach (SymbolicRegexNode<S> state in states) { if (state.IsNullable) { return true; } } return false; } /// <summary>Returns true if some state can be final</summary> private bool CanBeFinal(IEnumerable<SymbolicRegexNode<S>> states) { foreach (SymbolicRegexNode<S> state in states) { if (state.CanBeNullable) { return true; } } return false; } /// <summary>Returns true if some state is final in the given context</summary> private bool IsFinal(IEnumerable<SymbolicRegexNode<S>> states, uint context) { foreach (SymbolicRegexNode<S> state in states) { if (state.IsNullableFor(context)) { return true; } } return false; } private bool IsWordchar(S pred) => _solver.IsSatisfiable(_solver.And(pred, _root._builder._wordLetterPredicateForAnchors)); private bool IsNewline(S pred) => _solver.IsSatisfiable(_solver.And(pred, _root._builder._newLinePredicate)); } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #if DEBUG using System.Collections.Generic; using System.Diagnostics; namespace System.Text.RegularExpressions.Symbolic { internal sealed class SymbolicRegexSampler<S> where S : notnull { private Random _random; private SymbolicRegexNode<S> _root; /// <summary>The used random seed</summary> public int RandomSeed { get; private set; } private BDD _asciiWordCharacters; private BDD _asciiNonWordCharacters; // omits all characters before ' ' private BDD _ascii; // omits all characters before ' ' private ICharAlgebra<S> _solver; public SymbolicRegexSampler(SymbolicRegexNode<S> root, int randomseed, bool negative) { _root = negative ? root._builder.Not(root) : root; // Treat 0 as no seed and instead choose a random seed randomly RandomSeed = randomseed == 0 ? new Random().Next() : randomseed; _random = new Random(RandomSeed); _solver = root._builder._solver; CharSetSolver bddSolver = CharSetSolver.Instance; _asciiWordCharacters = bddSolver.Or(new BDD[] { bddSolver.RangeConstraint('A', 'Z'), bddSolver.RangeConstraint('a', 'z'), bddSolver.CharConstraint('_'), bddSolver.RangeConstraint('0', '9')}); // Visible ASCII range for input character generation _ascii = bddSolver.RangeConstraint('\x20', '\x7E'); _asciiNonWordCharacters = bddSolver.And(_ascii, bddSolver.Not(_asciiWordCharacters)); } /// <summary>Generates up to k random strings accepted by the regex</summary> public IEnumerable<string> GenerateRandomMembers(int k) { for (int i = 0; i < k; i++) { // Holds the generated input so far StringBuilder input_so_far = new(); // Initially there is no previous character // Here one could also consider previous characters for example for \b, \B, and ^ anchors // and initialize input_so_far accordingly uint prevCharKind = CharKind.BeginningEnd; // This flag is set to false in the unlikely situation that generation ends up in a dead-end bool generationSucceeded = true; // Current set of states reached initially contains just the root List<SymbolicRegexNode<S>> states = new(); states.Add(_root); // Used for end suffixes List<string> possible_endings = new(); List<SymbolicRegexNode<S>> nextStates = new(); while (true) { Debug.Assert(states.Count > 0); if (CanBeFinal(states)) { // Unconditionally final state or end of the input due to \Z anchor for example if (IsFinal(states) || IsFinal(states, CharKind.Context(prevCharKind, CharKind.BeginningEnd))) { possible_endings.Add(""); } // End of line due to end-of-line anchor if (IsFinal(states, CharKind.Context(prevCharKind, CharKind.Newline))) { possible_endings.Add("\n"); } // Related to wordborder due to \b or \B if (IsFinal(states, CharKind.Context(prevCharKind, CharKind.WordLetter))) { possible_endings.Add(ChooseChar(_asciiWordCharacters).ToString()); } // Related to wordborder due to \b or \B if (IsFinal(states, CharKind.Context(prevCharKind, CharKind.General))) { possible_endings.Add(ChooseChar(_asciiNonWordCharacters).ToString()); } } // Choose to stop here based on a coin-toss if (possible_endings.Count > 0 && ChooseRandomlyTrueOrFalse()) { //Choose some suffix that allows some anchor (if any) to be nullable input_so_far.Append(Choose(possible_endings)); break; } SymbolicRegexNode<S> state = Choose(states); char c = '\0'; uint cKind = 0; // Observe that state.CreateDerivative() can be a deadend List<(S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>)> paths = new(state.CreateDerivative().EnumeratePaths(_solver.True)); if (paths.Count > 0) { (S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path = Choose(paths); // Consider a random path from some random state in states and // select a random member of the predicate on that path c = ChooseChar(ToBDD(path.Item1)); // Map the character back into the corresponding character constraint of the solver S c_pred = _solver.CharConstraint(c); // Determine the character kind of c cKind = IsNewline(c_pred) ? CharKind.Newline : (IsWordchar(c_pred) ? CharKind.WordLetter : CharKind.General); // Construct the combined context of previous and c kind uint context = CharKind.Context(prevCharKind, cKind); // Step into the next set of states nextStates.AddRange(Step(states, c_pred, context)); } // In the case that there are no next states: stop here if (nextStates.Count == 0) { if (possible_endings.Count > 0) { input_so_far.Append(Choose(possible_endings)); } else { // Ending up here is unlikely but possible for example for infeasible patterns such as @"no\bway" // or due to poor choice of c -- no anchor is enabled -- so this is a deadend generationSucceeded = false; } break; } input_so_far.Append(c); states.Clear(); possible_endings.Clear(); List<SymbolicRegexNode<S>> tmp = states; states = nextStates; nextStates = tmp; prevCharKind = cKind; } if (generationSucceeded) { yield return input_so_far.ToString(); } } } private IEnumerable<SymbolicRegexNode<S>> Step(List<SymbolicRegexNode<S>> states, S pred, uint context) { HashSet<SymbolicRegexNode<S>> seen = new(); foreach (SymbolicRegexNode<S> state in states) { foreach ((S, SymbolicRegexNode<S>?, SymbolicRegexNode<S>) path in state.CreateDerivative().EnumeratePaths(pred)) { // Either there are no anchors or else check that the anchors are nullable in the given context if (path.Item2 is null || path.Item2.IsNullableFor(context)) { // Omit repetitions from the enumeration if (seen.Add(path.Item3)) { yield return path.Item3; } } } } } private BDD ToBDD(S pred) => _solver.ConvertToCharSet(pred); private T Choose<T>(IList<T> elems) => elems[_random.Next(elems.Count)]; private char ChooseChar((uint, uint) pair) => (char)_random.Next((int)pair.Item1, (int)pair.Item2 + 1); private char ChooseChar(BDD bdd) { Debug.Assert(!bdd.IsEmpty); // Select characters from the visible ASCII range whenever possible BDD bdd1 = CharSetSolver.Instance.And(bdd, _ascii); return ChooseChar(Choose(CharSetSolver.Instance.ToRanges(bdd1.IsEmpty ? bdd : bdd1))); } private bool ChooseRandomlyTrueOrFalse() => _random.Next(100) < 50; /// <summary>Returns true if some state is unconditionally final</summary> private bool IsFinal(List<SymbolicRegexNode<S>> states) { foreach (SymbolicRegexNode<S> state in states) { if (state.IsNullable) { return true; } } return false; } /// <summary>Returns true if some state is final in the given context</summary> private bool IsFinal(List<SymbolicRegexNode<S>> states, uint context) { foreach (SymbolicRegexNode<S> state in states) { if (state.IsNullableFor(context)) { return true; } } return false; } /// <summary>Returns true if some state can be final</summary> private bool CanBeFinal(List<SymbolicRegexNode<S>> states) { foreach (SymbolicRegexNode<S> state in states) { if (state.CanBeNullable) { return true; } } return false; } private bool IsWordchar(S pred) => _solver.IsSatisfiable(_solver.And(pred, _root._builder._wordLetterPredicateForAnchors)); private bool IsNewline(S pred) => _solver.IsSatisfiable(_solver.And(pred, _root._builder._newLinePredicate)); } } #endif
1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/jit64/valuetypes/nullable/castclass/null/castclass-null012.cs
// 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; using System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((ValueType)(object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)(object)(ValueType)o) == null; } private static bool BoxUnboxToNQ(object o) { return ((ValueType)o) == null; } private static bool BoxUnboxToQ(object o) { return ((double?)(ValueType)o) == null; } private static int Main() { double? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
// 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; using System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((ValueType)(object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)(object)(ValueType)o) == null; } private static bool BoxUnboxToNQ(object o) { return ((ValueType)o) == null; } private static bool BoxUnboxToQ(object o) { return ((double?)(ValueType)o) == null; } private static int Main() { double? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Signatures/MethodSignature.cs
// 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.Immutable; using System.Reflection.Metadata; namespace System.Reflection.Metadata { /// <summary> /// Represents a method (definition, reference, or standalone) or property signature. /// In the case of properties, the signature matches that of a getter with a distinguishing <see cref="SignatureHeader"/>. /// </summary> public readonly struct MethodSignature<TType> { /// <summary> /// Represents the information in the leading byte of the signature (kind, calling convention, flags). /// </summary> public SignatureHeader Header { get; } /// <summary> /// Gets the method's return type. /// </summary> public TType ReturnType { get; } /// <summary> /// Gets the number of parameters that are required. Will be equal to the length <see cref="ParameterTypes"/> of /// unless this signature represents the standalone call site of a vararg method, in which case the entries /// extra entries in <see cref="ParameterTypes"/> are the types used for the optional parameters. /// </summary> public int RequiredParameterCount { get; } /// <summary> /// Gets the number of generic type parameters of the method. Will be 0 for non-generic methods. /// </summary> public int GenericParameterCount { get; } /// <summary> /// Gets the method's parameter types. /// </summary> public ImmutableArray<TType> ParameterTypes { get; } public MethodSignature(SignatureHeader header, TType returnType, int requiredParameterCount, int genericParameterCount, ImmutableArray<TType> parameterTypes) { Header = header; ReturnType = returnType; GenericParameterCount = genericParameterCount; RequiredParameterCount = requiredParameterCount; ParameterTypes = parameterTypes; } } }
// 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.Immutable; using System.Reflection.Metadata; namespace System.Reflection.Metadata { /// <summary> /// Represents a method (definition, reference, or standalone) or property signature. /// In the case of properties, the signature matches that of a getter with a distinguishing <see cref="SignatureHeader"/>. /// </summary> public readonly struct MethodSignature<TType> { /// <summary> /// Represents the information in the leading byte of the signature (kind, calling convention, flags). /// </summary> public SignatureHeader Header { get; } /// <summary> /// Gets the method's return type. /// </summary> public TType ReturnType { get; } /// <summary> /// Gets the number of parameters that are required. Will be equal to the length <see cref="ParameterTypes"/> of /// unless this signature represents the standalone call site of a vararg method, in which case the entries /// extra entries in <see cref="ParameterTypes"/> are the types used for the optional parameters. /// </summary> public int RequiredParameterCount { get; } /// <summary> /// Gets the number of generic type parameters of the method. Will be 0 for non-generic methods. /// </summary> public int GenericParameterCount { get; } /// <summary> /// Gets the method's parameter types. /// </summary> public ImmutableArray<TType> ParameterTypes { get; } public MethodSignature(SignatureHeader header, TType returnType, int requiredParameterCount, int genericParameterCount, ImmutableArray<TType> parameterTypes) { Header = header; ReturnType = returnType; GenericParameterCount = genericParameterCount; RequiredParameterCount = requiredParameterCount; ParameterTypes = parameterTypes; } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.IO.Pipelines/ref/System.IO.Pipelines.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.IO.Pipelines { public partial struct FlushResult { private int _dummyPrimitive; public FlushResult(bool isCanceled, bool isCompleted) { throw null; } public bool IsCanceled { get { throw null; } } public bool IsCompleted { get { throw null; } } } public partial interface IDuplexPipe { System.IO.Pipelines.PipeReader Input { get; } System.IO.Pipelines.PipeWriter Output { get; } } public sealed partial class Pipe { public Pipe() { } public Pipe(System.IO.Pipelines.PipeOptions options) { } public System.IO.Pipelines.PipeReader Reader { get { throw null; } } public System.IO.Pipelines.PipeWriter Writer { get { throw null; } } public void Reset() { } } public partial class PipeOptions { public PipeOptions(System.Buffers.MemoryPool<byte>? pool = null, System.IO.Pipelines.PipeScheduler? readerScheduler = null, System.IO.Pipelines.PipeScheduler? writerScheduler = null, long pauseWriterThreshold = (long)-1, long resumeWriterThreshold = (long)-1, int minimumSegmentSize = -1, bool useSynchronizationContext = true) { } public static System.IO.Pipelines.PipeOptions Default { get { throw null; } } public int MinimumSegmentSize { get { throw null; } } public long PauseWriterThreshold { get { throw null; } } public System.Buffers.MemoryPool<byte> Pool { get { throw null; } } public System.IO.Pipelines.PipeScheduler ReaderScheduler { get { throw null; } } public long ResumeWriterThreshold { get { throw null; } } public bool UseSynchronizationContext { get { throw null; } } public System.IO.Pipelines.PipeScheduler WriterScheduler { get { throw null; } } } public abstract partial class PipeReader { protected PipeReader() { } public abstract void AdvanceTo(System.SequencePosition consumed); public abstract void AdvanceTo(System.SequencePosition consumed, System.SequencePosition examined); public virtual System.IO.Stream AsStream(bool leaveOpen = false) { throw null; } public abstract void CancelPendingRead(); public abstract void Complete(System.Exception? exception = null); public virtual System.Threading.Tasks.ValueTask CompleteAsync(System.Exception? exception = null) { throw null; } public virtual System.Threading.Tasks.Task CopyToAsync(System.IO.Pipelines.PipeWriter destination, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.IO.Pipelines.PipeReader Create(System.Buffers.ReadOnlySequence<byte> sequence) { throw null; } public static System.IO.Pipelines.PipeReader Create(System.IO.Stream stream, System.IO.Pipelines.StreamPipeReaderOptions? readerOptions = null) { throw null; } [System.ObsoleteAttribute("OnWriterCompleted has been deprecated and may not be invoked on all implementations of PipeReader.")] public virtual void OnWriterCompleted(System.Action<System.Exception?, object?> callback, object? state) { } public abstract System.Threading.Tasks.ValueTask<System.IO.Pipelines.ReadResult> ReadAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public System.Threading.Tasks.ValueTask<System.IO.Pipelines.ReadResult> ReadAtLeastAsync(int minimumSize, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected virtual System.Threading.Tasks.ValueTask<System.IO.Pipelines.ReadResult> ReadAtLeastAsyncCore(int minimumSize, System.Threading.CancellationToken cancellationToken) { throw null; } public abstract bool TryRead(out System.IO.Pipelines.ReadResult result); } public abstract partial class PipeScheduler { protected PipeScheduler() { } public static System.IO.Pipelines.PipeScheduler Inline { get { throw null; } } public static System.IO.Pipelines.PipeScheduler ThreadPool { get { throw null; } } public abstract void Schedule(System.Action<object?> action, object? state); } public abstract partial class PipeWriter : System.Buffers.IBufferWriter<byte> { protected PipeWriter() { } public abstract void Advance(int bytes); public virtual System.IO.Stream AsStream(bool leaveOpen = false) { throw null; } public abstract void CancelPendingFlush(); public virtual bool CanGetUnflushedBytes => throw null; public abstract void Complete(System.Exception? exception = null); public virtual System.Threading.Tasks.ValueTask CompleteAsync(System.Exception? exception = null) { throw null; } protected internal virtual System.Threading.Tasks.Task CopyFromAsync(System.IO.Stream source, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.IO.Pipelines.PipeWriter Create(System.IO.Stream stream, System.IO.Pipelines.StreamPipeWriterOptions? writerOptions = null) { throw null; } public abstract System.Threading.Tasks.ValueTask<System.IO.Pipelines.FlushResult> FlushAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public abstract System.Memory<byte> GetMemory(int sizeHint = 0); public abstract System.Span<byte> GetSpan(int sizeHint = 0); [System.ObsoleteAttribute("OnReaderCompleted has been deprecated and may not be invoked on all implementations of PipeWriter.")] public virtual void OnReaderCompleted(System.Action<System.Exception?, object?> callback, object? state) { } public virtual long UnflushedBytes => throw null; public virtual System.Threading.Tasks.ValueTask<System.IO.Pipelines.FlushResult> WriteAsync(System.ReadOnlyMemory<byte> source, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public readonly partial struct ReadResult { private readonly object _dummy; private readonly int _dummyPrimitive; public ReadResult(System.Buffers.ReadOnlySequence<byte> buffer, bool isCanceled, bool isCompleted) { throw null; } public System.Buffers.ReadOnlySequence<byte> Buffer { get { throw null; } } public bool IsCanceled { get { throw null; } } public bool IsCompleted { get { throw null; } } } public static partial class StreamPipeExtensions { public static System.Threading.Tasks.Task CopyToAsync(this System.IO.Stream source, System.IO.Pipelines.PipeWriter destination, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class StreamPipeReaderOptions { public StreamPipeReaderOptions(System.Buffers.MemoryPool<byte>? pool, int bufferSize, int minimumReadSize, bool leaveOpen) { } public StreamPipeReaderOptions(System.Buffers.MemoryPool<byte>? pool = null, int bufferSize = -1, int minimumReadSize = -1, bool leaveOpen = false, bool useZeroByteReads = false) { } public int BufferSize { get { throw null; } } public bool LeaveOpen { get { throw null; } } public int MinimumReadSize { get { throw null; } } public System.Buffers.MemoryPool<byte> Pool { get { throw null; } } public bool UseZeroByteReads { get { throw null; } } } public partial class StreamPipeWriterOptions { public StreamPipeWriterOptions(System.Buffers.MemoryPool<byte>? pool = null, int minimumBufferSize = -1, bool leaveOpen = false) { } public bool LeaveOpen { get { throw null; } } public int MinimumBufferSize { get { throw null; } } public System.Buffers.MemoryPool<byte> Pool { get { throw null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ------------------------------------------------------------------------------ // Changes to this file must follow the https://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.IO.Pipelines { public partial struct FlushResult { private int _dummyPrimitive; public FlushResult(bool isCanceled, bool isCompleted) { throw null; } public bool IsCanceled { get { throw null; } } public bool IsCompleted { get { throw null; } } } public partial interface IDuplexPipe { System.IO.Pipelines.PipeReader Input { get; } System.IO.Pipelines.PipeWriter Output { get; } } public sealed partial class Pipe { public Pipe() { } public Pipe(System.IO.Pipelines.PipeOptions options) { } public System.IO.Pipelines.PipeReader Reader { get { throw null; } } public System.IO.Pipelines.PipeWriter Writer { get { throw null; } } public void Reset() { } } public partial class PipeOptions { public PipeOptions(System.Buffers.MemoryPool<byte>? pool = null, System.IO.Pipelines.PipeScheduler? readerScheduler = null, System.IO.Pipelines.PipeScheduler? writerScheduler = null, long pauseWriterThreshold = (long)-1, long resumeWriterThreshold = (long)-1, int minimumSegmentSize = -1, bool useSynchronizationContext = true) { } public static System.IO.Pipelines.PipeOptions Default { get { throw null; } } public int MinimumSegmentSize { get { throw null; } } public long PauseWriterThreshold { get { throw null; } } public System.Buffers.MemoryPool<byte> Pool { get { throw null; } } public System.IO.Pipelines.PipeScheduler ReaderScheduler { get { throw null; } } public long ResumeWriterThreshold { get { throw null; } } public bool UseSynchronizationContext { get { throw null; } } public System.IO.Pipelines.PipeScheduler WriterScheduler { get { throw null; } } } public abstract partial class PipeReader { protected PipeReader() { } public abstract void AdvanceTo(System.SequencePosition consumed); public abstract void AdvanceTo(System.SequencePosition consumed, System.SequencePosition examined); public virtual System.IO.Stream AsStream(bool leaveOpen = false) { throw null; } public abstract void CancelPendingRead(); public abstract void Complete(System.Exception? exception = null); public virtual System.Threading.Tasks.ValueTask CompleteAsync(System.Exception? exception = null) { throw null; } public virtual System.Threading.Tasks.Task CopyToAsync(System.IO.Pipelines.PipeWriter destination, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task CopyToAsync(System.IO.Stream destination, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.IO.Pipelines.PipeReader Create(System.Buffers.ReadOnlySequence<byte> sequence) { throw null; } public static System.IO.Pipelines.PipeReader Create(System.IO.Stream stream, System.IO.Pipelines.StreamPipeReaderOptions? readerOptions = null) { throw null; } [System.ObsoleteAttribute("OnWriterCompleted has been deprecated and may not be invoked on all implementations of PipeReader.")] public virtual void OnWriterCompleted(System.Action<System.Exception?, object?> callback, object? state) { } public abstract System.Threading.Tasks.ValueTask<System.IO.Pipelines.ReadResult> ReadAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public System.Threading.Tasks.ValueTask<System.IO.Pipelines.ReadResult> ReadAtLeastAsync(int minimumSize, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected virtual System.Threading.Tasks.ValueTask<System.IO.Pipelines.ReadResult> ReadAtLeastAsyncCore(int minimumSize, System.Threading.CancellationToken cancellationToken) { throw null; } public abstract bool TryRead(out System.IO.Pipelines.ReadResult result); } public abstract partial class PipeScheduler { protected PipeScheduler() { } public static System.IO.Pipelines.PipeScheduler Inline { get { throw null; } } public static System.IO.Pipelines.PipeScheduler ThreadPool { get { throw null; } } public abstract void Schedule(System.Action<object?> action, object? state); } public abstract partial class PipeWriter : System.Buffers.IBufferWriter<byte> { protected PipeWriter() { } public abstract void Advance(int bytes); public virtual System.IO.Stream AsStream(bool leaveOpen = false) { throw null; } public abstract void CancelPendingFlush(); public virtual bool CanGetUnflushedBytes => throw null; public abstract void Complete(System.Exception? exception = null); public virtual System.Threading.Tasks.ValueTask CompleteAsync(System.Exception? exception = null) { throw null; } protected internal virtual System.Threading.Tasks.Task CopyFromAsync(System.IO.Stream source, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.IO.Pipelines.PipeWriter Create(System.IO.Stream stream, System.IO.Pipelines.StreamPipeWriterOptions? writerOptions = null) { throw null; } public abstract System.Threading.Tasks.ValueTask<System.IO.Pipelines.FlushResult> FlushAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public abstract System.Memory<byte> GetMemory(int sizeHint = 0); public abstract System.Span<byte> GetSpan(int sizeHint = 0); [System.ObsoleteAttribute("OnReaderCompleted has been deprecated and may not be invoked on all implementations of PipeWriter.")] public virtual void OnReaderCompleted(System.Action<System.Exception?, object?> callback, object? state) { } public virtual long UnflushedBytes => throw null; public virtual System.Threading.Tasks.ValueTask<System.IO.Pipelines.FlushResult> WriteAsync(System.ReadOnlyMemory<byte> source, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public readonly partial struct ReadResult { private readonly object _dummy; private readonly int _dummyPrimitive; public ReadResult(System.Buffers.ReadOnlySequence<byte> buffer, bool isCanceled, bool isCompleted) { throw null; } public System.Buffers.ReadOnlySequence<byte> Buffer { get { throw null; } } public bool IsCanceled { get { throw null; } } public bool IsCompleted { get { throw null; } } } public static partial class StreamPipeExtensions { public static System.Threading.Tasks.Task CopyToAsync(this System.IO.Stream source, System.IO.Pipelines.PipeWriter destination, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class StreamPipeReaderOptions { public StreamPipeReaderOptions(System.Buffers.MemoryPool<byte>? pool, int bufferSize, int minimumReadSize, bool leaveOpen) { } public StreamPipeReaderOptions(System.Buffers.MemoryPool<byte>? pool = null, int bufferSize = -1, int minimumReadSize = -1, bool leaveOpen = false, bool useZeroByteReads = false) { } public int BufferSize { get { throw null; } } public bool LeaveOpen { get { throw null; } } public int MinimumReadSize { get { throw null; } } public System.Buffers.MemoryPool<byte> Pool { get { throw null; } } public bool UseZeroByteReads { get { throw null; } } } public partial class StreamPipeWriterOptions { public StreamPipeWriterOptions(System.Buffers.MemoryPool<byte>? pool = null, int minimumBufferSize = -1, bool leaveOpen = false) { } public bool LeaveOpen { get { throw null; } } public int MinimumBufferSize { get { throw null; } } public System.Buffers.MemoryPool<byte> Pool { get { throw null; } } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <FeatureGenericMath>false</FeatureGenericMath> <NoWarn>$(NoWarn),1718,SYSLIB0013</NoWarn> <TestRuntime>true</TestRuntime> <IncludeRemoteExecutor>true</IncludeRemoteExecutor> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser</TargetFrameworks> <Nullable>disable</Nullable> <!-- Disable nullability public only feature for NullabilityInfoContextTests --> <Features>$(Features.Replace('nullablePublicOnly', '')</Features> </PropertyGroup> <PropertyGroup> <DefineConstants Condition="'$(FeatureGenericMath)' == 'true'">$(DefineConstants);FEATURE_GENERIC_MATH</DefineConstants> </PropertyGroup> <ItemGroup> <RdXmlFile Include="default.rd.xml" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\EnumTypes.cs" Link="Common\System\EnumTypes.cs" /> <Compile Include="$(CommonTestPath)System\MockType.cs" Link="Common\System\MockType.cs" /> <Compile Include="$(CommonTestPath)System\Collections\CollectionAsserts.cs" Link="Common\System\Collections\CollectionAsserts.cs" /> <Compile Include="$(CommonTestPath)System\Collections\ICollection.Generic.Tests.cs" Link="Common\System\Collections\ICollection.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.Generic.Tests.cs" Link="Common\System\Collections\IEnumerable.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IList.Generic.Tests.cs" Link="Common\System\Collections\IList.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\TestBase.Generic.cs" Link="Common\System\Collections\TestBase.Generic.cs" /> <Compile Include="$(CommonTestPath)System\Collections\TestBase.NonGeneric.cs" Link="Common\System\Collections\TestBase.NonGeneric.cs" /> <Compile Include="$(CommonTestPath)Tests\System\StringTests.cs" Link="Common\System\StringTests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IDictionary.NonGeneric.Tests.cs" Link="Common\System\Collections\IDictionary.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IList.NonGeneric.Tests.cs" Link="Common\System\Collections\IList.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\ICollection.NonGeneric.Tests.cs" Link="Common\System\Collections\ICollection.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.NonGeneric.Tests.cs" Link="Common\System\Collections\IEnumerable.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)TestUtilities\System\DisableParallelization.cs" Link="Common\TestUtilities\System\DisableParallelization.cs" /> <Compile Include="Helpers.cs" /> <Compile Include="Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs" /> <Compile Include="Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs" /> <Compile Include="System\AccessViolationExceptionTests.cs" /> <Compile Include="System\ActivatorTests.cs" /> <Compile Include="System\ActivatorTests.Generic.cs" /> <Compile Include="System\AmbiguousImplementationExceptionTests.cs" /> <Compile Include="System\ArgumentExceptionTests.cs" /> <Compile Include="System\ArgumentNullExceptionTests.cs" /> <Compile Include="System\ArgumentOutOfRangeExceptionTests.cs" /> <Compile Include="System\ArithmeticExceptionTests.cs" /> <Compile Include="System\ArrayTests.cs" /> <Compile Include="System\ArrayEnumeratorTests.cs" /> <Compile Include="System\ArraySegmentTests.cs" /> <Compile Include="System\ArrayTypeMismatchExceptionTests.cs" /> <Compile Include="System\ApplicationExceptionTests.cs" /> <Compile Include="System\AttributeTests.cs" /> <Compile Include="System\Attributes.cs" /> <Compile Include="System\AttributeUsageAttributeTests.cs" /> <Compile Include="System\BadImageFormatExceptionTests.cs" /> <Compile Include="System\BooleanTests.cs" /> <Compile Include="System\BufferTests.cs" /> <Compile Include="System\ByteTests.cs" /> <Compile Include="System\CharTests.cs" /> <Compile Include="System\CLSCompliantAttributeTests.cs" /> <Compile Include="System\DateOnlyTests.cs" /> <Compile Include="System\DateTimeTests.cs" /> <Compile Include="System\DateTimeOffsetTests.cs" /> <Compile Include="System\DBNullTests.cs" /> <Compile Include="System\DecimalTests.cs" /> <Compile Include="System\DelegateTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\StringSyntaxAttributeTests.cs" /> <Compile Include="System\DivideByZeroExceptionTests.cs" /> <Compile Include="System\DoubleTests.cs" /> <Compile Include="System\DuplicateWaitObjectExceptionTests.cs" /> <Compile Include="System\EntryPointNotFoundExceptionTests.cs" /> <Compile Include="System\EnumTests.cs" /> <Compile Include="System\ExceptionTests.cs" /> <Compile Include="System\Exception.Helpers.cs" /> <Compile Include="System\ExecutionEngineExceptionTests.cs" /> <Compile Include="System\ExternalExceptionTests.cs" /> <Compile Include="System\EventArgsTests.cs" /> <Compile Include="System\FieldAccessExceptionTests.cs" /> <Compile Include="System\FlagsAttributeTests.cs" /> <Compile Include="System\FormattableStringTests.cs" /> <Compile Include="System\FormatExceptionTests.cs" /> <Compile Include="System\GCTests.cs" /> <Compile Include="System\GuidTests.cs" /> <Compile Include="System\HalfTests.cs" /> <Compile Include="System\HandleTests.cs" /> <Compile Include="System\HashCodeTests.cs" /> <Compile Include="System\IndexOutOfRangeExceptionTests.cs" /> <Compile Include="System\IndexTests.cs" /> <Compile Include="System\Int16Tests.cs" /> <Compile Include="System\Int32Tests.cs" /> <Compile Include="System\Int64Tests.cs" /> <Compile Include="System\IntPtrTests.cs" /> <Compile Include="System\InvalidCastExceptionTests.cs" /> <Compile Include="System\InvalidOperationExceptionTests.cs" /> <Compile Include="System\InvalidProgramExceptionTests.cs" /> <Compile Include="System\LazyTests.cs" /> <Compile Include="System\LazyOfTMetadataTests.cs" /> <Compile Include="System\MarshalByRefObjectTests.cs" /> <Compile Include="System\MemberAccessExceptionTests.cs" /> <Compile Include="System\MethodAccessExceptionTests.cs" /> <Compile Include="System\MissingFieldExceptionTests.cs" /> <Compile Include="System\MissingMemberExceptionTests.cs" /> <Compile Include="System\MissingMethodExceptionTests.cs" /> <Compile Include="System\MulticastDelegateTests.cs" /> <Compile Include="System\NotFiniteNumberExceptionTests.cs" /> <Compile Include="System\NotImplementedExceptionTests.cs" /> <Compile Include="System\NotSupportedExceptionTests.cs" /> <Compile Include="System\NullableMetadataTests.cs" /> <Compile Include="System\NullableTests.cs" /> <Compile Include="System\NullReferenceExceptionTests.cs" /> <Compile Include="System\ObjectTests.cs" /> <Compile Include="System\ObjectDisposedExceptionTests.cs" /> <Compile Include="System\ObsoleteAttributeTests.cs" /> <Compile Include="System\OutOfMemoryExceptionTests.cs" /> <Compile Include="System\OverflowExceptionTests.cs" /> <Compile Include="System\ParamArrayAttributeTests.cs" /> <Compile Include="System\PlatformNotSupportedExceptionTests.cs" /> <Compile Include="System\PseudoCustomAttributeTests.cs" /> <Compile Include="System\RangeTests.cs" /> <Compile Include="System\RankExceptionTests.cs" /> <Compile Include="System\Reflection\NullabilityInfoContextTests.cs" /> <Compile Include="System\SByteTests.cs" /> <Compile Include="System\SingleTests.cs" /> <Compile Include="System\StackOverflowExceptionTests.cs" /> <Compile Include="System\String.SplitTests.cs" /> <Compile Include="System\StringComparerTests.cs" /> <Compile Include="System\StringGetHashCodeTests.cs" /> <Compile Include="System\StringSplitExtensions.cs" /> <Compile Include="System\StringTests.cs" /> <Compile Include="System\SystemExceptionTests.cs" /> <Compile Include="System\TimeOnlyTests.cs" /> <Compile Include="System\TimeoutExceptionTests.cs" /> <Compile Include="System\TimeSpanTests.cs" /> <Compile Include="System\TimeZoneInfoTests.cs" /> <Compile Include="System\TimeZoneTests.cs" /> <Compile Include="System\TimeZoneNotFoundExceptionTests.cs" /> <Compile Include="System\TypedReferenceTests.cs" /> <Compile Include="System\TypeLoadExceptionTests.cs" /> <Compile Include="System\TypeUnloadedExceptionTests.cs" /> <Compile Include="System\TupleTests.cs" /> <Compile Include="System\UseResourceKeysTest.cs" /> <Compile Include="System\UInt16Tests.cs" /> <Compile Include="System\UInt32Tests.cs" /> <Compile Include="System\UInt64Tests.cs" /> <Compile Include="System\UIntPtrTests.cs" /> <Compile Include="System\UnitySerializationHolderTests.cs" /> <Compile Include="System\Uri.CreateStringTests.cs" /> <Compile Include="System\Uri.CreateUriTests.cs" /> <Compile Include="System\Uri.MethodsTests.cs" /> <Compile Include="System\ValueTypeTests.cs" /> <Compile Include="System\VersionTests.cs" /> <Compile Include="System\WeakReferenceTests.cs" /> <Compile Include="System\AppContext\AppContextTests.cs" /> <Compile Include="System\AppContext\AppContextTests.Switch.cs" /> <Compile Include="System\AppContext\AppContextTests.Switch.Validation.cs" /> <Compile Include="System\Collections\Generic\KeyNotFoundExceptionTests.cs" /> <Compile Include="System\Collections\Generic\KeyValuePairTests.cs" /> <Compile Include="System\Collections\ObjectModel\CollectionTests.cs" /> <Compile Include="System\Collections\ObjectModel\CollectionTestBase.cs" /> <Compile Include="System\Collections\ObjectModel\ReadOnlyCollectionTests.cs" /> <Compile Include="System\ComponentModel\DefaultValueAttributeTests.cs" /> <Compile Include="System\ComponentModel\EditorBrowsableAttributeTests.cs" /> <Compile Include="System\Diagnostics\ConditionalAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\ConstantExpectedAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\DynamicallyAccessedMembersAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\DynamicDependencyAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresAssemblyFilesAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresDynamicCodeAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresUnreferencedCodeAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\SetsRequiredMembersAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\UnconditionalSuppressMessageAttributeTests.cs" /> <Compile Include="System\Diagnostics\StackTraceHiddenAttributeTests.cs" /> <Compile Include="System\IO\DirectoryNotFoundExceptionTests.cs" /> <Compile Include="System\IO\DirectoryNotFoundException.InteropTests.cs" /> <Compile Include="System\IO\EndOfStreamExceptionTests.cs" /> <Compile Include="System\IO\Exceptions.HResults.cs" /> <Compile Include="System\IO\FileLoadExceptionTests.cs" /> <Compile Include="System\IO\FileLoadException.InteropTests.cs" /> <Compile Include="System\IO\FileNotFoundExceptionTests.cs" /> <Compile Include="System\IO\FileNotFoundException.InteropTests.cs" /> <Compile Include="System\IO\IOExceptionTests.cs" /> <Compile Include="System\IO\PathTooLongExceptionTests.cs" /> <Compile Include="System\IO\PathTooLongException.InteropTests.cs" /> <Compile Include="System\Reflection\AssemblyAlgorithmIdAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCompanyAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyConfigurationAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCopyrightAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCultureAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDefaultAliasAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDelaySignAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDescriptionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyFileVersionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyFlagsAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyInformationalVersionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyKeyFileAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyKeyNameAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyMetadataAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyProductAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblySignatureKeyAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyTitleAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyTrademarkAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyVersionAttributeTests.cs" /> <Compile Include="System\Reflection\BindingFlagsDoNotWrap.cs" /> <Compile Include="System\Reflection\CustomAttributeDataTests.cs" /> <Compile Include="System\Reflection\CustomAttributesTestData.cs" /> <Compile Include="System\Reflection\CustomAttribute_Named_Typed_ArgumentTests.cs" /> <Compile Include="System\Reflection\DefaultMemberAttributeTests.cs" /> <Compile Include="System\Reflection\InvokeRefReturn.cs" /> <Compile Include="System\Reflection\InvokeWithRefLikeArgs.cs" /> <Compile Include="System\Reflection\IsCollectibleTests.cs" /> <Compile Include="System\Reflection\MethodBaseTests.cs" /> <Compile Include="System\Reflection\MethodBodyTests.cs" /> <Compile Include="System\Reflection\ModuleTests.cs" /> <Compile Include="System\Reflection\ObfuscateAssemblyAttributeTests.cs" /> <Compile Include="System\Reflection\ObfuscationAttributeTests.cs" /> <Compile Include="System\Reflection\PointerTests.cs" /> <Compile Include="System\Reflection\ReflectionCacheTests.cs" /> <Compile Include="System\Reflection\ReflectionContextTests.cs" /> <Compile Include="System\Reflection\ReflectionTypeLoadExceptionTests.cs" /> <Compile Include="System\Reflection\StrongNameKeyPairTests.cs" /> <Compile Include="System\Reflection\TypeDelegatorTests.cs" /> <Compile Include="System\Reflection\TypeTests.Get.CornerCases.cs" /> <Compile Include="System\Reflection\TypeTests.GetMember.cs" /> <Compile Include="System\Runtime\DependentHandleTests.cs" /> <Compile Include="System\Runtime\JitInfoTests.cs" /> <Compile Include="System\Runtime\MemoryFailPointTests.cs" /> <Compile Include="System\Runtime\NgenServicingAttributesTests.cs" /> <Compile Include="System\Runtime\CompilerServices\AttributesTests.cs" /> <Compile Include="System\Runtime\CompilerServices\ConditionalWeakTableTests.cs" /> <Compile Include="System\Runtime\CompilerServices\DefaultInterpolatedStringHandlerTests.cs" /> <Compile Include="System\Runtime\CompilerServices\FormattableStringFactoryTests.cs" /> <Compile Include="System\Runtime\CompilerServices\StrongBoxTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeHelpersTests.cs" /> <Compile Include="System\Runtime\ConstrainedExecution\PrePrepareMethodAttributeTests.cs" /> <Compile Include="System\Runtime\ExceptionServices\HandleProcessCorruptedStateExceptions.cs" /> <Compile Include="System\Runtime\Serialization\OptionalFieldAttributeTests.cs" /> <Compile Include="System\Runtime\Serialization\SerializationExceptionTests.cs" /> <Compile Include="System\Runtime\Serialization\StreamingContextTests.cs" /> <Compile Include="System\Runtime\Versioning\OSPlatformAttributeTests.cs" /> <Compile Include="System\Runtime\Versioning\RequiresPreviewFeaturesAttributeTests.cs" /> <Compile Include="System\Security\SecurityAttributeTests.cs" /> <Compile Include="System\Security\SecurityExceptionTests.cs" /> <Compile Include="System\Text\StringBuilderTests.cs" /> <Compile Include="System\Text\StringBuilderInterpolationTests.cs" /> <Compile Include="System\Threading\PeriodicTimerTests.cs" /> <Compile Include="System\Threading\WaitHandleTests.cs" /> <Compile Include="System\Type\TypePropertyTests.cs" /> <Compile Include="System\Type\TypeTests.cs" /> <Compile Include="System\Type\TypeTests.Get.cs" /> <Compile Include="$(CommonTestPath)System\RandomDataGenerator.cs" Link="Common\System\RandomDataGenerator.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix' or '$(TargetPlatformIdentifier)' == 'Browser'"> <Compile Include="System\ExitCodeTests.Unix.cs" /> </ItemGroup> <ItemGroup Condition="'$(FeatureGenericMath)' == 'true'"> <Compile Include="System\ByteTests.GenericMath.cs" /> <Compile Include="System\CharTests.GenericMath.cs" /> <Compile Include="System\DoubleTests.GenericMath.cs" /> <Compile Include="System\GenericMathHelpers.cs" /> <Compile Include="System\HalfTests.GenericMath.cs" /> <Compile Include="System\Int16Tests.GenericMath.cs" /> <Compile Include="System\Int32Tests.GenericMath.cs" /> <Compile Include="System\Int64Tests.GenericMath.cs" /> <Compile Include="System\IntPtrTests.GenericMath.cs" /> <Compile Include="System\SByteTests.GenericMath.cs" /> <Compile Include="System\SingleTests.GenericMath.cs" /> <Compile Include="System\UInt16Tests.GenericMath.cs" /> <Compile Include="System\UInt32Tests.GenericMath.cs" /> <Compile Include="System\UInt64Tests.GenericMath.cs" /> <Compile Include="System\UIntPtrTests.GenericMath.cs" /> </ItemGroup> <ItemGroup> <Compile Include="System\Reflection\SignatureTypes.cs" /> <Compile Include="System\Runtime\CompilerServices\CallerArgumentExpressionAttributeTests.cs" /> <Compile Include="System\Runtime\CompilerServices\MethodImplAttributeTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeFeatureTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeWrappedExceptionTests.cs" /> <Compile Include="System\Runtime\ExceptionServices\ExceptionDispatchInfoTests.cs" /> <Compile Include="System\Text\ASCIIUtilityTests.cs" /> <Compile Include="System\Text\EncodingTests.cs" /> <Compile Include="System\Text\RuneTests.cs" /> <Compile Include="System\Text\RuneTests.TestData.cs" /> <Compile Include="System\Text\Unicode\Utf16UtilityTests.ValidateChars.cs" /> <Compile Include="System\Text\Unicode\Utf8Tests.cs" /> <Compile Include="System\Text\Unicode\Utf8UtilityTests.ValidateBytes.cs" /> <Compile Include="System\ArgIteratorTests.cs" /> <Compile Include="$(CommonPath)..\tests\System\RealFormatterTestsBase.cs" Link="System\RealFormatterTestsBase.cs" /> <Compile Include="System\RealFormatterTests.cs" /> <Compile Include="$(CommonPath)..\tests\System\RealParserTestsBase.cs" Link="System\RealParserTestsBase.cs" /> <Compile Include="System\RealParserTests.cs" /> <TrimmerRootDescriptor Include="$(ILLinkDescriptorsPath)ILLink.Descriptors.Castle.xml" /> <TrimmerRootDescriptor Include="$(MSBuildThisFileDirectory)ILLink.Descriptors.xml" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.Generic.Serialization.Tests.cs" Link="Common\System\Collections\IEnumerable.Generic.Serialization.Tests.cs" /> <EmbeddedResource Include="System\Reflection\EmbeddedImage.png"> <LogicalName>System.Reflection.Tests.EmbeddedImage.png</LogicalName> </EmbeddedResource> <EmbeddedResource Include="System\Reflection\EmbeddedTextFile.txt"> <LogicalName>System.Reflection.Tests.EmbeddedTextFile.txt</LogicalName> </EmbeddedResource> <Compile Include="$(CommonTestPath)System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs" Link="Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Moq" Version="$(MoqVersion)" /> <PackageReference Include="System.Runtime.Numerics.TestData" Version="$(SystemRuntimeNumericsTestDataVersion)" GeneratePathProperty="true" /> <ProjectReference Include="TestLoadAssembly\TestLoadAssembly.csproj" /> <ProjectReference Include="TestCollectibleAssembly\TestCollectibleAssembly.csproj" /> <ProjectReference Include="TestModule\System.Reflection.TestModule.ilproj" /> <ProjectReference Include="TestStructs\System.TestStructs.ilproj" /> <ProjectReference Include="$(CommonTestPath)TestUtilities.Unicode\TestUtilities.Unicode.csproj" /> <!-- Used during reflection in tests. --> <ProjectReference Include="$(LibrariesProjectRoot)System.Security.Permissions\src\System.Security.Permissions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Threading.AccessControl\src\System.Threading.AccessControl.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <FeatureGenericMath>false</FeatureGenericMath> <NoWarn>$(NoWarn),1718,SYSLIB0013</NoWarn> <TestRuntime>true</TestRuntime> <IncludeRemoteExecutor>true</IncludeRemoteExecutor> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser</TargetFrameworks> <Nullable>disable</Nullable> <!-- Disable nullability public only feature for NullabilityInfoContextTests --> <Features>$(Features.Replace('nullablePublicOnly', '')</Features> </PropertyGroup> <PropertyGroup> <DefineConstants Condition="'$(FeatureGenericMath)' == 'true'">$(DefineConstants);FEATURE_GENERIC_MATH</DefineConstants> </PropertyGroup> <ItemGroup> <RdXmlFile Include="default.rd.xml" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\EnumTypes.cs" Link="Common\System\EnumTypes.cs" /> <Compile Include="$(CommonTestPath)System\MockType.cs" Link="Common\System\MockType.cs" /> <Compile Include="$(CommonTestPath)System\Collections\CollectionAsserts.cs" Link="Common\System\Collections\CollectionAsserts.cs" /> <Compile Include="$(CommonTestPath)System\Collections\ICollection.Generic.Tests.cs" Link="Common\System\Collections\ICollection.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.Generic.Tests.cs" Link="Common\System\Collections\IEnumerable.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IList.Generic.Tests.cs" Link="Common\System\Collections\IList.Generic.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\TestBase.Generic.cs" Link="Common\System\Collections\TestBase.Generic.cs" /> <Compile Include="$(CommonTestPath)System\Collections\TestBase.NonGeneric.cs" Link="Common\System\Collections\TestBase.NonGeneric.cs" /> <Compile Include="$(CommonTestPath)Tests\System\StringTests.cs" Link="Common\System\StringTests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IDictionary.NonGeneric.Tests.cs" Link="Common\System\Collections\IDictionary.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IList.NonGeneric.Tests.cs" Link="Common\System\Collections\IList.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\ICollection.NonGeneric.Tests.cs" Link="Common\System\Collections\ICollection.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.NonGeneric.Tests.cs" Link="Common\System\Collections\IEnumerable.NonGeneric.Tests.cs" /> <Compile Include="$(CommonTestPath)TestUtilities\System\DisableParallelization.cs" Link="Common\TestUtilities\System\DisableParallelization.cs" /> <Compile Include="Helpers.cs" /> <Compile Include="Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs" /> <Compile Include="Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs" /> <Compile Include="System\AccessViolationExceptionTests.cs" /> <Compile Include="System\ActivatorTests.cs" /> <Compile Include="System\ActivatorTests.Generic.cs" /> <Compile Include="System\AmbiguousImplementationExceptionTests.cs" /> <Compile Include="System\ArgumentExceptionTests.cs" /> <Compile Include="System\ArgumentNullExceptionTests.cs" /> <Compile Include="System\ArgumentOutOfRangeExceptionTests.cs" /> <Compile Include="System\ArithmeticExceptionTests.cs" /> <Compile Include="System\ArrayTests.cs" /> <Compile Include="System\ArrayEnumeratorTests.cs" /> <Compile Include="System\ArraySegmentTests.cs" /> <Compile Include="System\ArrayTypeMismatchExceptionTests.cs" /> <Compile Include="System\ApplicationExceptionTests.cs" /> <Compile Include="System\AttributeTests.cs" /> <Compile Include="System\Attributes.cs" /> <Compile Include="System\AttributeUsageAttributeTests.cs" /> <Compile Include="System\BadImageFormatExceptionTests.cs" /> <Compile Include="System\BooleanTests.cs" /> <Compile Include="System\BufferTests.cs" /> <Compile Include="System\ByteTests.cs" /> <Compile Include="System\CharTests.cs" /> <Compile Include="System\CLSCompliantAttributeTests.cs" /> <Compile Include="System\DateOnlyTests.cs" /> <Compile Include="System\DateTimeTests.cs" /> <Compile Include="System\DateTimeOffsetTests.cs" /> <Compile Include="System\DBNullTests.cs" /> <Compile Include="System\DecimalTests.cs" /> <Compile Include="System\DelegateTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\StringSyntaxAttributeTests.cs" /> <Compile Include="System\DivideByZeroExceptionTests.cs" /> <Compile Include="System\DoubleTests.cs" /> <Compile Include="System\DuplicateWaitObjectExceptionTests.cs" /> <Compile Include="System\EntryPointNotFoundExceptionTests.cs" /> <Compile Include="System\EnumTests.cs" /> <Compile Include="System\ExceptionTests.cs" /> <Compile Include="System\Exception.Helpers.cs" /> <Compile Include="System\ExecutionEngineExceptionTests.cs" /> <Compile Include="System\ExternalExceptionTests.cs" /> <Compile Include="System\EventArgsTests.cs" /> <Compile Include="System\FieldAccessExceptionTests.cs" /> <Compile Include="System\FlagsAttributeTests.cs" /> <Compile Include="System\FormattableStringTests.cs" /> <Compile Include="System\FormatExceptionTests.cs" /> <Compile Include="System\GCTests.cs" /> <Compile Include="System\GuidTests.cs" /> <Compile Include="System\HalfTests.cs" /> <Compile Include="System\HandleTests.cs" /> <Compile Include="System\HashCodeTests.cs" /> <Compile Include="System\IndexOutOfRangeExceptionTests.cs" /> <Compile Include="System\IndexTests.cs" /> <Compile Include="System\Int16Tests.cs" /> <Compile Include="System\Int32Tests.cs" /> <Compile Include="System\Int64Tests.cs" /> <Compile Include="System\IntPtrTests.cs" /> <Compile Include="System\InvalidCastExceptionTests.cs" /> <Compile Include="System\InvalidOperationExceptionTests.cs" /> <Compile Include="System\InvalidProgramExceptionTests.cs" /> <Compile Include="System\LazyTests.cs" /> <Compile Include="System\LazyOfTMetadataTests.cs" /> <Compile Include="System\MarshalByRefObjectTests.cs" /> <Compile Include="System\MemberAccessExceptionTests.cs" /> <Compile Include="System\MethodAccessExceptionTests.cs" /> <Compile Include="System\MissingFieldExceptionTests.cs" /> <Compile Include="System\MissingMemberExceptionTests.cs" /> <Compile Include="System\MissingMethodExceptionTests.cs" /> <Compile Include="System\MulticastDelegateTests.cs" /> <Compile Include="System\NotFiniteNumberExceptionTests.cs" /> <Compile Include="System\NotImplementedExceptionTests.cs" /> <Compile Include="System\NotSupportedExceptionTests.cs" /> <Compile Include="System\NullableMetadataTests.cs" /> <Compile Include="System\NullableTests.cs" /> <Compile Include="System\NullReferenceExceptionTests.cs" /> <Compile Include="System\ObjectTests.cs" /> <Compile Include="System\ObjectDisposedExceptionTests.cs" /> <Compile Include="System\ObsoleteAttributeTests.cs" /> <Compile Include="System\OutOfMemoryExceptionTests.cs" /> <Compile Include="System\OverflowExceptionTests.cs" /> <Compile Include="System\ParamArrayAttributeTests.cs" /> <Compile Include="System\PlatformNotSupportedExceptionTests.cs" /> <Compile Include="System\PseudoCustomAttributeTests.cs" /> <Compile Include="System\RangeTests.cs" /> <Compile Include="System\RankExceptionTests.cs" /> <Compile Include="System\Reflection\NullabilityInfoContextTests.cs" /> <Compile Include="System\SByteTests.cs" /> <Compile Include="System\SingleTests.cs" /> <Compile Include="System\StackOverflowExceptionTests.cs" /> <Compile Include="System\String.SplitTests.cs" /> <Compile Include="System\StringComparerTests.cs" /> <Compile Include="System\StringGetHashCodeTests.cs" /> <Compile Include="System\StringSplitExtensions.cs" /> <Compile Include="System\StringTests.cs" /> <Compile Include="System\SystemExceptionTests.cs" /> <Compile Include="System\TimeOnlyTests.cs" /> <Compile Include="System\TimeoutExceptionTests.cs" /> <Compile Include="System\TimeSpanTests.cs" /> <Compile Include="System\TimeZoneInfoTests.cs" /> <Compile Include="System\TimeZoneTests.cs" /> <Compile Include="System\TimeZoneNotFoundExceptionTests.cs" /> <Compile Include="System\TypedReferenceTests.cs" /> <Compile Include="System\TypeLoadExceptionTests.cs" /> <Compile Include="System\TypeUnloadedExceptionTests.cs" /> <Compile Include="System\TupleTests.cs" /> <Compile Include="System\UseResourceKeysTest.cs" /> <Compile Include="System\UInt16Tests.cs" /> <Compile Include="System\UInt32Tests.cs" /> <Compile Include="System\UInt64Tests.cs" /> <Compile Include="System\UIntPtrTests.cs" /> <Compile Include="System\UnitySerializationHolderTests.cs" /> <Compile Include="System\Uri.CreateStringTests.cs" /> <Compile Include="System\Uri.CreateUriTests.cs" /> <Compile Include="System\Uri.MethodsTests.cs" /> <Compile Include="System\ValueTypeTests.cs" /> <Compile Include="System\VersionTests.cs" /> <Compile Include="System\WeakReferenceTests.cs" /> <Compile Include="System\AppContext\AppContextTests.cs" /> <Compile Include="System\AppContext\AppContextTests.Switch.cs" /> <Compile Include="System\AppContext\AppContextTests.Switch.Validation.cs" /> <Compile Include="System\Collections\Generic\KeyNotFoundExceptionTests.cs" /> <Compile Include="System\Collections\Generic\KeyValuePairTests.cs" /> <Compile Include="System\Collections\ObjectModel\CollectionTests.cs" /> <Compile Include="System\Collections\ObjectModel\CollectionTestBase.cs" /> <Compile Include="System\Collections\ObjectModel\ReadOnlyCollectionTests.cs" /> <Compile Include="System\ComponentModel\DefaultValueAttributeTests.cs" /> <Compile Include="System\ComponentModel\EditorBrowsableAttributeTests.cs" /> <Compile Include="System\Diagnostics\ConditionalAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\ConstantExpectedAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\DynamicallyAccessedMembersAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\DynamicDependencyAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresAssemblyFilesAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresDynamicCodeAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\RequiresUnreferencedCodeAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\SetsRequiredMembersAttributeTests.cs" /> <Compile Include="System\Diagnostics\CodeAnalysis\UnconditionalSuppressMessageAttributeTests.cs" /> <Compile Include="System\Diagnostics\StackTraceHiddenAttributeTests.cs" /> <Compile Include="System\IO\DirectoryNotFoundExceptionTests.cs" /> <Compile Include="System\IO\DirectoryNotFoundException.InteropTests.cs" /> <Compile Include="System\IO\EndOfStreamExceptionTests.cs" /> <Compile Include="System\IO\Exceptions.HResults.cs" /> <Compile Include="System\IO\FileLoadExceptionTests.cs" /> <Compile Include="System\IO\FileLoadException.InteropTests.cs" /> <Compile Include="System\IO\FileNotFoundExceptionTests.cs" /> <Compile Include="System\IO\FileNotFoundException.InteropTests.cs" /> <Compile Include="System\IO\IOExceptionTests.cs" /> <Compile Include="System\IO\PathTooLongExceptionTests.cs" /> <Compile Include="System\IO\PathTooLongException.InteropTests.cs" /> <Compile Include="System\Reflection\AssemblyAlgorithmIdAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCompanyAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyConfigurationAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCopyrightAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyCultureAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDefaultAliasAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDelaySignAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyDescriptionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyFileVersionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyFlagsAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyInformationalVersionAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyKeyFileAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyKeyNameAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyMetadataAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyProductAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblySignatureKeyAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyTitleAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyTrademarkAttributeTests.cs" /> <Compile Include="System\Reflection\AssemblyVersionAttributeTests.cs" /> <Compile Include="System\Reflection\BindingFlagsDoNotWrap.cs" /> <Compile Include="System\Reflection\CustomAttributeDataTests.cs" /> <Compile Include="System\Reflection\CustomAttributesTestData.cs" /> <Compile Include="System\Reflection\CustomAttribute_Named_Typed_ArgumentTests.cs" /> <Compile Include="System\Reflection\DefaultMemberAttributeTests.cs" /> <Compile Include="System\Reflection\InvokeRefReturn.cs" /> <Compile Include="System\Reflection\InvokeWithRefLikeArgs.cs" /> <Compile Include="System\Reflection\IsCollectibleTests.cs" /> <Compile Include="System\Reflection\MethodBaseTests.cs" /> <Compile Include="System\Reflection\MethodBodyTests.cs" /> <Compile Include="System\Reflection\ModuleTests.cs" /> <Compile Include="System\Reflection\ObfuscateAssemblyAttributeTests.cs" /> <Compile Include="System\Reflection\ObfuscationAttributeTests.cs" /> <Compile Include="System\Reflection\PointerTests.cs" /> <Compile Include="System\Reflection\ReflectionCacheTests.cs" /> <Compile Include="System\Reflection\ReflectionContextTests.cs" /> <Compile Include="System\Reflection\ReflectionTypeLoadExceptionTests.cs" /> <Compile Include="System\Reflection\StrongNameKeyPairTests.cs" /> <Compile Include="System\Reflection\TypeDelegatorTests.cs" /> <Compile Include="System\Reflection\TypeTests.Get.CornerCases.cs" /> <Compile Include="System\Reflection\TypeTests.GetMember.cs" /> <Compile Include="System\Runtime\DependentHandleTests.cs" /> <Compile Include="System\Runtime\JitInfoTests.cs" /> <Compile Include="System\Runtime\MemoryFailPointTests.cs" /> <Compile Include="System\Runtime\NgenServicingAttributesTests.cs" /> <Compile Include="System\Runtime\CompilerServices\AttributesTests.cs" /> <Compile Include="System\Runtime\CompilerServices\ConditionalWeakTableTests.cs" /> <Compile Include="System\Runtime\CompilerServices\DefaultInterpolatedStringHandlerTests.cs" /> <Compile Include="System\Runtime\CompilerServices\FormattableStringFactoryTests.cs" /> <Compile Include="System\Runtime\CompilerServices\StrongBoxTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeHelpersTests.cs" /> <Compile Include="System\Runtime\ConstrainedExecution\PrePrepareMethodAttributeTests.cs" /> <Compile Include="System\Runtime\ExceptionServices\HandleProcessCorruptedStateExceptions.cs" /> <Compile Include="System\Runtime\Serialization\OptionalFieldAttributeTests.cs" /> <Compile Include="System\Runtime\Serialization\SerializationExceptionTests.cs" /> <Compile Include="System\Runtime\Serialization\StreamingContextTests.cs" /> <Compile Include="System\Runtime\Versioning\OSPlatformAttributeTests.cs" /> <Compile Include="System\Runtime\Versioning\RequiresPreviewFeaturesAttributeTests.cs" /> <Compile Include="System\Security\SecurityAttributeTests.cs" /> <Compile Include="System\Security\SecurityExceptionTests.cs" /> <Compile Include="System\Text\StringBuilderTests.cs" /> <Compile Include="System\Text\StringBuilderInterpolationTests.cs" /> <Compile Include="System\Threading\PeriodicTimerTests.cs" /> <Compile Include="System\Threading\WaitHandleTests.cs" /> <Compile Include="System\Type\TypePropertyTests.cs" /> <Compile Include="System\Type\TypeTests.cs" /> <Compile Include="System\Type\TypeTests.Get.cs" /> <Compile Include="$(CommonTestPath)System\RandomDataGenerator.cs" Link="Common\System\RandomDataGenerator.cs" /> </ItemGroup> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'Unix' or '$(TargetPlatformIdentifier)' == 'Browser'"> <Compile Include="System\ExitCodeTests.Unix.cs" /> </ItemGroup> <ItemGroup Condition="'$(FeatureGenericMath)' == 'true'"> <Compile Include="System\ByteTests.GenericMath.cs" /> <Compile Include="System\CharTests.GenericMath.cs" /> <Compile Include="System\DoubleTests.GenericMath.cs" /> <Compile Include="System\GenericMathHelpers.cs" /> <Compile Include="System\HalfTests.GenericMath.cs" /> <Compile Include="System\Int16Tests.GenericMath.cs" /> <Compile Include="System\Int32Tests.GenericMath.cs" /> <Compile Include="System\Int64Tests.GenericMath.cs" /> <Compile Include="System\IntPtrTests.GenericMath.cs" /> <Compile Include="System\SByteTests.GenericMath.cs" /> <Compile Include="System\SingleTests.GenericMath.cs" /> <Compile Include="System\UInt16Tests.GenericMath.cs" /> <Compile Include="System\UInt32Tests.GenericMath.cs" /> <Compile Include="System\UInt64Tests.GenericMath.cs" /> <Compile Include="System\UIntPtrTests.GenericMath.cs" /> </ItemGroup> <ItemGroup> <Compile Include="System\Reflection\SignatureTypes.cs" /> <Compile Include="System\Runtime\CompilerServices\CallerArgumentExpressionAttributeTests.cs" /> <Compile Include="System\Runtime\CompilerServices\MethodImplAttributeTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeFeatureTests.cs" /> <Compile Include="System\Runtime\CompilerServices\RuntimeWrappedExceptionTests.cs" /> <Compile Include="System\Runtime\ExceptionServices\ExceptionDispatchInfoTests.cs" /> <Compile Include="System\Text\ASCIIUtilityTests.cs" /> <Compile Include="System\Text\EncodingTests.cs" /> <Compile Include="System\Text\RuneTests.cs" /> <Compile Include="System\Text\RuneTests.TestData.cs" /> <Compile Include="System\Text\Unicode\Utf16UtilityTests.ValidateChars.cs" /> <Compile Include="System\Text\Unicode\Utf8Tests.cs" /> <Compile Include="System\Text\Unicode\Utf8UtilityTests.ValidateBytes.cs" /> <Compile Include="System\ArgIteratorTests.cs" /> <Compile Include="$(CommonPath)..\tests\System\RealFormatterTestsBase.cs" Link="System\RealFormatterTestsBase.cs" /> <Compile Include="System\RealFormatterTests.cs" /> <Compile Include="$(CommonPath)..\tests\System\RealParserTestsBase.cs" Link="System\RealParserTestsBase.cs" /> <Compile Include="System\RealParserTests.cs" /> <TrimmerRootDescriptor Include="$(ILLinkDescriptorsPath)ILLink.Descriptors.Castle.xml" /> <TrimmerRootDescriptor Include="$(MSBuildThisFileDirectory)ILLink.Descriptors.xml" /> </ItemGroup> <ItemGroup> <Compile Include="$(CommonTestPath)System\Collections\IEnumerable.Generic.Serialization.Tests.cs" Link="Common\System\Collections\IEnumerable.Generic.Serialization.Tests.cs" /> <EmbeddedResource Include="System\Reflection\EmbeddedImage.png"> <LogicalName>System.Reflection.Tests.EmbeddedImage.png</LogicalName> </EmbeddedResource> <EmbeddedResource Include="System\Reflection\EmbeddedTextFile.txt"> <LogicalName>System.Reflection.Tests.EmbeddedTextFile.txt</LogicalName> </EmbeddedResource> <Compile Include="$(CommonTestPath)System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs" Link="Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Moq" Version="$(MoqVersion)" /> <PackageReference Include="System.Runtime.Numerics.TestData" Version="$(SystemRuntimeNumericsTestDataVersion)" GeneratePathProperty="true" /> <ProjectReference Include="TestLoadAssembly\TestLoadAssembly.csproj" /> <ProjectReference Include="TestCollectibleAssembly\TestCollectibleAssembly.csproj" /> <ProjectReference Include="TestModule\System.Reflection.TestModule.ilproj" /> <ProjectReference Include="TestStructs\System.TestStructs.ilproj" /> <ProjectReference Include="$(CommonTestPath)TestUtilities.Unicode\TestUtilities.Unicode.csproj" /> <!-- Used during reflection in tests. --> <ProjectReference Include="$(LibrariesProjectRoot)System.Security.Permissions\src\System.Security.Permissions.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Threading.AccessControl\src\System.Threading.AccessControl.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/GC/Stress/Tests/MulDimJagAry.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestKind>BuildOnly</CLRTestKind> </PropertyGroup> <ItemGroup> <Compile Include="MulDimJagAry.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <CLRTestKind>BuildOnly</CLRTestKind> </PropertyGroup> <ItemGroup> <Compile Include="MulDimJagAry.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Net.Security/tests/FunctionalTests/SslStreamAlpnTests.cs
// 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; using System.Linq; using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class SslStreamAlpnTestBase { private static bool BackendSupportsAlpn => PlatformDetection.SupportsAlpn; private static bool ClientSupportsAlpn => PlatformDetection.SupportsClientAlpn; readonly ITestOutputHelper _output; public static readonly object[][] Http2Servers = Configuration.Http.Http2Servers; // Whether AuthenticateAs(Client/Server) or AuthenticateAs(Client/Server)Async will be called public abstract bool TestAuthenticateAsync { get; } protected SslStreamAlpnTestBase(ITestOutputHelper output) { _output = output; } private async Task DoHandshakeWithOptions(SslStream clientSslStream, SslStream serverSslStream, SslClientAuthenticationOptions clientOptions, SslServerAuthenticationOptions serverOptions) { using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { clientOptions.RemoteCertificateValidationCallback = AllowAnyServerCertificate; clientOptions.TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false); serverOptions.ServerCertificateContext = SslStreamCertificateContext.Create(certificate, null); Task t1 = clientSslStream.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions); Task t2 = serverSslStream.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); } } protected bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None; if (!Capability.IsTrustedRootCertificateInstalled()) { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; } Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors); if (sslPolicyErrors == expectedSslPolicyErrors) { return true; } else { return false; } } [Fact] public async Task SslStream_StreamToStream_DuplicateOptions_Throws() { RemoteCertificateValidationCallback rCallback = (sender, certificate, chain, errors) => { return true; }; LocalCertificateSelectionCallback lCallback = (sender, host, localCertificates, remoteCertificate, issuers) => { return null; }; (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams(); using (clientStream) using (serverStream) using (var client = new SslStream(clientStream, false, rCallback, lCallback, EncryptionPolicy.RequireEncryption)) using (var server = new SslStream(serverStream, false, rCallback)) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions(); clientOptions.RemoteCertificateValidationCallback = AllowAnyServerCertificate; clientOptions.TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false); SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions(); serverOptions.ServerCertificate = certificate; serverOptions.RemoteCertificateValidationCallback = AllowAnyServerCertificate; Task t1 = Assert.ThrowsAsync<InvalidOperationException>(() => client.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions)); Task t2 = Assert.ThrowsAsync<InvalidOperationException>(() => server.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions)); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); } } [Theory] [MemberData(nameof(Alpn_TestData))] public async Task SslStream_StreamToStream_Alpn_Success(List<SslApplicationProtocol> clientProtocols, List<SslApplicationProtocol> serverProtocols, SslApplicationProtocol expected) { (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams(); using (clientStream) using (serverStream) using (var client = new SslStream(clientStream, false)) using (var server = new SslStream(serverStream, false)) { SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions { ApplicationProtocols = clientProtocols, }; SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions { ApplicationProtocols = serverProtocols, }; await DoHandshakeWithOptions(client, server, clientOptions, serverOptions); Assert.Equal(expected, client.NegotiatedApplicationProtocol); Assert.Equal(expected, server.NegotiatedApplicationProtocol); } } [Fact] public async Task SslStream_StreamToStream_Alpn_NonMatchingProtocols_Fail() { (SslStream clientStream, SslStream serverStream) = TestHelper.GetConnectedSslStreams(); using (serverStream) using (clientStream) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions { ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, ServerCertificate = certificate, }; SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions { ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }, RemoteCertificateValidationCallback = AllowAnyServerCertificate, TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false), }; // Test ALPN failure only on platforms that supports ALPN. if (BackendSupportsAlpn) { Task t1 = Assert.ThrowsAsync<AuthenticationException>(() => clientStream.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions)); await Assert.ThrowsAsync<AuthenticationException>(() => serverStream.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions)); serverStream.Dispose(); await t1.WaitAsync(TestConfiguration.PassingTestTimeout); } else { Task t1 = clientStream.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions); Task t2 = serverStream.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); Assert.Equal(default(SslApplicationProtocol), clientStream.NegotiatedApplicationProtocol); Assert.Equal(default(SslApplicationProtocol), serverStream.NegotiatedApplicationProtocol); } } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(ClientSupportsAlpn))] [MemberData(nameof(Http2Servers))] public async Task SslStream_Http2_Alpn_Success(Uri server) { using (TcpClient client = new TcpClient()) { try { await client.ConnectAsync(server.Host, server.Port); using (SslStream clientStream = new SslStream(client.GetStream(), leaveInnerStreamOpen: false)) { SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions { ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 , SslApplicationProtocol.Http11 }, TargetHost = server.Host }; await clientStream.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions); Assert.Equal("h2", clientStream.NegotiatedApplicationProtocol.ToString()); } } catch (Exception e) { // Failures to connect do not cause test failure. _output.WriteLine("Unable to connect: {0}", e); } } } public static IEnumerable<object[]> Alpn_TestData() { if (OperatingSystem.IsMacOS()) { yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null }; yield return new object[] { null, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol>(), null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null, null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, null }; yield return new object[] { new List<SslApplicationProtocol>(), new List<SslApplicationProtocol>(), null }; yield return new object[] { null, new List<SslApplicationProtocol>(), null }; yield return new object[] { new List<SslApplicationProtocol>(), null, null }; yield return new object[] { null, null, null }; } else { yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, BackendSupportsAlpn ? SslApplicationProtocol.Http2 : default }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, BackendSupportsAlpn ? SslApplicationProtocol.Http11 : default }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, BackendSupportsAlpn ? SslApplicationProtocol.Http11 : default }; yield return new object[] { null, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, default(SslApplicationProtocol) }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol>(), default(SslApplicationProtocol) }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null, default(SslApplicationProtocol) }; yield return new object[] { new List<SslApplicationProtocol>(), new List<SslApplicationProtocol>(), default(SslApplicationProtocol) }; yield return new object[] { null, new List<SslApplicationProtocol>(), default(SslApplicationProtocol) }; yield return new object[] { new List<SslApplicationProtocol>(), null, default(SslApplicationProtocol) }; yield return new object[] { null, null, default(SslApplicationProtocol) }; } } } public sealed class SslStreamAlpnTest_Async : SslStreamAlpnTestBase { public override bool TestAuthenticateAsync => true; public SslStreamAlpnTest_Async(ITestOutputHelper output) : base (output) { } } public sealed class SslStreamAlpnTest_Sync : SslStreamAlpnTestBase { public override bool TestAuthenticateAsync => false; public SslStreamAlpnTest_Sync(ITestOutputHelper output) : base(output) { } } }
// 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; using System.Linq; using System.Net.Sockets; using System.Net.Test.Common; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Security.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class SslStreamAlpnTestBase { private static bool BackendSupportsAlpn => PlatformDetection.SupportsAlpn; private static bool ClientSupportsAlpn => PlatformDetection.SupportsClientAlpn; readonly ITestOutputHelper _output; public static readonly object[][] Http2Servers = Configuration.Http.Http2Servers; // Whether AuthenticateAs(Client/Server) or AuthenticateAs(Client/Server)Async will be called public abstract bool TestAuthenticateAsync { get; } protected SslStreamAlpnTestBase(ITestOutputHelper output) { _output = output; } private async Task DoHandshakeWithOptions(SslStream clientSslStream, SslStream serverSslStream, SslClientAuthenticationOptions clientOptions, SslServerAuthenticationOptions serverOptions) { using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { clientOptions.RemoteCertificateValidationCallback = AllowAnyServerCertificate; clientOptions.TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false); serverOptions.ServerCertificateContext = SslStreamCertificateContext.Create(certificate, null); Task t1 = clientSslStream.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions); Task t2 = serverSslStream.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); } } protected bool AllowAnyServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None; if (!Capability.IsTrustedRootCertificateInstalled()) { expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors; } Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors); if (sslPolicyErrors == expectedSslPolicyErrors) { return true; } else { return false; } } [Fact] public async Task SslStream_StreamToStream_DuplicateOptions_Throws() { RemoteCertificateValidationCallback rCallback = (sender, certificate, chain, errors) => { return true; }; LocalCertificateSelectionCallback lCallback = (sender, host, localCertificates, remoteCertificate, issuers) => { return null; }; (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams(); using (clientStream) using (serverStream) using (var client = new SslStream(clientStream, false, rCallback, lCallback, EncryptionPolicy.RequireEncryption)) using (var server = new SslStream(serverStream, false, rCallback)) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions(); clientOptions.RemoteCertificateValidationCallback = AllowAnyServerCertificate; clientOptions.TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false); SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions(); serverOptions.ServerCertificate = certificate; serverOptions.RemoteCertificateValidationCallback = AllowAnyServerCertificate; Task t1 = Assert.ThrowsAsync<InvalidOperationException>(() => client.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions)); Task t2 = Assert.ThrowsAsync<InvalidOperationException>(() => server.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions)); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); } } [Theory] [MemberData(nameof(Alpn_TestData))] public async Task SslStream_StreamToStream_Alpn_Success(List<SslApplicationProtocol> clientProtocols, List<SslApplicationProtocol> serverProtocols, SslApplicationProtocol expected) { (Stream clientStream, Stream serverStream) = TestHelper.GetConnectedStreams(); using (clientStream) using (serverStream) using (var client = new SslStream(clientStream, false)) using (var server = new SslStream(serverStream, false)) { SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions { ApplicationProtocols = clientProtocols, }; SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions { ApplicationProtocols = serverProtocols, }; await DoHandshakeWithOptions(client, server, clientOptions, serverOptions); Assert.Equal(expected, client.NegotiatedApplicationProtocol); Assert.Equal(expected, server.NegotiatedApplicationProtocol); } } [Fact] public async Task SslStream_StreamToStream_Alpn_NonMatchingProtocols_Fail() { (SslStream clientStream, SslStream serverStream) = TestHelper.GetConnectedSslStreams(); using (serverStream) using (clientStream) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions { ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, ServerCertificate = certificate, }; SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions { ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }, RemoteCertificateValidationCallback = AllowAnyServerCertificate, TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false), }; // Test ALPN failure only on platforms that supports ALPN. if (BackendSupportsAlpn) { Task t1 = Assert.ThrowsAsync<AuthenticationException>(() => clientStream.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions)); await Assert.ThrowsAsync<AuthenticationException>(() => serverStream.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions)); serverStream.Dispose(); await t1.WaitAsync(TestConfiguration.PassingTestTimeout); } else { Task t1 = clientStream.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions); Task t2 = serverStream.AuthenticateAsServerAsync(TestAuthenticateAsync, serverOptions); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); Assert.Equal(default(SslApplicationProtocol), clientStream.NegotiatedApplicationProtocol); Assert.Equal(default(SslApplicationProtocol), serverStream.NegotiatedApplicationProtocol); } } } [OuterLoop("Uses external servers")] [ConditionalTheory(nameof(ClientSupportsAlpn))] [MemberData(nameof(Http2Servers))] public async Task SslStream_Http2_Alpn_Success(Uri server) { using (TcpClient client = new TcpClient()) { try { await client.ConnectAsync(server.Host, server.Port); using (SslStream clientStream = new SslStream(client.GetStream(), leaveInnerStreamOpen: false)) { SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions { ApplicationProtocols = new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 , SslApplicationProtocol.Http11 }, TargetHost = server.Host }; await clientStream.AuthenticateAsClientAsync(TestAuthenticateAsync, clientOptions); Assert.Equal("h2", clientStream.NegotiatedApplicationProtocol.ToString()); } } catch (Exception e) { // Failures to connect do not cause test failure. _output.WriteLine("Unable to connect: {0}", e); } } } public static IEnumerable<object[]> Alpn_TestData() { if (OperatingSystem.IsMacOS()) { yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null }; yield return new object[] { null, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol>(), null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null, null }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, null }; yield return new object[] { new List<SslApplicationProtocol>(), new List<SslApplicationProtocol>(), null }; yield return new object[] { null, new List<SslApplicationProtocol>(), null }; yield return new object[] { new List<SslApplicationProtocol>(), null, null }; yield return new object[] { null, null, null }; } else { yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http2 }, BackendSupportsAlpn ? SslApplicationProtocol.Http2 : default }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, BackendSupportsAlpn ? SslApplicationProtocol.Http11 : default }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, BackendSupportsAlpn ? SslApplicationProtocol.Http11 : default }; yield return new object[] { null, new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, default(SslApplicationProtocol) }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, new List<SslApplicationProtocol>(), default(SslApplicationProtocol) }; yield return new object[] { new List<SslApplicationProtocol> { SslApplicationProtocol.Http11, SslApplicationProtocol.Http2 }, null, default(SslApplicationProtocol) }; yield return new object[] { new List<SslApplicationProtocol>(), new List<SslApplicationProtocol>(), default(SslApplicationProtocol) }; yield return new object[] { null, new List<SslApplicationProtocol>(), default(SslApplicationProtocol) }; yield return new object[] { new List<SslApplicationProtocol>(), null, default(SslApplicationProtocol) }; yield return new object[] { null, null, default(SslApplicationProtocol) }; } } } public sealed class SslStreamAlpnTest_Async : SslStreamAlpnTestBase { public override bool TestAuthenticateAsync => true; public SslStreamAlpnTest_Async(ITestOutputHelper output) : base (output) { } } public sealed class SslStreamAlpnTest_Sync : SslStreamAlpnTestBase { public override bool TestAuthenticateAsync => false; public SslStreamAlpnTest_Sync(ITestOutputHelper output) : base(output) { } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M11-Beta1/b46170/b46170.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/nativeaot/SmokeTests/PInvoke/PInvoke.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- Correctness of interop for abstract delegates cannot be guaranteed after native compilation --> <NoWarn>$(NoWarn);IL3055</NoWarn> <!-- Look for MULTIMODULE_BUILD #define for the more specific incompatible parts --> <CLRTestTargetUnsupported Condition="'$(IlcMultiModule)' == 'true'">true</CLRTestTargetUnsupported> </PropertyGroup> <ItemGroup> <Compile Include="PInvoke.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CMakeLists.txt" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <!-- Correctness of interop for abstract delegates cannot be guaranteed after native compilation --> <NoWarn>$(NoWarn);IL3055</NoWarn> <!-- Look for MULTIMODULE_BUILD #define for the more specific incompatible parts --> <CLRTestTargetUnsupported Condition="'$(IlcMultiModule)' == 'true'">true</CLRTestTargetUnsupported> </PropertyGroup> <ItemGroup> <Compile Include="PInvoke.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="CMakeLists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Insert.Vector128.Int16.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Insert_Vector128_Int16_1() { var test = new InsertTest__Insert_Vector128_Int16_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertTest__Insert_Vector128_Int16_1 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Int16 _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); testStruct._fld3 = TestLibrary.Generator.GetInt16(); return testStruct; } public void RunStructFldScenario(InsertTest__Insert_Vector128_Int16_1 testClass) { var result = AdvSimd.Insert(_fld1, ElementIndex, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertTest__Insert_Vector128_Int16_1 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Int16* pFld3 = &_fld3) { var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)pFld1), ElementIndex, *pFld3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly byte ElementIndex = 1; private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Vector128<Int16> _clsVar1; private static Int16 _clsVar3; private Vector128<Int16> _fld1; private Int16 _fld3; private DataTable _dataTable; static InsertTest__Insert_Vector128_Int16_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); _clsVar3 = TestLibrary.Generator.GetInt16(); } public InsertTest__Insert_Vector128_Int16_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); _fld3 = TestLibrary.Generator.GetInt16(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Insert( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), ElementIndex, _fld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _fld3, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), ElementIndex, _fld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _fld3, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); Int16 op3 = TestLibrary.Generator.GetInt16(); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Insert), new Type[] { typeof(Vector128<Int16>), typeof(byte), typeof(Int16) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), ElementIndex, op3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, op3, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); Int16 op3 = TestLibrary.Generator.GetInt16(); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Insert), new Type[] { typeof(Vector128<Int16>), typeof(byte), typeof(Int16) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), ElementIndex, op3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, op3, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Insert( _clsVar1, ElementIndex, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Int16* pClsVar3 = &_clsVar3) { var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)pClsVar1), ElementIndex, *pClsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op3 = TestLibrary.Generator.GetInt16(); var result = AdvSimd.Insert(op1, ElementIndex, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op3 = TestLibrary.Generator.GetInt16(); var result = AdvSimd.Insert(op1, ElementIndex, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertTest__Insert_Vector128_Int16_1(); var result = AdvSimd.Insert(test._fld1, ElementIndex, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertTest__Insert_Vector128_Int16_1(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Int16* pFld3 = &test._fld3) { var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)pFld1), ElementIndex, *pFld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Insert(_fld1, ElementIndex, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Int16* pFld3 = &_fld3) { var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)pFld1), ElementIndex, *pFld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Insert(test._fld1, ElementIndex, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)(&test._fld1)), ElementIndex, test._fld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Int16 op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, op3, outArray, method); } private void ValidateResult(void* op1, Int16 op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, op3, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16 thirdOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex, thirdOp, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Insert)}<Int16>(Vector128<Int16>, 1, Int16): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: {thirdOp}"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Insert_Vector128_Int16_1() { var test = new InsertTest__Insert_Vector128_Int16_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertTest__Insert_Vector128_Int16_1 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Int16 _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); testStruct._fld3 = TestLibrary.Generator.GetInt16(); return testStruct; } public void RunStructFldScenario(InsertTest__Insert_Vector128_Int16_1 testClass) { var result = AdvSimd.Insert(_fld1, ElementIndex, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertTest__Insert_Vector128_Int16_1 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Int16* pFld3 = &_fld3) { var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)pFld1), ElementIndex, *pFld3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly byte ElementIndex = 1; private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Vector128<Int16> _clsVar1; private static Int16 _clsVar3; private Vector128<Int16> _fld1; private Int16 _fld3; private DataTable _dataTable; static InsertTest__Insert_Vector128_Int16_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); _clsVar3 = TestLibrary.Generator.GetInt16(); } public InsertTest__Insert_Vector128_Int16_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); _fld3 = TestLibrary.Generator.GetInt16(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Insert( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), ElementIndex, _fld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _fld3, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), ElementIndex, _fld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _fld3, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); Int16 op3 = TestLibrary.Generator.GetInt16(); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Insert), new Type[] { typeof(Vector128<Int16>), typeof(byte), typeof(Int16) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), ElementIndex, op3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, op3, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); Int16 op3 = TestLibrary.Generator.GetInt16(); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Insert), new Type[] { typeof(Vector128<Int16>), typeof(byte), typeof(Int16) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), ElementIndex, op3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, op3, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Insert( _clsVar1, ElementIndex, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Int16* pClsVar3 = &_clsVar3) { var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)pClsVar1), ElementIndex, *pClsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op3 = TestLibrary.Generator.GetInt16(); var result = AdvSimd.Insert(op1, ElementIndex, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op3 = TestLibrary.Generator.GetInt16(); var result = AdvSimd.Insert(op1, ElementIndex, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertTest__Insert_Vector128_Int16_1(); var result = AdvSimd.Insert(test._fld1, ElementIndex, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertTest__Insert_Vector128_Int16_1(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Int16* pFld3 = &test._fld3) { var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)pFld1), ElementIndex, *pFld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Insert(_fld1, ElementIndex, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Int16* pFld3 = &_fld3) { var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)pFld1), ElementIndex, *pFld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Insert(test._fld1, ElementIndex, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Insert( AdvSimd.LoadVector128((Int16*)(&test._fld1)), ElementIndex, test._fld3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Int16 op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, op3, outArray, method); } private void ValidateResult(void* op1, Int16 op3, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, op3, outArray, method); } private void ValidateResult(Int16[] firstOp, Int16 thirdOp, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex, thirdOp, i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Insert)}<Int16>(Vector128<Int16>, 1, Int16): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: {thirdOp}"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.IsolatedStorage { internal static partial class Helper { private const string IsolatedStorageDirectoryName = "IsolatedStorage"; private static string? s_machineRootDirectory; private static string? s_roamingUserRootDirectory; private static string? s_userRootDirectory; /// <summary> /// The full root directory is the relevant special folder from Environment.GetFolderPath() plus "IsolatedStorage" /// and a set of random directory names if not roaming. (The random directories aren't created for WinRT as /// the FolderPath locations for WinRT are app isolated already.) /// /// Examples: /// /// User: @"C:\Users\jerem\AppData\Local\IsolatedStorage\10v31ho4.bo2\eeolfu22.f2w\" /// User|Roaming: @"C:\Users\jerem\AppData\Roaming\IsolatedStorage\" /// Machine: @"C:\ProgramData\IsolatedStorage\nin03cyc.wr0\o3j0urs3.0sn\" /// /// Identity for the current store gets tacked on after this. /// </summary> internal static string GetRootDirectory(IsolatedStorageScope scope) { if (IsRoaming(scope)) { if (string.IsNullOrEmpty(s_roamingUserRootDirectory)) { s_roamingUserRootDirectory = GetDataDirectory(scope); } return s_roamingUserRootDirectory; } if (IsMachine(scope)) { if (string.IsNullOrEmpty(s_machineRootDirectory)) { s_machineRootDirectory = GetRandomDirectory(GetDataDirectory(scope), scope); } return s_machineRootDirectory; } if (string.IsNullOrEmpty(s_userRootDirectory)) s_userRootDirectory = GetRandomDirectory(GetDataDirectory(scope), scope); return s_userRootDirectory; } internal static bool IsMachine(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Machine) != 0); internal static bool IsAssembly(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Assembly) != 0); internal static bool IsApplication(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Application) != 0); internal static bool IsRoaming(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Roaming) != 0); internal static bool IsDomain(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Domain) != 0); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.IO.IsolatedStorage { internal static partial class Helper { private const string IsolatedStorageDirectoryName = "IsolatedStorage"; private static string? s_machineRootDirectory; private static string? s_roamingUserRootDirectory; private static string? s_userRootDirectory; /// <summary> /// The full root directory is the relevant special folder from Environment.GetFolderPath() plus "IsolatedStorage" /// and a set of random directory names if not roaming. (The random directories aren't created for WinRT as /// the FolderPath locations for WinRT are app isolated already.) /// /// Examples: /// /// User: @"C:\Users\jerem\AppData\Local\IsolatedStorage\10v31ho4.bo2\eeolfu22.f2w\" /// User|Roaming: @"C:\Users\jerem\AppData\Roaming\IsolatedStorage\" /// Machine: @"C:\ProgramData\IsolatedStorage\nin03cyc.wr0\o3j0urs3.0sn\" /// /// Identity for the current store gets tacked on after this. /// </summary> internal static string GetRootDirectory(IsolatedStorageScope scope) { if (IsRoaming(scope)) { if (string.IsNullOrEmpty(s_roamingUserRootDirectory)) { s_roamingUserRootDirectory = GetDataDirectory(scope); } return s_roamingUserRootDirectory; } if (IsMachine(scope)) { if (string.IsNullOrEmpty(s_machineRootDirectory)) { s_machineRootDirectory = GetRandomDirectory(GetDataDirectory(scope), scope); } return s_machineRootDirectory; } if (string.IsNullOrEmpty(s_userRootDirectory)) s_userRootDirectory = GetRandomDirectory(GetDataDirectory(scope), scope); return s_userRootDirectory; } internal static bool IsMachine(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Machine) != 0); internal static bool IsAssembly(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Assembly) != 0); internal static bool IsApplication(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Application) != 0); internal static bool IsRoaming(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Roaming) != 0); internal static bool IsDomain(IsolatedStorageScope scope) => ((scope & IsolatedStorageScope.Domain) != 0); } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/MinAcross.Vector128.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MinAcross_Vector128_Single() { var test = new SimpleUnaryOpTest__MinAcross_Vector128_Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__MinAcross_Vector128_Single { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__MinAcross_Vector128_Single testClass) { var result = AdvSimd.Arm64.MinAcross(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__MinAcross_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__MinAcross_Vector128_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__MinAcross_Vector128_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.MinAcross( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MinAcross), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MinAcross), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.MinAcross( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = AdvSimd.Arm64.MinAcross(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Arm64.MinAcross(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__MinAcross_Vector128_Single(); var result = AdvSimd.Arm64.MinAcross(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__MinAcross_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.MinAcross(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MinAcross(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(Helpers.MinAcross(firstOp)) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (int i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.MinAcross)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MinAcross_Vector128_Single() { var test = new SimpleUnaryOpTest__MinAcross_Vector128_Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__MinAcross_Vector128_Single { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleUnaryOpTest__MinAcross_Vector128_Single testClass) { var result = AdvSimd.Arm64.MinAcross(_fld1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleUnaryOpTest__MinAcross_Vector128_Single testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar1; private Vector128<Single> _fld1; private DataTable _dataTable; static SimpleUnaryOpTest__MinAcross_Vector128_Single() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleUnaryOpTest__MinAcross_Vector128_Single() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.MinAcross( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MinAcross), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.MinAcross), new Type[] { typeof(Vector128<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.MinAcross( _clsVar1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) { var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(pClsVar1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var result = AdvSimd.Arm64.MinAcross(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var result = AdvSimd.Arm64.MinAcross(op1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleUnaryOpTest__MinAcross_Vector128_Single(); var result = AdvSimd.Arm64.MinAcross(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleUnaryOpTest__MinAcross_Vector128_Single(); fixed (Vector128<Single>* pFld1 = &test._fld1) { var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.MinAcross(_fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) { var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(pFld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MinAcross(test._fld1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.MinAcross( AdvSimd.LoadVector128((Single*)(&test._fld1)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(Helpers.MinAcross(firstOp)) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (int i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.MinAcross)}<Single>(Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/Common/tests/System/Net/Http/HttpClientHandlerTest.Cookies.cs
// 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.Diagnostics; using System.Linq; using System.Net.Test.Common; using System.Threading.Tasks; using Microsoft.DotNet.XUnitExtensions; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { #if WINHTTPHANDLER_TEST using HttpClientHandler = System.Net.Http.WinHttpClientHandler; #endif public abstract class HttpClientHandlerTest_Cookies : HttpClientHandlerTestBase { private const string s_cookieName = "ABC"; private const string s_cookieValue = "123"; private const string s_expectedCookieHeaderValue = "ABC=123"; private const string s_customCookieHeaderValue = "CustomCookie=456"; private const string s_simpleContent = "Hello world!"; public HttpClientHandlerTest_Cookies(ITestOutputHelper output) : base(output) { } // // Send cookie tests // private static CookieContainer CreateSingleCookieContainer(Uri uri) => CreateSingleCookieContainer(uri, s_cookieName, s_cookieValue); private static CookieContainer CreateSingleCookieContainer(Uri uri, string cookieName, string cookieValue) { var container = new CookieContainer(); container.Add(uri, new Cookie(cookieName, cookieValue)); return container; } private static string GetCookieHeaderValue(string cookieName, string cookieValue) => $"{cookieName}={cookieValue}"; [Fact] public async Task GetAsync_DefaultCoookieContainer_NoCookieSent() { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using (HttpClient client = CreateHttpClient()) { await client.GetAsync(uri); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); Assert.Equal(0, requestData.GetHeaderValueCount("Cookie")); }); } [Theory] [MemberData(nameof(CookieNamesValuesAndUseCookies))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue, bool useCookies) { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(uri, cookieName, cookieValue); handler.UseCookies = useCookies; using (HttpClient client = CreateHttpClient(handler)) { await client.GetAsync(uri); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); if (useCookies) { Assert.Equal(GetCookieHeaderValue(cookieName, cookieValue), requestData.GetSingleHeaderValue("Cookie")); } else { Assert.Equal(0, requestData.GetHeaderValueCount("Cookie")); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_SetCookieContainerMultipleCookies_CookiesSent() { var cookies = new Cookie[] { new Cookie("hello", "world"), new Cookie("foo", "bar"), new Cookie("ABC", "123") }; await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { HttpClientHandler handler = CreateHttpClientHandler(); var cookieContainer = new CookieContainer(); foreach (Cookie c in cookies) { cookieContainer.Add(uri, c); } handler.CookieContainer = cookieContainer; using (HttpClient client = CreateHttpClient(handler)) { await client.GetAsync(uri); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); string expectedHeaderValue = string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}").ToArray()); Assert.Equal(expectedHeaderValue, requestData.GetSingleHeaderValue("Cookie")); }); } [Fact] public async Task GetAsync_AddCookieHeader_CookieHeaderSent() { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using (HttpClient client = CreateHttpClient()) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri) { Version = UseVersion }; requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue); await client.SendAsync(TestAsync, requestMessage); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); Assert.Equal(s_customCookieHeaderValue, requestData.GetSingleHeaderValue("Cookie")); }); } [Fact] public async Task GetAsync_AddMultipleCookieHeaders_CookiesSent() { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using (HttpClient client = CreateHttpClient()) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri) { Version = UseVersion }; requestMessage.Headers.Add("Cookie", "A=1"); requestMessage.Headers.Add("Cookie", "B=2"); requestMessage.Headers.Add("Cookie", "C=3"); await client.SendAsync(TestAsync, requestMessage); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); // Multiple Cookie header values are treated as any other header values and are // concatenated using ", " as the separator. string cookieHeaderValue = requestData.GetSingleHeaderValue("Cookie"); var cookieValues = cookieHeaderValue.Split(new string[] { ", " }, StringSplitOptions.None); Assert.Contains("A=1", cookieValues); Assert.Contains("B=2", cookieValues); Assert.Contains("C=3", cookieValues); Assert.Equal(3, cookieValues.Count()); }); } private string GetCookieValue(HttpRequestData request) { #if !NETFRAMEWORK if (LoopbackServerFactory.Version < HttpVersion.Version20) #else if (LoopbackServerFactory.Version < HttpVersion20.Value) #endif { // HTTP/1.x must have only one value. return request.GetSingleHeaderValue("Cookie"); } string cookieHeaderValue = null; string[] cookieHeaderValues = request.GetHeaderValues("Cookie"); foreach (string header in cookieHeaderValues) { if (cookieHeaderValue == null) { cookieHeaderValue = header; } else { // rfc7540 8.1.2.5 states multiple cookie headers should be represented as single value. cookieHeaderValue = String.Concat(cookieHeaderValue, "; ", header); } } return cookieHeaderValue; } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_SetCookieContainerAndCookieHeader_BothCookiesSent() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = CreateHttpClient(handler)) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, url) { Version = UseVersion }; requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue); Task<HttpResponseMessage> getResponseTask = client.SendAsync(TestAsync, requestMessage); Task<HttpRequestData> serverTask = server.HandleRequestAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); HttpRequestData requestData = await serverTask; string cookieHeaderValue = GetCookieValue(requestData); var cookies = cookieHeaderValue.Split(new string[] { "; " }, StringSplitOptions.None); Assert.Contains(s_expectedCookieHeaderValue, cookies); Assert.Contains(s_customCookieHeaderValue, cookies); Assert.Equal(2, cookies.Count()); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_SetCookieContainerAndMultipleCookieHeaders_BothCookiesSent() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = CreateHttpClient(handler)) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, url) { Version = UseVersion }; requestMessage.Headers.Add("Cookie", "A=1"); requestMessage.Headers.Add("Cookie", "B=2"); Task<HttpResponseMessage> getResponseTask = client.SendAsync(TestAsync, requestMessage); Task<HttpRequestData> serverTask = server.HandleRequestAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); HttpRequestData requestData = await serverTask; string cookieHeaderValue = GetCookieValue(requestData); // Multiple Cookie header values are treated as any other header values and are // concatenated using ", " as the separator. The container cookie is concatenated to // one of these values using the "; " cookie separator. var cookieValues = cookieHeaderValue.Split(new string[] { ", " }, StringSplitOptions.None); Assert.Equal(2, cookieValues.Count()); // Find container cookie and remove it so we can validate the rest of the cookie header values bool sawContainerCookie = false; for (int i = 0; i < cookieValues.Length; i++) { if (cookieValues[i].Contains(';')) { Assert.False(sawContainerCookie); var cookies = cookieValues[i].Split(new string[] { "; " }, StringSplitOptions.None); Assert.Equal(2, cookies.Count()); Assert.Contains(s_expectedCookieHeaderValue, cookies); sawContainerCookie = true; cookieValues[i] = cookies.Where(c => c != s_expectedCookieHeaderValue).Single(); } } Assert.Contains("A=1", cookieValues); Assert.Contains("B=2", cookieValues); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsyncWithRedirect_SetCookieContainer_CorrectCookiesSent() { if (UseVersion == HttpVersion30) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56870")] return; } const string path1 = "/foo"; const string path2 = "/bar"; const string unusedPath = "/unused"; await LoopbackServerFactory.CreateClientAndServerAsync(async url => { Uri url1 = new Uri(url, path1); Uri url2 = new Uri(url, path2); Uri unusedUrl = new Uri(url, unusedPath); HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = new CookieContainer(); handler.CookieContainer.Add(url1, new Cookie("cookie1", "value1", path1)); handler.CookieContainer.Add(url2, new Cookie("cookie2", "value2", path2)); handler.CookieContainer.Add(unusedUrl, new Cookie("cookie3", "value3", unusedPath)); using (HttpClient client = CreateHttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling await client.GetAsync(url1); } }, async server => { HttpRequestData requestData1 = await server.HandleRequestAsync(HttpStatusCode.Found, new HttpHeaderData[] { new HttpHeaderData("Location", path2) }); Assert.Equal("cookie1=value1", requestData1.GetSingleHeaderValue("Cookie")); HttpRequestData requestData2 = await server.HandleRequestAsync(content: s_simpleContent); Assert.Equal("cookie2=value2", requestData2.GetSingleHeaderValue("Cookie")); }); } // // Receive cookie tests // [Theory] [MemberData(nameof(CookieNamesValuesAndUseCookies))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveSetCookieHeader_CookieAdded(string cookieName, string cookieValue, bool useCookies) { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseCookies = useCookies; using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", GetCookieHeaderValue(cookieName, cookieValue)) }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); if (useCookies) { Assert.Equal(1, collection.Count); Assert.Equal(cookieName, collection[0].Name); Assert.Equal(cookieValue, collection[0].Value); } else { Assert.Equal(0, collection.Count); } } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveMultipleSetCookieHeaders_CookieAdded() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "A=1; Path=/"), new HttpHeaderData("Set-Cookie", "B=2; Path=/"), new HttpHeaderData("Set-Cookie", "C=3; Path=/") }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(3, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); } // Default path should be calculated according to https://tools.ietf.org/html/rfc6265#section-5.1.4 // When a cookie is being sent without an explicitly defined Path for a URL with URL-Path /path/sub, // the cookie should be added with Path=/path. // ConditionalFact: CookieContainer does not follow RFC6265 on .NET Framework, therefore the (WinHttpHandler) test is expected to fail [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetFramework))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_NoPathDefined_CookieAddedWithDefaultPath() { await LoopbackServerFactory.CreateServerAsync(async (server, serverUrl) => { Uri requestUrl = new Uri(serverUrl, "path/sub"); HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(requestUrl); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "A=1"), }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); Cookie cookie = handler.CookieContainer.GetCookies(requestUrl)[0]; Assert.Equal("/path", cookie.Path); } }); } // According to RFC6265, cookie path is not expected to match the request's path, // these cookies should be accepted by the client. // ConditionalFact: CookieContainer does not follow RFC6265 on .NET Framework, therefore the (WinHttpHandler) test is expected to fail [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetFramework))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_CookiePathDoesNotMatchRequestPath_CookieAccepted() { await LoopbackServerFactory.CreateServerAsync(async (server, serverUrl) => { Uri requestUrl = new Uri(serverUrl, "original"); Uri otherUrl = new Uri(serverUrl, "other"); HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(requestUrl); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new[] { new HttpHeaderData("Set-Cookie", "A=1; Path=/other"), }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); Cookie cookie = handler.CookieContainer.GetCookies(otherUrl)[0]; Assert.Equal("/other", cookie.Path); } }); } // Based on the OIDC login scenario described in comments: // https://github.com/dotnet/runtime/pull/39250#issuecomment-659783480 // https://github.com/dotnet/runtime/issues/26141#issuecomment-612097147 // ConditionalFact: CookieContainer does not follow RFC6265 on .NET Framework, therefore the (WinHttpHandler) test is expected to fail [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetFramework))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_Redirect_CookiesArePreserved() { if (UseVersion == HttpVersion30) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56870")] return; } HttpClientHandler handler = CreateHttpClientHandler(); string loginPath = "/login/user"; string returnPath = "/return"; await LoopbackServerFactory.CreateClientAndServerAsync(async serverUrl => { Uri loginUrl = new Uri(serverUrl, loginPath); Uri returnUrl = new Uri(serverUrl, returnPath); CookieContainer cookies = handler.CookieContainer; using (HttpClient client = CreateHttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling HttpResponseMessage response = await client.GetAsync(loginUrl); string content = await response.Content.ReadAsStringAsync(); Assert.Equal(s_simpleContent, content); Cookie cookie = handler.CookieContainer.GetCookies(returnUrl)[0]; Assert.Equal("LoggedIn", cookie.Name); } }, async server => { HttpRequestData requestData1 = await server.HandleRequestAsync(HttpStatusCode.Found, new[] { new HttpHeaderData("Location", returnPath), new HttpHeaderData("Set-Cookie", "LoggedIn=true; Path=/return"), }); Assert.Equal(0, requestData1.GetHeaderValueCount("Cookie")); HttpRequestData requestData2 = await server.HandleRequestAsync(content: s_simpleContent, headers: new[]{ new HttpHeaderData("Set-Cookie", "LoggedIn=true; Path=/return"), }); Assert.Equal("LoggedIn=true", requestData2.GetSingleHeaderValue("Cookie")); }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveSetCookieHeader_CookieUpdated() { const string newCookieValue = "789"; await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", $"{s_cookieName}={newCookieValue}") }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(1, collection.Count); Assert.Equal(s_cookieName, collection[0].Name); Assert.Equal(newCookieValue, collection[0].Value); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveSetCookieHeader_CookieRemoved() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", $"{s_cookieName}=; Expires=Sun, 06 Nov 1994 08:49:37 GMT") }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(0, collection.Count); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveInvalidSetCookieHeader_ValidCookiesAdded() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "A=1; Path=/;Expires=asdfsadgads"), // invalid Expires new HttpHeaderData("Set-Cookie", "B=2; Path=/"), new HttpHeaderData("Set-Cookie", "C=3; Path=/") }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsyncWithRedirect_ReceiveSetCookie_CookieSent() { if (UseVersion == HttpVersion30) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56870")] return; } const string path1 = "/foo"; const string path2 = "/bar"; await LoopbackServerFactory.CreateClientAndServerAsync(async url => { Uri url1 = new Uri(url, path1); HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling await client.GetAsync(url1); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[2]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); } }, async server => { HttpRequestData requestData1 = await server.HandleRequestAsync( HttpStatusCode.Found, new HttpHeaderData[] { new HttpHeaderData("Location", $"{path2}"), new HttpHeaderData("Set-Cookie", "A=1; Path=/") }); Assert.Equal(0, requestData1.GetHeaderValueCount("Cookie")); HttpRequestData requestData2 = await server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "B=2; Path=/") }, s_simpleContent); Assert.Equal("A=1", requestData2.GetSingleHeaderValue("Cookie")); }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsyncWithBasicAuth_ReceiveSetCookie_CookieSent() { if (UseVersion == HttpVersion30) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56870")] return; } if (IsWinHttpHandler) { // Issue https://github.com/dotnet/runtime/issues/24979 // WinHttpHandler does not process the cookie. return; } await LoopbackServerFactory.CreateClientAndServerAsync(async url => { HttpClientHandler handler = CreateHttpClientHandler(); handler.Credentials = new NetworkCredential("user", "pass"); using (HttpClient client = CreateHttpClient(handler)) { await client.GetAsync(url); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[2]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); } }, async server => { HttpRequestData requestData1 = await server.HandleRequestAsync( HttpStatusCode.Unauthorized, new HttpHeaderData[] { new HttpHeaderData("WWW-Authenticate", "Basic realm=\"WallyWorld\""), new HttpHeaderData("Set-Cookie", "A=1; Path=/") }); Assert.Equal(0, requestData1.GetHeaderValueCount("Cookie")); HttpRequestData requestData2 = await server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "B=2; Path=/") }, s_simpleContent); Assert.Equal("A=1", requestData2.GetSingleHeaderValue("Cookie")); }); } // // MemberData stuff // private static string GenerateCookie(string name, char repeat, int overallHeaderValueLength) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length); int valueCount = overallHeaderValueLength - emptyHeaderValue.Length; return new string(repeat, valueCount); } public static IEnumerable<object[]> CookieNamesValuesAndUseCookies() { foreach (bool useCookies in BoolValues) { yield return new object[] { "ABC", "123", useCookies }; yield return new object[] { "Hello", "World", useCookies }; yield return new object[] { "foo", "bar", useCookies }; #if !NETFRAMEWORK yield return new object[] { "Hello World", "value", useCookies }; #endif yield return new object[] { ".AspNetCore.Session", "RAExEmXpoCbueP_QYM", useCookies }; yield return new object[] { ".AspNetCore.Antiforgery.Xam7_OeLcN4", "CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM", useCookies }; // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257), useCookies }; } } } public abstract class HttpClientHandlerTest_Cookies_Http11 : HttpClientHandlerTestBase { public HttpClientHandlerTest_Cookies_Http11(ITestOutputHelper output) : base(output) { } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveMultipleSetCookieHeaders_CookieAdded() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: A=1; Path=/\r\n" + $"Set-Cookie : B=2; Path=/\r\n" + // space before colon to verify header is trimmed and recognized $"Set-Cookie: C=3; Path=/\r\n", "Hello world!"); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(3, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); } } }
// 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.Diagnostics; using System.Linq; using System.Net.Test.Common; using System.Threading.Tasks; using Microsoft.DotNet.XUnitExtensions; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { #if WINHTTPHANDLER_TEST using HttpClientHandler = System.Net.Http.WinHttpClientHandler; #endif public abstract class HttpClientHandlerTest_Cookies : HttpClientHandlerTestBase { private const string s_cookieName = "ABC"; private const string s_cookieValue = "123"; private const string s_expectedCookieHeaderValue = "ABC=123"; private const string s_customCookieHeaderValue = "CustomCookie=456"; private const string s_simpleContent = "Hello world!"; public HttpClientHandlerTest_Cookies(ITestOutputHelper output) : base(output) { } // // Send cookie tests // private static CookieContainer CreateSingleCookieContainer(Uri uri) => CreateSingleCookieContainer(uri, s_cookieName, s_cookieValue); private static CookieContainer CreateSingleCookieContainer(Uri uri, string cookieName, string cookieValue) { var container = new CookieContainer(); container.Add(uri, new Cookie(cookieName, cookieValue)); return container; } private static string GetCookieHeaderValue(string cookieName, string cookieValue) => $"{cookieName}={cookieValue}"; [Fact] public async Task GetAsync_DefaultCoookieContainer_NoCookieSent() { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using (HttpClient client = CreateHttpClient()) { await client.GetAsync(uri); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); Assert.Equal(0, requestData.GetHeaderValueCount("Cookie")); }); } [Theory] [MemberData(nameof(CookieNamesValuesAndUseCookies))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue, bool useCookies) { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(uri, cookieName, cookieValue); handler.UseCookies = useCookies; using (HttpClient client = CreateHttpClient(handler)) { await client.GetAsync(uri); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); if (useCookies) { Assert.Equal(GetCookieHeaderValue(cookieName, cookieValue), requestData.GetSingleHeaderValue("Cookie")); } else { Assert.Equal(0, requestData.GetHeaderValueCount("Cookie")); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_SetCookieContainerMultipleCookies_CookiesSent() { var cookies = new Cookie[] { new Cookie("hello", "world"), new Cookie("foo", "bar"), new Cookie("ABC", "123") }; await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { HttpClientHandler handler = CreateHttpClientHandler(); var cookieContainer = new CookieContainer(); foreach (Cookie c in cookies) { cookieContainer.Add(uri, c); } handler.CookieContainer = cookieContainer; using (HttpClient client = CreateHttpClient(handler)) { await client.GetAsync(uri); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); string expectedHeaderValue = string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}").ToArray()); Assert.Equal(expectedHeaderValue, requestData.GetSingleHeaderValue("Cookie")); }); } [Fact] public async Task GetAsync_AddCookieHeader_CookieHeaderSent() { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using (HttpClient client = CreateHttpClient()) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri) { Version = UseVersion }; requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue); await client.SendAsync(TestAsync, requestMessage); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); Assert.Equal(s_customCookieHeaderValue, requestData.GetSingleHeaderValue("Cookie")); }); } [Fact] public async Task GetAsync_AddMultipleCookieHeaders_CookiesSent() { await LoopbackServerFactory.CreateClientAndServerAsync( async uri => { using (HttpClient client = CreateHttpClient()) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, uri) { Version = UseVersion }; requestMessage.Headers.Add("Cookie", "A=1"); requestMessage.Headers.Add("Cookie", "B=2"); requestMessage.Headers.Add("Cookie", "C=3"); await client.SendAsync(TestAsync, requestMessage); } }, async server => { HttpRequestData requestData = await server.HandleRequestAsync(); // Multiple Cookie header values are treated as any other header values and are // concatenated using ", " as the separator. string cookieHeaderValue = requestData.GetSingleHeaderValue("Cookie"); var cookieValues = cookieHeaderValue.Split(new string[] { ", " }, StringSplitOptions.None); Assert.Contains("A=1", cookieValues); Assert.Contains("B=2", cookieValues); Assert.Contains("C=3", cookieValues); Assert.Equal(3, cookieValues.Count()); }); } private string GetCookieValue(HttpRequestData request) { #if !NETFRAMEWORK if (LoopbackServerFactory.Version < HttpVersion.Version20) #else if (LoopbackServerFactory.Version < HttpVersion20.Value) #endif { // HTTP/1.x must have only one value. return request.GetSingleHeaderValue("Cookie"); } string cookieHeaderValue = null; string[] cookieHeaderValues = request.GetHeaderValues("Cookie"); foreach (string header in cookieHeaderValues) { if (cookieHeaderValue == null) { cookieHeaderValue = header; } else { // rfc7540 8.1.2.5 states multiple cookie headers should be represented as single value. cookieHeaderValue = String.Concat(cookieHeaderValue, "; ", header); } } return cookieHeaderValue; } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_SetCookieContainerAndCookieHeader_BothCookiesSent() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = CreateHttpClient(handler)) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, url) { Version = UseVersion }; requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue); Task<HttpResponseMessage> getResponseTask = client.SendAsync(TestAsync, requestMessage); Task<HttpRequestData> serverTask = server.HandleRequestAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); HttpRequestData requestData = await serverTask; string cookieHeaderValue = GetCookieValue(requestData); var cookies = cookieHeaderValue.Split(new string[] { "; " }, StringSplitOptions.None); Assert.Contains(s_expectedCookieHeaderValue, cookies); Assert.Contains(s_customCookieHeaderValue, cookies); Assert.Equal(2, cookies.Count()); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_SetCookieContainerAndMultipleCookieHeaders_BothCookiesSent() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = CreateHttpClient(handler)) { var requestMessage = new HttpRequestMessage(HttpMethod.Get, url) { Version = UseVersion }; requestMessage.Headers.Add("Cookie", "A=1"); requestMessage.Headers.Add("Cookie", "B=2"); Task<HttpResponseMessage> getResponseTask = client.SendAsync(TestAsync, requestMessage); Task<HttpRequestData> serverTask = server.HandleRequestAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); HttpRequestData requestData = await serverTask; string cookieHeaderValue = GetCookieValue(requestData); // Multiple Cookie header values are treated as any other header values and are // concatenated using ", " as the separator. The container cookie is concatenated to // one of these values using the "; " cookie separator. var cookieValues = cookieHeaderValue.Split(new string[] { ", " }, StringSplitOptions.None); Assert.Equal(2, cookieValues.Count()); // Find container cookie and remove it so we can validate the rest of the cookie header values bool sawContainerCookie = false; for (int i = 0; i < cookieValues.Length; i++) { if (cookieValues[i].Contains(';')) { Assert.False(sawContainerCookie); var cookies = cookieValues[i].Split(new string[] { "; " }, StringSplitOptions.None); Assert.Equal(2, cookies.Count()); Assert.Contains(s_expectedCookieHeaderValue, cookies); sawContainerCookie = true; cookieValues[i] = cookies.Where(c => c != s_expectedCookieHeaderValue).Single(); } } Assert.Contains("A=1", cookieValues); Assert.Contains("B=2", cookieValues); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsyncWithRedirect_SetCookieContainer_CorrectCookiesSent() { if (UseVersion == HttpVersion30) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56870")] return; } const string path1 = "/foo"; const string path2 = "/bar"; const string unusedPath = "/unused"; await LoopbackServerFactory.CreateClientAndServerAsync(async url => { Uri url1 = new Uri(url, path1); Uri url2 = new Uri(url, path2); Uri unusedUrl = new Uri(url, unusedPath); HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = new CookieContainer(); handler.CookieContainer.Add(url1, new Cookie("cookie1", "value1", path1)); handler.CookieContainer.Add(url2, new Cookie("cookie2", "value2", path2)); handler.CookieContainer.Add(unusedUrl, new Cookie("cookie3", "value3", unusedPath)); using (HttpClient client = CreateHttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling await client.GetAsync(url1); } }, async server => { HttpRequestData requestData1 = await server.HandleRequestAsync(HttpStatusCode.Found, new HttpHeaderData[] { new HttpHeaderData("Location", path2) }); Assert.Equal("cookie1=value1", requestData1.GetSingleHeaderValue("Cookie")); HttpRequestData requestData2 = await server.HandleRequestAsync(content: s_simpleContent); Assert.Equal("cookie2=value2", requestData2.GetSingleHeaderValue("Cookie")); }); } // // Receive cookie tests // [Theory] [MemberData(nameof(CookieNamesValuesAndUseCookies))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveSetCookieHeader_CookieAdded(string cookieName, string cookieValue, bool useCookies) { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseCookies = useCookies; using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", GetCookieHeaderValue(cookieName, cookieValue)) }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); if (useCookies) { Assert.Equal(1, collection.Count); Assert.Equal(cookieName, collection[0].Name); Assert.Equal(cookieValue, collection[0].Value); } else { Assert.Equal(0, collection.Count); } } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveMultipleSetCookieHeaders_CookieAdded() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "A=1; Path=/"), new HttpHeaderData("Set-Cookie", "B=2; Path=/"), new HttpHeaderData("Set-Cookie", "C=3; Path=/") }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(3, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); } // Default path should be calculated according to https://tools.ietf.org/html/rfc6265#section-5.1.4 // When a cookie is being sent without an explicitly defined Path for a URL with URL-Path /path/sub, // the cookie should be added with Path=/path. // ConditionalFact: CookieContainer does not follow RFC6265 on .NET Framework, therefore the (WinHttpHandler) test is expected to fail [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetFramework))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_NoPathDefined_CookieAddedWithDefaultPath() { await LoopbackServerFactory.CreateServerAsync(async (server, serverUrl) => { Uri requestUrl = new Uri(serverUrl, "path/sub"); HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(requestUrl); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "A=1"), }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); Cookie cookie = handler.CookieContainer.GetCookies(requestUrl)[0]; Assert.Equal("/path", cookie.Path); } }); } // According to RFC6265, cookie path is not expected to match the request's path, // these cookies should be accepted by the client. // ConditionalFact: CookieContainer does not follow RFC6265 on .NET Framework, therefore the (WinHttpHandler) test is expected to fail [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetFramework))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_CookiePathDoesNotMatchRequestPath_CookieAccepted() { await LoopbackServerFactory.CreateServerAsync(async (server, serverUrl) => { Uri requestUrl = new Uri(serverUrl, "original"); Uri otherUrl = new Uri(serverUrl, "other"); HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(requestUrl); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new[] { new HttpHeaderData("Set-Cookie", "A=1; Path=/other"), }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); Cookie cookie = handler.CookieContainer.GetCookies(otherUrl)[0]; Assert.Equal("/other", cookie.Path); } }); } // Based on the OIDC login scenario described in comments: // https://github.com/dotnet/runtime/pull/39250#issuecomment-659783480 // https://github.com/dotnet/runtime/issues/26141#issuecomment-612097147 // ConditionalFact: CookieContainer does not follow RFC6265 on .NET Framework, therefore the (WinHttpHandler) test is expected to fail [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotNetFramework))] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_Redirect_CookiesArePreserved() { if (UseVersion == HttpVersion30) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56870")] return; } HttpClientHandler handler = CreateHttpClientHandler(); string loginPath = "/login/user"; string returnPath = "/return"; await LoopbackServerFactory.CreateClientAndServerAsync(async serverUrl => { Uri loginUrl = new Uri(serverUrl, loginPath); Uri returnUrl = new Uri(serverUrl, returnPath); CookieContainer cookies = handler.CookieContainer; using (HttpClient client = CreateHttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling HttpResponseMessage response = await client.GetAsync(loginUrl); string content = await response.Content.ReadAsStringAsync(); Assert.Equal(s_simpleContent, content); Cookie cookie = handler.CookieContainer.GetCookies(returnUrl)[0]; Assert.Equal("LoggedIn", cookie.Name); } }, async server => { HttpRequestData requestData1 = await server.HandleRequestAsync(HttpStatusCode.Found, new[] { new HttpHeaderData("Location", returnPath), new HttpHeaderData("Set-Cookie", "LoggedIn=true; Path=/return"), }); Assert.Equal(0, requestData1.GetHeaderValueCount("Cookie")); HttpRequestData requestData2 = await server.HandleRequestAsync(content: s_simpleContent, headers: new[]{ new HttpHeaderData("Set-Cookie", "LoggedIn=true; Path=/return"), }); Assert.Equal("LoggedIn=true", requestData2.GetSingleHeaderValue("Cookie")); }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveSetCookieHeader_CookieUpdated() { const string newCookieValue = "789"; await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", $"{s_cookieName}={newCookieValue}") }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(1, collection.Count); Assert.Equal(s_cookieName, collection[0].Name); Assert.Equal(newCookieValue, collection[0].Value); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveSetCookieHeader_CookieRemoved() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", $"{s_cookieName}=; Expires=Sun, 06 Nov 1994 08:49:37 GMT") }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(0, collection.Count); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveInvalidSetCookieHeader_ValidCookiesAdded() { await LoopbackServerFactory.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<HttpRequestData> serverTask = server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "A=1; Path=/;Expires=asdfsadgads"), // invalid Expires new HttpHeaderData("Set-Cookie", "B=2; Path=/"), new HttpHeaderData("Set-Cookie", "C=3; Path=/") }, s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsyncWithRedirect_ReceiveSetCookie_CookieSent() { if (UseVersion == HttpVersion30) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56870")] return; } const string path1 = "/foo"; const string path2 = "/bar"; await LoopbackServerFactory.CreateClientAndServerAsync(async url => { Uri url1 = new Uri(url, path1); HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling await client.GetAsync(url1); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[2]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); } }, async server => { HttpRequestData requestData1 = await server.HandleRequestAsync( HttpStatusCode.Found, new HttpHeaderData[] { new HttpHeaderData("Location", $"{path2}"), new HttpHeaderData("Set-Cookie", "A=1; Path=/") }); Assert.Equal(0, requestData1.GetHeaderValueCount("Cookie")); HttpRequestData requestData2 = await server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "B=2; Path=/") }, s_simpleContent); Assert.Equal("A=1", requestData2.GetSingleHeaderValue("Cookie")); }); } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsyncWithBasicAuth_ReceiveSetCookie_CookieSent() { if (UseVersion == HttpVersion30) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/56870")] return; } if (IsWinHttpHandler) { // Issue https://github.com/dotnet/runtime/issues/24979 // WinHttpHandler does not process the cookie. return; } await LoopbackServerFactory.CreateClientAndServerAsync(async url => { HttpClientHandler handler = CreateHttpClientHandler(); handler.Credentials = new NetworkCredential("user", "pass"); using (HttpClient client = CreateHttpClient(handler)) { await client.GetAsync(url); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[2]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); } }, async server => { HttpRequestData requestData1 = await server.HandleRequestAsync( HttpStatusCode.Unauthorized, new HttpHeaderData[] { new HttpHeaderData("WWW-Authenticate", "Basic realm=\"WallyWorld\""), new HttpHeaderData("Set-Cookie", "A=1; Path=/") }); Assert.Equal(0, requestData1.GetHeaderValueCount("Cookie")); HttpRequestData requestData2 = await server.HandleRequestAsync( HttpStatusCode.OK, new HttpHeaderData[] { new HttpHeaderData("Set-Cookie", "B=2; Path=/") }, s_simpleContent); Assert.Equal("A=1", requestData2.GetSingleHeaderValue("Cookie")); }); } // // MemberData stuff // private static string GenerateCookie(string name, char repeat, int overallHeaderValueLength) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length); int valueCount = overallHeaderValueLength - emptyHeaderValue.Length; return new string(repeat, valueCount); } public static IEnumerable<object[]> CookieNamesValuesAndUseCookies() { foreach (bool useCookies in BoolValues) { yield return new object[] { "ABC", "123", useCookies }; yield return new object[] { "Hello", "World", useCookies }; yield return new object[] { "foo", "bar", useCookies }; #if !NETFRAMEWORK yield return new object[] { "Hello World", "value", useCookies }; #endif yield return new object[] { ".AspNetCore.Session", "RAExEmXpoCbueP_QYM", useCookies }; yield return new object[] { ".AspNetCore.Antiforgery.Xam7_OeLcN4", "CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM", useCookies }; // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257), useCookies }; } } } public abstract class HttpClientHandlerTest_Cookies_Http11 : HttpClientHandlerTestBase { public HttpClientHandlerTest_Cookies_Http11(ITestOutputHelper output) : base(output) { } [Fact] [SkipOnPlatform(TestPlatforms.Browser, "CookieContainer is not supported on Browser")] public async Task GetAsync_ReceiveMultipleSetCookieHeaders_CookieAdded() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = CreateHttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: A=1; Path=/\r\n" + $"Set-Cookie : B=2; Path=/\r\n" + // space before colon to verify header is trimmed and recognized $"Set-Cookie: C=3; Path=/\r\n", "Hello world!"); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(3, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/HardwareIntrinsics/Arm/Rdm.Arm64/Rdm.Arm64_ro.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="MultiplyRoundedDoublingAndAddSaturateHighScalar.Vector64.Int16.cs" /> <Compile Include="MultiplyRoundedDoublingAndAddSaturateHighScalar.Vector64.Int32.cs" /> <Compile Include="MultiplyRoundedDoublingAndSubtractSaturateHighScalar.Vector64.Int16.cs" /> <Compile Include="MultiplyRoundedDoublingAndSubtractSaturateHighScalar.Vector64.Int32.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh.Vector64.Int16.Vector64.Int16.3.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh.Vector64.Int16.Vector128.Int16.7.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh.Vector64.Int32.Vector64.Int32.1.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh.Vector64.Int32.Vector128.Int32.3.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh.Vector64.Int16.Vector64.Int16.3.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh.Vector64.Int16.Vector128.Int16.7.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh.Vector64.Int32.Vector64.Int32.1.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh.Vector64.Int32.Vector128.Int32.3.cs" /> <Compile Include="Program.Rdm.Arm64.cs" /> <Compile Include="..\Shared\Helpers.cs" /> <Compile Include="..\Shared\Program.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Embedded</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="MultiplyRoundedDoublingAndAddSaturateHighScalar.Vector64.Int16.cs" /> <Compile Include="MultiplyRoundedDoublingAndAddSaturateHighScalar.Vector64.Int32.cs" /> <Compile Include="MultiplyRoundedDoublingAndSubtractSaturateHighScalar.Vector64.Int16.cs" /> <Compile Include="MultiplyRoundedDoublingAndSubtractSaturateHighScalar.Vector64.Int32.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh.Vector64.Int16.Vector64.Int16.3.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh.Vector64.Int16.Vector128.Int16.7.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh.Vector64.Int32.Vector64.Int32.1.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh.Vector64.Int32.Vector128.Int32.3.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh.Vector64.Int16.Vector64.Int16.3.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh.Vector64.Int16.Vector128.Int16.7.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh.Vector64.Int32.Vector64.Int32.1.cs" /> <Compile Include="MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh.Vector64.Int32.Vector128.Int32.3.cs" /> <Compile Include="Program.Rdm.Arm64.cs" /> <Compile Include="..\Shared\Helpers.cs" /> <Compile Include="..\Shared\Program.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/jit64/gc/misc/test3.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="test3.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="test3.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M10/b09246/b09246.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; public class MyClass { //extern modifier public static int Main() { bool b = true; int exitcode = 0; b &= false; Console.WriteLine(b); b = b & false; Console.WriteLine(b); exitcode = b ? 1 : 100; b = false; Console.WriteLine(b); if (exitcode == 100) Console.WriteLine("Test passed."); else Console.WriteLine("Test failed."); return (exitcode); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; public class MyClass { //extern modifier public static int Main() { bool b = true; int exitcode = 0; b &= false; Console.WriteLine(b); b = b & false; Console.WriteLine(b); exitcode = b ? 1 : 100; b = false; Console.WriteLine(b); if (exitcode == 100) Console.WriteLine("Test passed."); else Console.WriteLine("Test failed."); return (exitcode); } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/ReleaseTests.cs
// 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.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public class ReleaseTests { [Fact] [SkipOnMono("ComWrappers are not supported on Mono")] public void Release_ValidPointer_Success() { var cw = new ComWrappersImpl(); IntPtr iUnknown = cw.GetOrCreateComInterfaceForObject(new object(), CreateComInterfaceFlags.None); try { Marshal.AddRef(iUnknown); Marshal.AddRef(iUnknown); Assert.Equal(2, Marshal.Release(iUnknown)); Assert.Equal(1, Marshal.Release(iUnknown)); Marshal.AddRef(iUnknown); Assert.Equal(1, Marshal.Release(iUnknown)); } finally { Assert.Equal(0, Marshal.Release(iUnknown)); } } [Fact] public void Release_ZeroPointer_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("pUnk", () => Marshal.Release(IntPtr.Zero)); } } }
// 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.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public class ReleaseTests { [Fact] [SkipOnMono("ComWrappers are not supported on Mono")] public void Release_ValidPointer_Success() { var cw = new ComWrappersImpl(); IntPtr iUnknown = cw.GetOrCreateComInterfaceForObject(new object(), CreateComInterfaceFlags.None); try { Marshal.AddRef(iUnknown); Marshal.AddRef(iUnknown); Assert.Equal(2, Marshal.Release(iUnknown)); Assert.Equal(1, Marshal.Release(iUnknown)); Marshal.AddRef(iUnknown); Assert.Equal(1, Marshal.Release(iUnknown)); } finally { Assert.Equal(0, Marshal.Release(iUnknown)); } } [Fact] public void Release_ZeroPointer_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("pUnk", () => Marshal.Release(IntPtr.Zero)); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Security.Cryptography.X509Certificates/tests/RSAOther.cs
// 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.Security.Cryptography.X509Certificates.Tests { internal class RSAOther : RSA { private readonly RSA _impl; internal RSAOther() { _impl = RSA.Create(); } public override int KeySize { get => _impl.KeySize; set => _impl.KeySize = value; } public override KeySizes[] LegalKeySizes => _impl.LegalKeySizes; public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => _impl.Decrypt(data, padding); public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => _impl.Encrypt(data, padding); public override RSAParameters ExportParameters(bool includePrivateParameters) => _impl.ExportParameters(includePrivateParameters); public override void ImportParameters(RSAParameters parameters) => _impl.ImportParameters(parameters); public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignData(data, offset, count, hashAlgorithm, padding); public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignData(data, hashAlgorithm, padding); public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignHash(hash, hashAlgorithm, padding); public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.VerifyData(data, offset, count, signature, hashAlgorithm, padding); public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.VerifyHash(hash, signature, hashAlgorithm, padding); protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { using (HashAlgorithm alg = GetHashAlgorithm(hashAlgorithm)) { return alg.ComputeHash(data, offset, count); } } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { using (HashAlgorithm alg = GetHashAlgorithm(hashAlgorithm)) { return alg.ComputeHash(data); } } protected override void Dispose(bool disposing) { if (disposing) { _impl.Dispose(); } base.Dispose(disposing); } internal static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithmName) { HashAlgorithm hasher; if (hashAlgorithmName == HashAlgorithmName.MD5) { hasher = MD5.Create(); } else if (hashAlgorithmName == HashAlgorithmName.SHA1) { hasher = SHA1.Create(); } else if (hashAlgorithmName == HashAlgorithmName.SHA256) { hasher = SHA256.Create(); } else if (hashAlgorithmName == HashAlgorithmName.SHA384) { hasher = SHA384.Create(); } else if (hashAlgorithmName == HashAlgorithmName.SHA512) { hasher = SHA512.Create(); } else { throw new NotSupportedException(); } return hasher; } } }
// 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.Security.Cryptography.X509Certificates.Tests { internal class RSAOther : RSA { private readonly RSA _impl; internal RSAOther() { _impl = RSA.Create(); } public override int KeySize { get => _impl.KeySize; set => _impl.KeySize = value; } public override KeySizes[] LegalKeySizes => _impl.LegalKeySizes; public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => _impl.Decrypt(data, padding); public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => _impl.Encrypt(data, padding); public override RSAParameters ExportParameters(bool includePrivateParameters) => _impl.ExportParameters(includePrivateParameters); public override void ImportParameters(RSAParameters parameters) => _impl.ImportParameters(parameters); public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignData(data, offset, count, hashAlgorithm, padding); public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignData(data, hashAlgorithm, padding); public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.SignHash(hash, hashAlgorithm, padding); public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.VerifyData(data, offset, count, signature, hashAlgorithm, padding); public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => _impl.VerifyHash(hash, signature, hashAlgorithm, padding); protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) { using (HashAlgorithm alg = GetHashAlgorithm(hashAlgorithm)) { return alg.ComputeHash(data, offset, count); } } protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) { using (HashAlgorithm alg = GetHashAlgorithm(hashAlgorithm)) { return alg.ComputeHash(data); } } protected override void Dispose(bool disposing) { if (disposing) { _impl.Dispose(); } base.Dispose(disposing); } internal static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithmName) { HashAlgorithm hasher; if (hashAlgorithmName == HashAlgorithmName.MD5) { hasher = MD5.Create(); } else if (hashAlgorithmName == HashAlgorithmName.SHA1) { hasher = SHA1.Create(); } else if (hashAlgorithmName == HashAlgorithmName.SHA256) { hasher = SHA256.Create(); } else if (hashAlgorithmName == HashAlgorithmName.SHA384) { hasher = SHA384.Create(); } else if (hashAlgorithmName == HashAlgorithmName.SHA512) { hasher = SHA512.Create(); } else { throw new NotSupportedException(); } return hasher; } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCng.Windows.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // This file is one of a group of files (AesCng.cs, TripleDESCng.cs) that are almost identical except // for the algorithm name. If you make a change to this file, there's a good chance you'll have to make // the same change to the other files so please check. This is a pain but given that the contracts demand // that each of these derive from a different class, it can't be helped. // using System.Runtime.Versioning; using Internal.Cryptography; using Internal.NativeCrypto; namespace System.Security.Cryptography { public sealed class AesCng : Aes, ICngSymmetricAlgorithm { [SupportedOSPlatform("windows")] public AesCng() { _core = new CngSymmetricAlgorithmCore(this); } [SupportedOSPlatform("windows")] public AesCng(string keyName) : this(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider) { } [SupportedOSPlatform("windows")] public AesCng(string keyName, CngProvider provider) : this(keyName, provider, CngKeyOpenOptions.None) { } [SupportedOSPlatform("windows")] public AesCng(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { _core = new CngSymmetricAlgorithmCore(this, keyName, provider, openOptions); } public override byte[] Key { get { return _core.GetKeyIfExportable(); } set { _core.SetKey(value); } } public override int KeySize { get { return base.KeySize; } set { _core.SetKeySize(value, this); } } public override ICryptoTransform CreateDecryptor() { // Do not change to CreateDecryptor(this.Key, this.IV). this.Key throws if a non-exportable hardware key is being used. return _core.CreateDecryptor(); } public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { return _core.CreateDecryptor(rgbKey, rgbIV); } public override ICryptoTransform CreateEncryptor() { // Do not change to CreateEncryptor(this.Key, this.IV). this.Key throws if a non-exportable hardware key is being used. return _core.CreateEncryptor(); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { return _core.CreateEncryptor(rgbKey, rgbIV); } public override void GenerateKey() { _core.GenerateKey(); } public override void GenerateIV() { _core.GenerateIV(); } protected override bool TryDecryptEcbCore( ReadOnlySpan<byte> ciphertext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv: default, encrypting: false, paddingMode, CipherMode.ECB, feedbackSizeInBits: 0); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptEcbCore( ReadOnlySpan<byte> plaintext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv: default, encrypting: true, paddingMode, CipherMode.ECB, feedbackSizeInBits: 0); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override bool TryEncryptCbcCore( ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv, encrypting: true, paddingMode, CipherMode.CBC, feedbackSizeInBits: 0); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override bool TryDecryptCbcCore( ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv, encrypting: false, paddingMode, CipherMode.CBC, feedbackSizeInBits: 0); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryDecryptCfbCore( ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv, encrypting: false, paddingMode, CipherMode.CFB, feedbackSizeInBits); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptCfbCore( ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv, encrypting: true, paddingMode, CipherMode.CFB, feedbackSizeInBits); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); } byte[] ICngSymmetricAlgorithm.BaseKey { get { return base.Key; } set { base.Key = value; } } int ICngSymmetricAlgorithm.BaseKeySize { get { return base.KeySize; } set { base.KeySize = value; } } bool ICngSymmetricAlgorithm.IsWeakKey(byte[] key) { return false; } int ICngSymmetricAlgorithm.GetPaddingSize(CipherMode mode, int feedbackSizeBits) { return this.GetPaddingSize(mode, feedbackSizeBits); } SafeAlgorithmHandle ICngSymmetricAlgorithm.GetEphemeralModeHandle(CipherMode mode, int feedbackSizeInBits) { try { return AesBCryptModes.GetSharedHandle(mode, feedbackSizeInBits / 8); } catch (NotSupportedException) { throw new CryptographicException(SR.Cryptography_InvalidCipherMode); } } string ICngSymmetricAlgorithm.GetNCryptAlgorithmIdentifier() { return Cng.BCRYPT_AES_ALGORITHM; } byte[] ICngSymmetricAlgorithm.PreprocessKey(byte[] key) { return key; } bool ICngSymmetricAlgorithm.IsValidEphemeralFeedbackSize(int feedbackSizeInBits) { return feedbackSizeInBits == 8 || feedbackSizeInBits == 128; } private CngSymmetricAlgorithmCore _core; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // This file is one of a group of files (AesCng.cs, TripleDESCng.cs) that are almost identical except // for the algorithm name. If you make a change to this file, there's a good chance you'll have to make // the same change to the other files so please check. This is a pain but given that the contracts demand // that each of these derive from a different class, it can't be helped. // using System.Runtime.Versioning; using Internal.Cryptography; using Internal.NativeCrypto; namespace System.Security.Cryptography { public sealed class AesCng : Aes, ICngSymmetricAlgorithm { [SupportedOSPlatform("windows")] public AesCng() { _core = new CngSymmetricAlgorithmCore(this); } [SupportedOSPlatform("windows")] public AesCng(string keyName) : this(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider) { } [SupportedOSPlatform("windows")] public AesCng(string keyName, CngProvider provider) : this(keyName, provider, CngKeyOpenOptions.None) { } [SupportedOSPlatform("windows")] public AesCng(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { _core = new CngSymmetricAlgorithmCore(this, keyName, provider, openOptions); } public override byte[] Key { get { return _core.GetKeyIfExportable(); } set { _core.SetKey(value); } } public override int KeySize { get { return base.KeySize; } set { _core.SetKeySize(value, this); } } public override ICryptoTransform CreateDecryptor() { // Do not change to CreateDecryptor(this.Key, this.IV). this.Key throws if a non-exportable hardware key is being used. return _core.CreateDecryptor(); } public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[]? rgbIV) { return _core.CreateDecryptor(rgbKey, rgbIV); } public override ICryptoTransform CreateEncryptor() { // Do not change to CreateEncryptor(this.Key, this.IV). this.Key throws if a non-exportable hardware key is being used. return _core.CreateEncryptor(); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[]? rgbIV) { return _core.CreateEncryptor(rgbKey, rgbIV); } public override void GenerateKey() { _core.GenerateKey(); } public override void GenerateIV() { _core.GenerateIV(); } protected override bool TryDecryptEcbCore( ReadOnlySpan<byte> ciphertext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv: default, encrypting: false, paddingMode, CipherMode.ECB, feedbackSizeInBits: 0); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptEcbCore( ReadOnlySpan<byte> plaintext, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv: default, encrypting: true, paddingMode, CipherMode.ECB, feedbackSizeInBits: 0); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override bool TryEncryptCbcCore( ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv, encrypting: true, paddingMode, CipherMode.CBC, feedbackSizeInBits: 0); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override bool TryDecryptCbcCore( ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv, encrypting: false, paddingMode, CipherMode.CBC, feedbackSizeInBits: 0); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryDecryptCfbCore( ReadOnlySpan<byte> ciphertext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv, encrypting: false, paddingMode, CipherMode.CFB, feedbackSizeInBits); using (cipher) { return UniversalCryptoOneShot.OneShotDecrypt(cipher, paddingMode, ciphertext, destination, out bytesWritten); } } protected override bool TryEncryptCfbCore( ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> iv, Span<byte> destination, PaddingMode paddingMode, int feedbackSizeInBits, out int bytesWritten) { ILiteSymmetricCipher cipher = _core.CreateLiteSymmetricCipher( iv, encrypting: true, paddingMode, CipherMode.CFB, feedbackSizeInBits); using (cipher) { return UniversalCryptoOneShot.OneShotEncrypt(cipher, paddingMode, plaintext, destination, out bytesWritten); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); } byte[] ICngSymmetricAlgorithm.BaseKey { get { return base.Key; } set { base.Key = value; } } int ICngSymmetricAlgorithm.BaseKeySize { get { return base.KeySize; } set { base.KeySize = value; } } bool ICngSymmetricAlgorithm.IsWeakKey(byte[] key) { return false; } int ICngSymmetricAlgorithm.GetPaddingSize(CipherMode mode, int feedbackSizeBits) { return this.GetPaddingSize(mode, feedbackSizeBits); } SafeAlgorithmHandle ICngSymmetricAlgorithm.GetEphemeralModeHandle(CipherMode mode, int feedbackSizeInBits) { try { return AesBCryptModes.GetSharedHandle(mode, feedbackSizeInBits / 8); } catch (NotSupportedException) { throw new CryptographicException(SR.Cryptography_InvalidCipherMode); } } string ICngSymmetricAlgorithm.GetNCryptAlgorithmIdentifier() { return Cng.BCRYPT_AES_ALGORITHM; } byte[] ICngSymmetricAlgorithm.PreprocessKey(byte[] key) { return key; } bool ICngSymmetricAlgorithm.IsValidEphemeralFeedbackSize(int feedbackSizeInBits) { return feedbackSizeInBits == 8 || feedbackSizeInBits == 128; } private CngSymmetricAlgorithmCore _core; } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/Microsoft.Extensions.Configuration.UserSecrets/src/UserSecretsConfigurationExtensions.cs
// 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.IO; using System.Reflection; using Microsoft.Extensions.Configuration.UserSecrets; using Microsoft.Extensions.FileProviders; namespace Microsoft.Extensions.Configuration { /// <summary> /// Configuration extensions for adding user secrets configuration source. /// </summary> public static class UserSecretsConfigurationExtensions { /// <summary> /// <para> /// Adds the user secrets configuration source. Searches the assembly that contains type <typeparamref name="T"/> /// for an instance of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <typeparam name="T">The type from the assembly to search for an instance of <see cref="UserSecretsIdAttribute"/>.</typeparam> /// <exception cref="InvalidOperationException">Thrown when the assembly containing <typeparamref name="T"/> does not have <see cref="UserSecretsIdAttribute"/>.</exception> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration) where T : class => configuration.AddUserSecrets(typeof(T).Assembly, optional: true, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source. Searches the assembly that contains type <typeparamref name="T"/> /// for an instance of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="optional">Whether loading secrets is optional. When false, this method may throw.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="optional"/> is false and the assembly containing <typeparamref name="T"/> does not have a valid <see cref="UserSecretsIdAttribute"/>.</exception> /// <typeparam name="T">The type from the assembly to search for an instance of <see cref="UserSecretsIdAttribute"/>.</typeparam> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration, bool optional) where T : class => configuration.AddUserSecrets(typeof(T).Assembly, optional, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source. Searches the assembly that contains type <typeparamref name="T"/> /// for an instance of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="optional">Whether loading secrets is optional. When false, this method may throw.</param> /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="optional"/> is false and the assembly containing <typeparamref name="T"/> does not have a valid <see cref="UserSecretsIdAttribute"/>.</exception> /// <typeparam name="T">The type from the assembly to search for an instance of <see cref="UserSecretsIdAttribute"/>.</typeparam> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration, bool optional, bool reloadOnChange) where T : class => configuration.AddUserSecrets(typeof(T).Assembly, optional, reloadOnChange); /// <summary> /// <para> /// Adds the user secrets configuration source. This searches <paramref name="assembly"/> for an instance /// of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="assembly">The assembly with the <see cref="UserSecretsIdAttribute" />.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="assembly"/> does not have a valid <see cref="UserSecretsIdAttribute"/></exception> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly) => configuration.AddUserSecrets(assembly, optional: true, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source. This searches <paramref name="assembly"/> for an instance /// of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="assembly">The assembly with the <see cref="UserSecretsIdAttribute" />.</param> /// <param name="optional">Whether loading secrets is optional. When false, this method may throw.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="optional"/> is false and <paramref name="assembly"/> does not have a valid <see cref="UserSecretsIdAttribute"/>.</exception> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly, bool optional) => configuration.AddUserSecrets(assembly, optional, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source. This searches <paramref name="assembly"/> for an instance /// of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="assembly">The assembly with the <see cref="UserSecretsIdAttribute" />.</param> /// <param name="optional">Whether loading secrets is optional. When false, this method may throw.</param> /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="optional"/> is false and <paramref name="assembly"/> does not have a valid <see cref="UserSecretsIdAttribute"/>.</exception> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration!!, Assembly assembly!!, bool optional, bool reloadOnChange) { UserSecretsIdAttribute? attribute = assembly.GetCustomAttribute<UserSecretsIdAttribute>(); if (attribute != null) { return AddUserSecretsInternal(configuration, attribute.UserSecretsId, optional, reloadOnChange); } if (!optional) { throw new InvalidOperationException(SR.Format(SR.Error_Missing_UserSecretsIdAttribute, assembly.GetName().Name)); } return configuration; } /// <summary> /// <para> /// Adds the user secrets configuration source with specified user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="userSecretsId">The user secrets ID.</param> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, string userSecretsId) => configuration.AddUserSecrets(userSecretsId, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source with specified user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="userSecretsId">The user secrets ID.</param> /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, string userSecretsId, bool reloadOnChange) => AddUserSecretsInternal(configuration, userSecretsId, true, reloadOnChange); private static IConfigurationBuilder AddUserSecretsInternal(IConfigurationBuilder configuration!!, string userSecretsId!!, bool optional, bool reloadOnChange) { return AddSecretsFile(configuration, PathHelper.GetSecretsPathFromSecretsId(userSecretsId), optional, reloadOnChange); } private static IConfigurationBuilder AddSecretsFile(IConfigurationBuilder configuration, string secretPath, bool optional, bool reloadOnChange) { string? directoryPath = Path.GetDirectoryName(secretPath); PhysicalFileProvider? fileProvider = Directory.Exists(directoryPath) ? new PhysicalFileProvider(directoryPath) : null; return configuration.AddJsonFile(fileProvider, PathHelper.SecretsFileName, optional, reloadOnChange); } } }
// 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.IO; using System.Reflection; using Microsoft.Extensions.Configuration.UserSecrets; using Microsoft.Extensions.FileProviders; namespace Microsoft.Extensions.Configuration { /// <summary> /// Configuration extensions for adding user secrets configuration source. /// </summary> public static class UserSecretsConfigurationExtensions { /// <summary> /// <para> /// Adds the user secrets configuration source. Searches the assembly that contains type <typeparamref name="T"/> /// for an instance of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <typeparam name="T">The type from the assembly to search for an instance of <see cref="UserSecretsIdAttribute"/>.</typeparam> /// <exception cref="InvalidOperationException">Thrown when the assembly containing <typeparamref name="T"/> does not have <see cref="UserSecretsIdAttribute"/>.</exception> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration) where T : class => configuration.AddUserSecrets(typeof(T).Assembly, optional: true, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source. Searches the assembly that contains type <typeparamref name="T"/> /// for an instance of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="optional">Whether loading secrets is optional. When false, this method may throw.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="optional"/> is false and the assembly containing <typeparamref name="T"/> does not have a valid <see cref="UserSecretsIdAttribute"/>.</exception> /// <typeparam name="T">The type from the assembly to search for an instance of <see cref="UserSecretsIdAttribute"/>.</typeparam> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration, bool optional) where T : class => configuration.AddUserSecrets(typeof(T).Assembly, optional, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source. Searches the assembly that contains type <typeparamref name="T"/> /// for an instance of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="optional">Whether loading secrets is optional. When false, this method may throw.</param> /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="optional"/> is false and the assembly containing <typeparamref name="T"/> does not have a valid <see cref="UserSecretsIdAttribute"/>.</exception> /// <typeparam name="T">The type from the assembly to search for an instance of <see cref="UserSecretsIdAttribute"/>.</typeparam> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets<T>(this IConfigurationBuilder configuration, bool optional, bool reloadOnChange) where T : class => configuration.AddUserSecrets(typeof(T).Assembly, optional, reloadOnChange); /// <summary> /// <para> /// Adds the user secrets configuration source. This searches <paramref name="assembly"/> for an instance /// of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="assembly">The assembly with the <see cref="UserSecretsIdAttribute" />.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="assembly"/> does not have a valid <see cref="UserSecretsIdAttribute"/></exception> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly) => configuration.AddUserSecrets(assembly, optional: true, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source. This searches <paramref name="assembly"/> for an instance /// of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="assembly">The assembly with the <see cref="UserSecretsIdAttribute" />.</param> /// <param name="optional">Whether loading secrets is optional. When false, this method may throw.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="optional"/> is false and <paramref name="assembly"/> does not have a valid <see cref="UserSecretsIdAttribute"/>.</exception> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly, bool optional) => configuration.AddUserSecrets(assembly, optional, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source. This searches <paramref name="assembly"/> for an instance /// of <see cref="UserSecretsIdAttribute"/>, which specifies a user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="assembly">The assembly with the <see cref="UserSecretsIdAttribute" />.</param> /// <param name="optional">Whether loading secrets is optional. When false, this method may throw.</param> /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> /// <exception cref="InvalidOperationException">Thrown when <paramref name="optional"/> is false and <paramref name="assembly"/> does not have a valid <see cref="UserSecretsIdAttribute"/>.</exception> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration!!, Assembly assembly!!, bool optional, bool reloadOnChange) { UserSecretsIdAttribute? attribute = assembly.GetCustomAttribute<UserSecretsIdAttribute>(); if (attribute != null) { return AddUserSecretsInternal(configuration, attribute.UserSecretsId, optional, reloadOnChange); } if (!optional) { throw new InvalidOperationException(SR.Format(SR.Error_Missing_UserSecretsIdAttribute, assembly.GetName().Name)); } return configuration; } /// <summary> /// <para> /// Adds the user secrets configuration source with specified user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="userSecretsId">The user secrets ID.</param> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, string userSecretsId) => configuration.AddUserSecrets(userSecretsId, reloadOnChange: false); /// <summary> /// <para> /// Adds the user secrets configuration source with specified user secrets ID. /// </para> /// <para> /// A user secrets ID is unique value used to store and identify a collection of secret configuration values. /// </para> /// </summary> /// <param name="configuration">The configuration builder.</param> /// <param name="userSecretsId">The user secrets ID.</param> /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> /// <returns>The configuration builder.</returns> public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, string userSecretsId, bool reloadOnChange) => AddUserSecretsInternal(configuration, userSecretsId, true, reloadOnChange); private static IConfigurationBuilder AddUserSecretsInternal(IConfigurationBuilder configuration!!, string userSecretsId!!, bool optional, bool reloadOnChange) { return AddSecretsFile(configuration, PathHelper.GetSecretsPathFromSecretsId(userSecretsId), optional, reloadOnChange); } private static IConfigurationBuilder AddSecretsFile(IConfigurationBuilder configuration, string secretPath, bool optional, bool reloadOnChange) { string? directoryPath = Path.GetDirectoryName(secretPath); PhysicalFileProvider? fileProvider = Directory.Exists(directoryPath) ? new PhysicalFileProvider(directoryPath) : null; return configuration.AddJsonFile(fileProvider, PathHelper.SecretsFileName, optional, reloadOnChange); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/Methodical/Boxing/functional/sin.cs
// 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 SinCalc { internal class SinCalc { protected struct CalcCtx { private double _powX,_sumOfTerms; private object _term; public double fact; public double get_powX() { return _powX; } public void set_powX(double val) { _powX = val; } public double sumOfTerms { get { return _sumOfTerms; } set { _sumOfTerms = value; } } public double term { get { return (double)_term; } set { _term = value; } } } protected static object PI = 3.1415926535897932384626433832795d; protected static object mySin(object Angle) { CalcCtx ctx = new CalcCtx(); object ct = ctx; ctx.fact = 1.0; ctx.set_powX(ctx.term = (double)Angle); ctx.sumOfTerms = 0.0; for (object i = 1; (int)i <= 200; i = (int)i + 2) { ctx.sumOfTerms = ctx.sumOfTerms + ctx.term; ctx.set_powX(ctx.get_powX() * (-(double)Angle * (double)Angle)); ctx.fact = ctx.fact * ((int)i + 1) * ((int)i + 2); ctx.term = ctx.get_powX() / ctx.fact; } return ctx.sumOfTerms; } private static int Main() { object i; object Angle; object Result1, Result2; object[] testresults = new object[10]; testresults[0] = 0.000000000d; testresults[1] = 0.309016994d; testresults[2] = 0.587785252d; testresults[3] = 0.809016994d; testresults[4] = 0.951056516d; testresults[5] = 1.000000000d; testresults[6] = 0.951056516d; testresults[7] = 0.809016994d; testresults[8] = 0.587785252d; testresults[9] = 0.309016994d; object mistake = 1e-9d; for (i = 0; (int)i < 10; i = (int)i + 1) { Angle = ((double)PI) * ((int)i / 10.0); Console.Write("Classlib Sin("); Console.Write(Angle); Console.Write(")="); Console.WriteLine(Result1 = Math.Sin((double)Angle)); Console.Write("This Version("); Console.Write(Angle); Console.Write(")="); Console.WriteLine(Result2 = (double)mySin(Angle)); Console.Write("Error is:"); Console.WriteLine((double)Result1 - (double)Result2); Console.WriteLine(); if (Math.Abs((double)Result1 - (double)Result2) > (double)mistake) { Console.WriteLine("ERROR, Versions too far apart!"); return 1; } if (Math.Abs((double)testresults[(int)i] - (double)Result1) > (double)mistake) { Console.WriteLine("ERROR, Classlib version isnt right!"); return 1; } if (Math.Abs((double)testresults[(int)i] - (double)Result2) > (double)mistake) { Console.WriteLine("ERROR, our version isnt right!"); return 1; } } Console.WriteLine("Yippie, all correct"); return 100; } } }
// 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 SinCalc { internal class SinCalc { protected struct CalcCtx { private double _powX,_sumOfTerms; private object _term; public double fact; public double get_powX() { return _powX; } public void set_powX(double val) { _powX = val; } public double sumOfTerms { get { return _sumOfTerms; } set { _sumOfTerms = value; } } public double term { get { return (double)_term; } set { _term = value; } } } protected static object PI = 3.1415926535897932384626433832795d; protected static object mySin(object Angle) { CalcCtx ctx = new CalcCtx(); object ct = ctx; ctx.fact = 1.0; ctx.set_powX(ctx.term = (double)Angle); ctx.sumOfTerms = 0.0; for (object i = 1; (int)i <= 200; i = (int)i + 2) { ctx.sumOfTerms = ctx.sumOfTerms + ctx.term; ctx.set_powX(ctx.get_powX() * (-(double)Angle * (double)Angle)); ctx.fact = ctx.fact * ((int)i + 1) * ((int)i + 2); ctx.term = ctx.get_powX() / ctx.fact; } return ctx.sumOfTerms; } private static int Main() { object i; object Angle; object Result1, Result2; object[] testresults = new object[10]; testresults[0] = 0.000000000d; testresults[1] = 0.309016994d; testresults[2] = 0.587785252d; testresults[3] = 0.809016994d; testresults[4] = 0.951056516d; testresults[5] = 1.000000000d; testresults[6] = 0.951056516d; testresults[7] = 0.809016994d; testresults[8] = 0.587785252d; testresults[9] = 0.309016994d; object mistake = 1e-9d; for (i = 0; (int)i < 10; i = (int)i + 1) { Angle = ((double)PI) * ((int)i / 10.0); Console.Write("Classlib Sin("); Console.Write(Angle); Console.Write(")="); Console.WriteLine(Result1 = Math.Sin((double)Angle)); Console.Write("This Version("); Console.Write(Angle); Console.Write(")="); Console.WriteLine(Result2 = (double)mySin(Angle)); Console.Write("Error is:"); Console.WriteLine((double)Result1 - (double)Result2); Console.WriteLine(); if (Math.Abs((double)Result1 - (double)Result2) > (double)mistake) { Console.WriteLine("ERROR, Versions too far apart!"); return 1; } if (Math.Abs((double)testresults[(int)i] - (double)Result1) > (double)mistake) { Console.WriteLine("ERROR, Classlib version isnt right!"); return 1; } if (Math.Abs((double)testresults[(int)i] - (double)Result2) > (double)mistake) { Console.WriteLine("ERROR, our version isnt right!"); return 1; } } Console.WriteLine("Yippie, all correct"); return 100; } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/SampleIObjectRef.cs
// 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.Serialization; namespace SerializationTestTypes { [DataContract(IsReference = false)] [KnownType(typeof(PublicDC))] public class DCExplicitInterfaceIObjRef : IObjectReference { [DataMember] public SelfRef1 data; [NonSerialized] public static SelfRef1 containedData = new SelfRef1(); public DCExplicitInterfaceIObjRef() { } public DCExplicitInterfaceIObjRef(bool init) { data = new SelfRef1(true); } object IObjectReference.GetRealObject(StreamingContext context) { return containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(containedData, obj); } public override int GetHashCode() { return containedData.GetHashCode(); } } [DataContract(IsReference = false)] [KnownType(typeof(PublicDC))] public class DCIObjRef : IObjectReference { [DataMember] public SimpleDCWithRef data; [NonSerialized] private static SimpleDCWithRef s_containedData = new SimpleDCWithRef(true); public DCIObjRef() { } public DCIObjRef(bool init) { } public object GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return s_containedData.GetHashCode(); } } [Serializable] [KnownType(typeof(PrivateDC))] public class SerExplicitInterfaceIObjRefReturnsPrivate : IObjectReference { [NonSerialized] private static PrivateDC s_containedData = new PrivateDC(); object IObjectReference.GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return base.GetHashCode(); } } [Serializable] [KnownType(typeof(PrivateDC))] public class SerIObjRefReturnsPrivate : IObjectReference { [NonSerialized] private static PrivateDC s_containedData = new PrivateDC(); object IObjectReference.GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return base.GetHashCode(); } } [DataContract(IsReference = false)] [KnownType(typeof(PrivateDC))] public class DCExplicitInterfaceIObjRefReturnsPrivate : IObjectReference { [DataMember] private PrivateDC _data = new PrivateDC(); [NonSerialized] private static PrivateDC s_containedData = new PrivateDC(); object IObjectReference.GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return s_containedData.GetHashCode(); } } [DataContract(IsReference = false)] [KnownType(typeof(PrivateDC))] public class DCIObjRefReturnsPrivate : IObjectReference { [DataMember] private PrivateDC _data = new PrivateDC(); [NonSerialized] private static PrivateDC s_containedData = new PrivateDC(); public object GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return s_containedData.GetHashCode(); } } }
// 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.Serialization; namespace SerializationTestTypes { [DataContract(IsReference = false)] [KnownType(typeof(PublicDC))] public class DCExplicitInterfaceIObjRef : IObjectReference { [DataMember] public SelfRef1 data; [NonSerialized] public static SelfRef1 containedData = new SelfRef1(); public DCExplicitInterfaceIObjRef() { } public DCExplicitInterfaceIObjRef(bool init) { data = new SelfRef1(true); } object IObjectReference.GetRealObject(StreamingContext context) { return containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(containedData, obj); } public override int GetHashCode() { return containedData.GetHashCode(); } } [DataContract(IsReference = false)] [KnownType(typeof(PublicDC))] public class DCIObjRef : IObjectReference { [DataMember] public SimpleDCWithRef data; [NonSerialized] private static SimpleDCWithRef s_containedData = new SimpleDCWithRef(true); public DCIObjRef() { } public DCIObjRef(bool init) { } public object GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return s_containedData.GetHashCode(); } } [Serializable] [KnownType(typeof(PrivateDC))] public class SerExplicitInterfaceIObjRefReturnsPrivate : IObjectReference { [NonSerialized] private static PrivateDC s_containedData = new PrivateDC(); object IObjectReference.GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return base.GetHashCode(); } } [Serializable] [KnownType(typeof(PrivateDC))] public class SerIObjRefReturnsPrivate : IObjectReference { [NonSerialized] private static PrivateDC s_containedData = new PrivateDC(); object IObjectReference.GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return base.GetHashCode(); } } [DataContract(IsReference = false)] [KnownType(typeof(PrivateDC))] public class DCExplicitInterfaceIObjRefReturnsPrivate : IObjectReference { [DataMember] private PrivateDC _data = new PrivateDC(); [NonSerialized] private static PrivateDC s_containedData = new PrivateDC(); object IObjectReference.GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return s_containedData.GetHashCode(); } } [DataContract(IsReference = false)] [KnownType(typeof(PrivateDC))] public class DCIObjRefReturnsPrivate : IObjectReference { [DataMember] private PrivateDC _data = new PrivateDC(); [NonSerialized] private static PrivateDC s_containedData = new PrivateDC(); public object GetRealObject(StreamingContext context) { return s_containedData; } public override bool Equals(object obj) { return DCRUtils.CompareIObjectRefTypes(s_containedData, obj); } public override int GetHashCode() { return s_containedData.GetHashCode(); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.IO.Compression/src/System/IO/Compression/GZipStream.cs
// 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; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO.Compression { public class GZipStream : Stream { private DeflateStream _deflateStream; public GZipStream(Stream stream, CompressionMode mode) : this(stream, mode, leaveOpen: false) { } public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen) { _deflateStream = new DeflateStream(stream, mode, leaveOpen, ZLibNative.GZip_DefaultWindowBits); } // Implies mode = Compress public GZipStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpen: false) { } // Implies mode = Compress public GZipStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) { _deflateStream = new DeflateStream(stream, compressionLevel, leaveOpen, ZLibNative.GZip_DefaultWindowBits); } public override bool CanRead => _deflateStream?.CanRead ?? false; public override bool CanWrite => _deflateStream?.CanWrite ?? false; public override bool CanSeek => _deflateStream?.CanSeek ?? false; public override long Length { get { throw new NotSupportedException(SR.NotSupported); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported); } set { throw new NotSupportedException(SR.NotSupported); } } public override void Flush() { CheckDeflateStream(); _deflateStream.Flush(); return; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported); } public override int ReadByte() { CheckDeflateStream(); return _deflateStream.ReadByte(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override int EndRead(IAsyncResult asyncResult) => _deflateStream.EndRead(asyncResult); public override int Read(byte[] buffer, int offset, int count) { CheckDeflateStream(); return _deflateStream.Read(buffer, offset, count); } public override int Read(Span<byte> buffer) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload // should use the behavior of Read(byte[],int,int) overload. return base.Read(buffer); } else { CheckDeflateStream(); return _deflateStream.ReadCore(buffer); } } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override void EndWrite(IAsyncResult asyncResult) => _deflateStream.EndWrite(asyncResult); public override void Write(byte[] buffer, int offset, int count) { CheckDeflateStream(); _deflateStream.Write(buffer, offset, count); } public override void WriteByte(byte value) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this WriteByte override being introduced. In that case, this WriteByte override // should use the behavior of the Write(byte[],int,int) overload. base.WriteByte(value); } else { CheckDeflateStream(); _deflateStream.WriteCore(MemoryMarshal.CreateReadOnlySpan(ref value, 1)); } } public override void Write(ReadOnlySpan<byte> buffer) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload // should use the behavior of Write(byte[],int,int) overload. base.Write(buffer); } else { CheckDeflateStream(); _deflateStream.WriteCore(buffer); } } public override void CopyTo(Stream destination, int bufferSize) { CheckDeflateStream(); _deflateStream.CopyTo(destination, bufferSize); } protected override void Dispose(bool disposing) { try { if (disposing && _deflateStream != null) { _deflateStream.Dispose(); } _deflateStream = null!; } finally { base.Dispose(disposing); } } public override ValueTask DisposeAsync() { if (GetType() != typeof(GZipStream)) { return base.DisposeAsync(); } DeflateStream? ds = _deflateStream; if (ds != null) { _deflateStream = null!; return ds.DisposeAsync(); } return default; } public Stream BaseStream => _deflateStream?.BaseStream!; public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckDeflateStream(); return _deflateStream.ReadAsync(buffer, offset, count, cancellationToken); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden ReadAsync(byte[], int, int) prior // to this ReadAsync(Memory<byte>) overload being introduced. In that case, this ReadAsync(Memory<byte>) overload // should use the behavior of ReadAsync(byte[],int,int) overload. return base.ReadAsync(buffer, cancellationToken); } else { CheckDeflateStream(); return _deflateStream.ReadAsyncMemory(buffer, cancellationToken); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckDeflateStream(); return _deflateStream.WriteAsync(buffer, offset, count, cancellationToken); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden WriteAsync(byte[], int, int) prior // to this WriteAsync(ReadOnlyMemory<byte>) overload being introduced. In that case, this // WriteAsync(ReadOnlyMemory<byte>) overload should use the behavior of Write(byte[],int,int) overload. return base.WriteAsync(buffer, cancellationToken); } else { CheckDeflateStream(); return _deflateStream.WriteAsyncMemory(buffer, cancellationToken); } } public override Task FlushAsync(CancellationToken cancellationToken) { CheckDeflateStream(); return _deflateStream.FlushAsync(cancellationToken); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { CheckDeflateStream(); return _deflateStream.CopyToAsync(destination, bufferSize, cancellationToken); } private void CheckDeflateStream() { if (_deflateStream == null) { ThrowStreamClosedException(); } } private static void ThrowStreamClosedException() { throw new ObjectDisposedException(nameof(GZipStream), SR.ObjectDisposed_StreamClosed); } } }
// 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; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO.Compression { public class GZipStream : Stream { private DeflateStream _deflateStream; public GZipStream(Stream stream, CompressionMode mode) : this(stream, mode, leaveOpen: false) { } public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen) { _deflateStream = new DeflateStream(stream, mode, leaveOpen, ZLibNative.GZip_DefaultWindowBits); } // Implies mode = Compress public GZipStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpen: false) { } // Implies mode = Compress public GZipStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) { _deflateStream = new DeflateStream(stream, compressionLevel, leaveOpen, ZLibNative.GZip_DefaultWindowBits); } public override bool CanRead => _deflateStream?.CanRead ?? false; public override bool CanWrite => _deflateStream?.CanWrite ?? false; public override bool CanSeek => _deflateStream?.CanSeek ?? false; public override long Length { get { throw new NotSupportedException(SR.NotSupported); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported); } set { throw new NotSupportedException(SR.NotSupported); } } public override void Flush() { CheckDeflateStream(); _deflateStream.Flush(); return; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported); } public override int ReadByte() { CheckDeflateStream(); return _deflateStream.ReadByte(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override int EndRead(IAsyncResult asyncResult) => _deflateStream.EndRead(asyncResult); public override int Read(byte[] buffer, int offset, int count) { CheckDeflateStream(); return _deflateStream.Read(buffer, offset, count); } public override int Read(Span<byte> buffer) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload // should use the behavior of Read(byte[],int,int) overload. return base.Read(buffer); } else { CheckDeflateStream(); return _deflateStream.ReadCore(buffer); } } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override void EndWrite(IAsyncResult asyncResult) => _deflateStream.EndWrite(asyncResult); public override void Write(byte[] buffer, int offset, int count) { CheckDeflateStream(); _deflateStream.Write(buffer, offset, count); } public override void WriteByte(byte value) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this WriteByte override being introduced. In that case, this WriteByte override // should use the behavior of the Write(byte[],int,int) overload. base.WriteByte(value); } else { CheckDeflateStream(); _deflateStream.WriteCore(MemoryMarshal.CreateReadOnlySpan(ref value, 1)); } } public override void Write(ReadOnlySpan<byte> buffer) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload // should use the behavior of Write(byte[],int,int) overload. base.Write(buffer); } else { CheckDeflateStream(); _deflateStream.WriteCore(buffer); } } public override void CopyTo(Stream destination, int bufferSize) { CheckDeflateStream(); _deflateStream.CopyTo(destination, bufferSize); } protected override void Dispose(bool disposing) { try { if (disposing && _deflateStream != null) { _deflateStream.Dispose(); } _deflateStream = null!; } finally { base.Dispose(disposing); } } public override ValueTask DisposeAsync() { if (GetType() != typeof(GZipStream)) { return base.DisposeAsync(); } DeflateStream? ds = _deflateStream; if (ds != null) { _deflateStream = null!; return ds.DisposeAsync(); } return default; } public Stream BaseStream => _deflateStream?.BaseStream!; public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckDeflateStream(); return _deflateStream.ReadAsync(buffer, offset, count, cancellationToken); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden ReadAsync(byte[], int, int) prior // to this ReadAsync(Memory<byte>) overload being introduced. In that case, this ReadAsync(Memory<byte>) overload // should use the behavior of ReadAsync(byte[],int,int) overload. return base.ReadAsync(buffer, cancellationToken); } else { CheckDeflateStream(); return _deflateStream.ReadAsyncMemory(buffer, cancellationToken); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckDeflateStream(); return _deflateStream.WriteAsync(buffer, offset, count, cancellationToken); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken)) { if (GetType() != typeof(GZipStream)) { // GZipStream is not sealed, and a derived type may have overridden WriteAsync(byte[], int, int) prior // to this WriteAsync(ReadOnlyMemory<byte>) overload being introduced. In that case, this // WriteAsync(ReadOnlyMemory<byte>) overload should use the behavior of Write(byte[],int,int) overload. return base.WriteAsync(buffer, cancellationToken); } else { CheckDeflateStream(); return _deflateStream.WriteAsyncMemory(buffer, cancellationToken); } } public override Task FlushAsync(CancellationToken cancellationToken) { CheckDeflateStream(); return _deflateStream.FlushAsync(cancellationToken); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { CheckDeflateStream(); return _deflateStream.CopyToAsync(destination, bufferSize, cancellationToken); } private void CheckDeflateStream() { if (_deflateStream == null) { ThrowStreamClosedException(); } } private static void ThrowStreamClosedException() { throw new ObjectDisposedException(nameof(GZipStream), SR.ObjectDisposed_StreamClosed); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.ObjectModel/tests/System/ComponentModel/TypeDescriptionProviderAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.ComponentModel.Tests { public class TypeDescriptionProviderAttributeTests { [Theory] [InlineData("")] [InlineData("typeName")] public void Ctor_String(string typeName) { var attribute = new TypeDescriptionProviderAttribute(typeName); Assert.Equal(typeName, attribute.TypeName); } [Fact] public void Ctor_NullTypeName_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("typeName", () => new TypeDescriptionProviderAttribute((string)null)); } [Theory] [InlineData(typeof(int))] public void Ctor_Type(Type type) { var attribute = new TypeDescriptionProviderAttribute(type); Assert.Equal(type.AssemblyQualifiedName, attribute.TypeName); } [Fact] public void Ctor_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => new TypeDescriptionProviderAttribute((Type)null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; namespace System.ComponentModel.Tests { public class TypeDescriptionProviderAttributeTests { [Theory] [InlineData("")] [InlineData("typeName")] public void Ctor_String(string typeName) { var attribute = new TypeDescriptionProviderAttribute(typeName); Assert.Equal(typeName, attribute.TypeName); } [Fact] public void Ctor_NullTypeName_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("typeName", () => new TypeDescriptionProviderAttribute((string)null)); } [Theory] [InlineData(typeof(int))] public void Ctor_Type(Type type) { var attribute = new TypeDescriptionProviderAttribute(type); Assert.Equal(type.AssemblyQualifiedName, attribute.TypeName); } [Fact] public void Ctor_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => new TypeDescriptionProviderAttribute((Type)null)); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Private.CoreLib/src/System/Runtime/MemoryFailPoint.Unix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime { public sealed partial class MemoryFailPoint { private static ulong GetTopOfMemory() { // These values are optimistic assumptions. In reality the value will // often be lower. return IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue; } private static bool CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree) { // TODO: Implement availPageFile = 0; totalAddressSpaceFree = 0; return false; } #pragma warning disable IDE0060 // Based on the shouldThrow parameter, this will throw an exception, or // returns whether there is enough space. In all cases, we update // our last known free address space, hopefully avoiding needing to // probe again. private static void CheckForFreeAddressSpace(ulong size, bool shouldThrow) { // Unreachable until CheckForAvailableMemory is implemented } // Allocate a specified number of bytes, commit them and free them. This should enlarge // page file if necessary and possible. private static void GrowPageFileIfNecessaryAndPossible(UIntPtr numBytes) { // Unreachable until CheckForAvailableMemory is implemented } #pragma warning restore IDE0060 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime { public sealed partial class MemoryFailPoint { private static ulong GetTopOfMemory() { // These values are optimistic assumptions. In reality the value will // often be lower. return IntPtr.Size == 4 ? uint.MaxValue : ulong.MaxValue; } private static bool CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree) { // TODO: Implement availPageFile = 0; totalAddressSpaceFree = 0; return false; } #pragma warning disable IDE0060 // Based on the shouldThrow parameter, this will throw an exception, or // returns whether there is enough space. In all cases, we update // our last known free address space, hopefully avoiding needing to // probe again. private static void CheckForFreeAddressSpace(ulong size, bool shouldThrow) { // Unreachable until CheckForAvailableMemory is implemented } // Allocate a specified number of bytes, commit them and free them. This should enlarge // page file if necessary and possible. private static void GrowPageFileIfNecessaryAndPossible(UIntPtr numBytes) { // Unreachable until CheckForAvailableMemory is implemented } #pragma warning restore IDE0060 } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ForeignKeyAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; namespace System.ComponentModel.DataAnnotations.Schema { /// <summary> /// Denotes a property used as a foreign key in a relationship. /// The annotation may be placed on the foreign key property and specify the associated navigation property name, /// or placed on a navigation property and specify the associated foreign key name. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class ForeignKeyAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="ForeignKeyAttribute" /> class. /// </summary> /// <param name="name"> /// If placed on a foreign key property, the name of the associated navigation property. /// If placed on a navigation property, the name of the associated foreign key(s). /// If a navigation property has multiple foreign keys, a comma separated list should be supplied. /// </param> public ForeignKeyAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(SR.Format(SR.ArgumentIsNullOrWhitespace, nameof(name)), nameof(name)); } Name = name; } /// <summary> /// If placed on a foreign key property, the name of the associated navigation property. /// If placed on a navigation property, the name of the associated foreign key(s). /// </summary> public string Name { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; namespace System.ComponentModel.DataAnnotations.Schema { /// <summary> /// Denotes a property used as a foreign key in a relationship. /// The annotation may be placed on the foreign key property and specify the associated navigation property name, /// or placed on a navigation property and specify the associated foreign key name. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class ForeignKeyAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="ForeignKeyAttribute" /> class. /// </summary> /// <param name="name"> /// If placed on a foreign key property, the name of the associated navigation property. /// If placed on a navigation property, the name of the associated foreign key(s). /// If a navigation property has multiple foreign keys, a comma separated list should be supplied. /// </param> public ForeignKeyAttribute(string name) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(SR.Format(SR.ArgumentIsNullOrWhitespace, nameof(name)), nameof(name)); } Name = name; } /// <summary> /// If placed on a foreign key property, the name of the associated navigation property. /// If placed on a navigation property, the name of the associated foreign key(s). /// </summary> public string Name { get; } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/Methodical/eh/basics/throwoutside_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwoutside.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="throwoutside.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\..\common\eh_common.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs
// 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.Dynamic; using System.Linq.Expressions; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Semantics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder { internal readonly struct RuntimeBinder { private static readonly object s_bindLock = new object(); private readonly ExpressionBinder _binder; internal bool IsChecked => _binder.Context.Checked; [RequiresUnreferencedCode(Binder.TrimmerWarning)] public RuntimeBinder(Type contextType, bool isChecked = false) { AggregateSymbol context; if (contextType != null) { lock (s_bindLock) { context = ((AggregateType)SymbolTable.GetCTypeFromType(contextType)).OwningAggregate; } } else { context = null; } _binder = new ExpressionBinder(new BindingContext(context, isChecked)); } [RequiresUnreferencedCode(Binder.TrimmerWarning)] public Expression Bind(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding) { // The lock is here to protect this instance of the binder from itself // when called on multiple threads. The cost in time of a single lock // on a single thread appears to be negligible and dominated by the cost // of the bind itself. My timing of 4000 consecutive dynamic calls with // bind, where the body of the called method is empty, are as follows // (five samples): // // Without lock() With lock() // = 00:00:10.7597696 = 00:00:10.7222606 // = 00:00:10.0711116 = 00:00:10.1818496 // = 00:00:09.9905507 = 00:00:10.1628693 // = 00:00:09.9892183 = 00:00:10.0750007 // = 00:00:09.9253234 = 00:00:10.0340266 // // ...subsequent calls that were cache hits, i.e., already bound, took less // than 1/1000 sec for the whole 4000 of them. lock (s_bindLock) { return BindCore(payload, parameters, args, out deferredBinding); } } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expression BindCore( ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding) { Debug.Assert(args.Length >= 1); ArgumentObject[] arguments = CreateArgumentArray(payload, parameters, args); // On any given bind call, we populate the symbol table with any new // conversions that we find for any of the types specified. We keep a // running SymbolTable so that we don't have to reflect over types if // we've seen them already in the table. // // Once we've loaded all the standard conversions into the symbol table, // we can call into the binder to bind the actual call. payload.PopulateSymbolTableWithName(arguments[0].Type, arguments); AddConversionsForArguments(arguments); // When we do any bind, we perform the following steps: // // 1) Create a local variable scope which contains local variable symbols // for each of the parameters, and the instance argument. // 2) If we have operators, then we don't need to do lookup. Otherwise, // look for the name and switch on the result - dispatch according to // the symbol kind. This results in an Expr being bound that is the expression. // 3) Create the EXPRRETURN which returns the call and wrap it in // an EXPRBOUNDLAMBDA which uses the local variable scope // created in step (1) as its local scope. // 4) Call the ExpressionTreeRewriter to generate a set of EXPRCALLs // that call the static ExpressionTree factory methods. // 5) Call the EXPRTreeToExpressionTreeVisitor to generate the actual // Linq expression tree for the whole thing and return it. // (1) - Create the locals Scope pScope = SymFactory.CreateScope(); LocalVariableSymbol[] locals = PopulateLocalScope(payload, pScope, arguments, parameters); // (1.5) - Check to see if we need to defer. if (DeferBinding(payload, arguments, args, locals, out deferredBinding)) { return null; } // (2) - look the thing up and dispatch. Expr pResult = payload.DispatchPayload(this, arguments, locals); Debug.Assert(pResult != null); return CreateExpressionTreeFromResult(parameters, pScope, pResult); } #region Helpers [ConditionalAttribute("DEBUG")] internal static void EnsureLockIsTaken() { // Make sure that the binder lock is taken Debug.Assert(System.Threading.Monitor.IsEntered(s_bindLock)); } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private bool DeferBinding( ICSharpBinder payload, ArgumentObject[] arguments, DynamicMetaObject[] args, LocalVariableSymbol[] locals, out DynamicMetaObject deferredBinding) { // This method deals with any deferrals we need to do. We check deferrals up front // and bail early if we need to do them. // (1) InvokeMember deferral. // // This is the deferral for the d.Foo() scenario where Foo actually binds to a // field or property, and not a method group that is invocable. We defer to // the standard GetMember/Invoke pattern. CSharpInvokeMemberBinder callPayload = payload as CSharpInvokeMemberBinder; if (callPayload != null) { int arity = callPayload.TypeArguments?.Length ?? 0; MemberLookup mem = new MemberLookup(); Expr callingObject = CreateCallingObjectForCall(callPayload, arguments, locals); SymWithType swt = SymbolTable.LookupMember( callPayload.Name, callingObject, _binder.Context.ContextForMemberLookup, arity, mem, (callPayload.Flags & CSharpCallFlags.EventHookup) != 0, true); if (swt != null && swt.Sym.getKind() != SYMKIND.SK_MethodSymbol) { // The GetMember only has one argument, and we need to just take the first arg info. CSharpGetMemberBinder getMember = new CSharpGetMemberBinder(callPayload.Name, false, callPayload.CallingContext, new CSharpArgumentInfo[] { callPayload.GetArgumentInfo(0) }).TryGetExisting(); // The Invoke has the remaining argument infos. However, we need to redo the first one // to correspond to the GetMember result. CSharpArgumentInfo[] argInfos = callPayload.ArgumentInfoArray(); argInfos[0] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null); CSharpInvokeBinder invoke = new CSharpInvokeBinder(callPayload.Flags, callPayload.CallingContext, argInfos).TryGetExisting(); DynamicMetaObject[] newArgs = new DynamicMetaObject[args.Length - 1]; Array.Copy(args, 1, newArgs, 0, args.Length - 1); deferredBinding = invoke.Defer(getMember.Defer(args[0]), newArgs); return true; } } deferredBinding = null; return false; } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static Expression CreateExpressionTreeFromResult(Expression[] parameters, Scope pScope, Expr pResult) { // (3) - Place the result in a return statement and create the ExprBoundLambda. ExprBoundLambda boundLambda = GenerateBoundLambda(pScope, pResult); // (4) - Rewrite the ExprBoundLambda into an expression tree. ExprBinOp exprTree = ExpressionTreeRewriter.Rewrite(boundLambda); // (5) - Create the actual Expression Tree Expression e = ExpressionTreeCallRewriter.Rewrite(exprTree, parameters); return e; } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Type GetArgumentType(ICSharpBinder p, CSharpArgumentInfo argInfo, Expression param, DynamicMetaObject arg, int index) { Type t = argInfo.UseCompileTimeType ? param.Type : arg.LimitType; Debug.Assert(t != null); if (argInfo.IsByRefOrOut) { // If we have a ref our an out parameter, make the byref type. // If we have the receiver of a call or invoke that is ref, it must be because of // a struct caller. Don't persist the ref for that. if (!(index == 0 && p.IsBinderThatCanHaveRefReceiver)) { t = t.MakeByRefType(); } } else if (!argInfo.UseCompileTimeType) { // If we don't have ref or out, then pick the best type to represent this value. // If the runtime value has a type that is not accessible, then we pick an // accessible type that is "closest" in some sense, where we recursively widen // components of type that can validly vary covariantly. // This ensures that the type we pick is something that the user could have written. // Since the actual type of these arguments are never going to be pointer // types or ref/out types (they are in fact boxed into an object), we have // a guarantee that we will always be able to find a best accessible type // (which, in the worst case, may be object). CType actualType = SymbolTable.GetCTypeFromType(t); CType bestType = TypeManager.GetBestAccessibleType(_binder.Context.ContextForMemberLookup, actualType); t = bestType.AssociatedSystemType; } return t; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private ArgumentObject[] CreateArgumentArray( ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args) { // Check the payloads to see whether or not we need to get the runtime types for // these arguments. ArgumentObject[] array = new ArgumentObject[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { CSharpArgumentInfo info = payload.GetArgumentInfo(i); array[i] = new ArgumentObject(args[i].Value, info, GetArgumentType(payload, info, parameters[i], args[i], i)); Debug.Assert(array[i].Type != null); } return array; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal static void PopulateSymbolTableWithPayloadInformation( ICSharpInvokeOrInvokeMemberBinder callOrInvoke, Type callingType, ArgumentObject[] arguments) { Type type; if (callOrInvoke.StaticCall) { type = arguments[0].Value as Type; if (type == null) { throw Error.BindStaticRequiresType(arguments[0].Info.Name); } } else { type = callingType; } SymbolTable.PopulateSymbolTableWithName( callOrInvoke.Name, callOrInvoke.TypeArguments, type); // If it looks like we're invoking a get_ or a set_, load the property as well. // This is because we need COM indexed properties called via method calls to // work the same as it used to. if (callOrInvoke.Name.StartsWith("set_", StringComparison.Ordinal) || callOrInvoke.Name.StartsWith("get_", StringComparison.Ordinal)) { SymbolTable.PopulateSymbolTableWithName( callOrInvoke.Name.Substring(4), //remove prefix callOrInvoke.TypeArguments, type); } } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static void AddConversionsForArguments(ArgumentObject[] arguments) { foreach (ArgumentObject arg in arguments) { SymbolTable.AddConversionsForType(arg.Type); } } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal ExprWithArgs DispatchPayload(ICSharpInvokeOrInvokeMemberBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) => BindCall(payload, CreateCallingObjectForCall(payload, arguments, locals), arguments, locals); ///////////////////////////////////////////////////////////////////////////////// // We take the ArgumentObjects to verify - if the parameter expression tells us // we have a ref parameter, but the argument object tells us we're not passed by ref, // then it means it was a ref that the compiler had to insert. This is used when // we have a call off of a struct for example. If thats the case, don't treat the // local as a ref type. [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static LocalVariableSymbol[] PopulateLocalScope( ICSharpBinder payload, Scope pScope, ArgumentObject[] arguments, Expression[] parameterExpressions) { // We use the compile time types for the local variables, and then // cast them to the runtime types for the expression tree. LocalVariableSymbol[] locals = new LocalVariableSymbol[parameterExpressions.Length]; for (int i = 0; i < parameterExpressions.Length; i++) { Expression parameter = parameterExpressions[i]; CType type = SymbolTable.GetCTypeFromType(parameter.Type); // Make sure we're not setting ref for the receiver of a call - the argument // will be marked as ref if we're calling off a struct, but we don't want // to persist that in our system. // If we're the first param of a call or invoke, and we're ref, it must be // because of structs. Don't persist the parameter modifier type. if (i != 0 || !payload.IsBinderThatCanHaveRefReceiver) { // If we have a ref or out, get the parameter modifier type. ParameterExpression paramExp = parameter as ParameterExpression; if (paramExp != null && paramExp.IsByRef) { CSharpArgumentInfo info = arguments[i].Info; if (info.IsByRefOrOut) { type = TypeManager.GetParameterModifier(type, info.IsOut); } } } LocalVariableSymbol local = SymFactory.CreateLocalVar(NameManager.Add("p" + i), pScope, type); locals[i] = local; } return locals; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static ExprBoundLambda GenerateBoundLambda(Scope pScope, Expr call) { // We don't actually need the real delegate type here - we just need SOME delegate type. // This is because we never attempt any conversions on the lambda itself. AggregateType delegateType = SymbolLoader.GetPredefindType(PredefinedType.PT_FUNC); return ExprFactory.CreateAnonymousMethod(delegateType, pScope, call); } #region ExprCreation ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateLocal(Type type, bool isOut, LocalVariableSymbol local) { CType ctype; if (isOut) { // We need to record the out state, but GetCTypeFromType will only determine that // it should be some sort of ParameterType but not be able to deduce that it needs // IsOut to be true. So do that logic here rather than create a ref type to then // throw away. Debug.Assert(type.IsByRef); ctype = TypeManager.GetParameterModifier(SymbolTable.GetCTypeFromType(type.GetElementType()), true); } else { ctype = SymbolTable.GetCTypeFromType(type); } // If we can convert, do that. If not, cast it. ExprLocal exprLocal = ExprFactory.CreateLocal(local); Expr result = _binder.tryConvert(exprLocal, ctype) ?? _binder.mustCast(exprLocal, ctype); result.Flags |= EXPRFLAG.EXF_LVALUE; return result; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr CreateArgumentListEXPR( ArgumentObject[] arguments, LocalVariableSymbol[] locals, int startIndex, int endIndex) { Expr args = null; Expr last = null; if (arguments != null) { for (int i = startIndex; i < endIndex; i++) { ArgumentObject argument = arguments[i]; Expr arg = CreateArgumentEXPR(argument, locals[i]); if (args == null) { args = arg; last = args; } else { // Lists are right-heavy. ExprFactory.AppendItemToList(arg, ref args, ref last); } } } return args; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateArgumentEXPR(ArgumentObject argument, LocalVariableSymbol local) { Expr arg; if (argument.Info.LiteralConstant) { if (argument.Value == null) { if (argument.Info.UseCompileTimeType) { arg = ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), default(ConstVal)); } else { arg = ExprFactory.CreateNull(); } } else { arg = ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), ConstVal.Get(argument.Value)); } } else { // If we have a dynamic argument and it was null, the type is going to be Object. // But we want it to be typed NullType so we can have null conversions. if (!argument.Info.UseCompileTimeType && argument.Value == null) { arg = ExprFactory.CreateNull(); } else { arg = CreateLocal(argument.Type, argument.Info.IsOut, local); } } // Now check if we have a named thing. If so, wrap this thing in a named argument. if (argument.Info.NamedArgument) { Debug.Assert(argument.Info.Name != null); arg = ExprFactory.CreateNamedArgumentSpecification(NameManager.Add(argument.Info.Name), arg); } // If we have an object that was "dynamic" at compile time, we need // to be able to convert it to every interface that the actual value // implements. This allows conversion binders and overload resolution // to behave as though type information is available for these Exprs, // even though it may be the case that the actual runtime type is // inaccessible and therefore unused. // This comes in handy for, e.g., iterators (they are nested private // classes), and COM RCWs without type information (they do not expose // their interfaces in a usual way). // It is critical that arg.RuntimeObject is non-null only when the // compile time type of the argument is dynamic, otherwise normal C# // semantics on typed arguments will be broken. if (!argument.Info.UseCompileTimeType && argument.Value != null) { arg.RuntimeObject = argument.Value; arg.RuntimeObjectActualType = SymbolTable.GetCTypeFromType(argument.Value.GetType()); } return arg; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static ExprMemberGroup CreateMemberGroupExpr( string Name, Type[] typeArguments, Expr callingObject, SYMKIND kind) { Name name = NameManager.Add(Name); AggregateType callingType; CType callingObjectType = callingObject.Type; if (callingObjectType is ArrayType) { callingType = SymbolLoader.GetPredefindType(PredefinedType.PT_ARRAY); } else if (callingObjectType is NullableType callingNub) { callingType = callingNub.GetAts(); } else { callingType = (AggregateType)callingObjectType; } // The C# binder expects that only the base virtual method is inserted // into the list of candidates, and only the type containing the base // virtual method is inserted into the list of types. However, since we // don't want to do all the logic, we're just going to insert every type // that has a member of the given name, and allow the C# binder to filter // out all overrides. // CONSIDER: using a hashset to filter out duplicate interface types. // Adopt a smarter algorithm to filter types before creating the exception. HashSet<CType> distinctCallingTypes = new HashSet<CType>(); List<CType> callingTypes = new List<CType>(); // Find that set of types now. symbmask_t mask = symbmask_t.MASK_MethodSymbol; switch (kind) { case SYMKIND.SK_PropertySymbol: case SYMKIND.SK_IndexerSymbol: mask = symbmask_t.MASK_PropertySymbol; break; case SYMKIND.SK_MethodSymbol: mask = symbmask_t.MASK_MethodSymbol; break; default: Debug.Fail("Unhandled kind"); break; } // If we have a constructor, only find its type. bool bIsConstructor = name == NameManager.GetPredefinedName(PredefinedName.PN_CTOR); foreach (AggregateType t in callingType.TypeHierarchy) { if (SymbolTable.AggregateContainsMethod(t.OwningAggregate, Name, mask) && distinctCallingTypes.Add(t)) { callingTypes.Add(t); } // If we have a constructor, run the loop once for the constructor's type, and thats it. if (bIsConstructor) { break; } } EXPRFLAG flags = EXPRFLAG.EXF_USERCALLABLE; // If its a delegate, mark that on the memgroup. if (Name == SpecialNames.Invoke && callingObject.Type.IsDelegateType) { flags |= EXPRFLAG.EXF_DELEGATE; } // For a constructor, we need to seed the memgroup with the constructor flag. if (Name == SpecialNames.Constructor) { flags |= EXPRFLAG.EXF_CTOR; } // If we have an indexer, mark that. if (Name == SpecialNames.Indexer) { flags |= EXPRFLAG.EXF_INDEXER; } TypeArray typeArgumentsAsTypeArray = typeArguments?.Length > 0 ? TypeArray.Allocate(SymbolTable.GetCTypeArrayFromTypes(typeArguments)) : TypeArray.Empty; ExprMemberGroup memgroup = ExprFactory.CreateMemGroup( // Tree flags, name, typeArgumentsAsTypeArray, kind, callingType, null, new CMemberLookupResults(TypeArray.Allocate(callingTypes.ToArray()), name)); if (!(callingObject is ExprClass)) { memgroup.OptionalObject = callingObject; } return memgroup; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateProperty( SymWithType swt, Expr callingObject, BindingFlag flags) { // For a property, we simply create the EXPRPROP for the thing, call the // expression tree rewriter, rewrite it, and send it on its way. PropertySymbol property = swt.Prop(); AggregateType propertyType = swt.GetType(); PropWithType pwt = new PropWithType(property, propertyType); ExprMemberGroup pMemGroup = CreateMemberGroupExpr(property.name.Text, null, callingObject, SYMKIND.SK_PropertySymbol); return _binder.BindToProperty(// For a static property instance, don't set the object. callingObject is ExprClass ? null : callingObject, pwt, flags, null, pMemGroup); } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private ExprWithArgs CreateIndexer(SymWithType swt, Expr callingObject, Expr arguments, BindingFlag bindFlags) { IndexerSymbol index = swt.Sym as IndexerSymbol; ExprMemberGroup memgroup = CreateMemberGroupExpr(index.name.Text, null, callingObject, SYMKIND.SK_PropertySymbol); ExprWithArgs result = _binder.BindMethodGroupToArguments(bindFlags, memgroup, arguments); ReorderArgumentsForNamedAndOptional(callingObject, result); return result; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateArray(Expr callingObject, Expr optionalIndexerArguments) { return _binder.BindArrayIndexCore(callingObject, optionalIndexerArguments); } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateField( SymWithType swt, Expr callingObject) { // For a field, simply create the EXPRFIELD and our caller takes care of the rest. FieldSymbol fieldSymbol = swt.Field(); AggregateType fieldType = swt.GetType(); FieldWithType fwt = new FieldWithType(fieldSymbol, fieldType); Expr field = _binder.BindToField(callingObject is ExprClass ? null : callingObject, fwt, 0); return field; } ///////////////////////////////////////////////////////////////////////////////// #endregion #endregion #region Calls ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateCallingObjectForCall( ICSharpInvokeOrInvokeMemberBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { // Here we have a regular call, so create the calling object off of the first // parameter and pass it through. Expr callingObject; if (payload.StaticCall) { Type t = arguments[0].Value as Type; Debug.Assert(t != null); // Would have thrown in PopulateSymbolTableWithPayloadInformation already callingObject = ExprFactory.CreateClass(SymbolTable.GetCTypeFromType(t)); } else { // If we have a null argument, just bail and throw. if (!arguments[0].Info.UseCompileTimeType && arguments[0].Value == null) { throw Error.NullReferenceOnMemberException(); } callingObject = _binder.mustConvert( CreateArgumentEXPR(arguments[0], locals[0]), SymbolTable.GetCTypeFromType(arguments[0].Type)); if (arguments[0].Type.IsValueType && callingObject is ExprCast) { // If we have a struct type, unbox it. callingObject.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } } return callingObject; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private ExprWithArgs BindCall( ICSharpInvokeOrInvokeMemberBinder payload, Expr callingObject, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { if (payload is InvokeBinder && !callingObject.Type.IsDelegateType) { throw Error.BindInvokeFailedNonDelegate(); } int arity = payload.TypeArguments?.Length ?? 0; MemberLookup mem = new MemberLookup(); SymWithType swt = SymbolTable.LookupMember( payload.Name, callingObject, _binder.Context.ContextForMemberLookup, arity, mem, (payload.Flags & CSharpCallFlags.EventHookup) != 0, true); if (swt == null) { throw mem.ReportErrors(); } if (swt.Sym.getKind() != SYMKIND.SK_MethodSymbol) { Debug.Fail("Unexpected type returned from lookup"); throw Error.InternalCompilerError(); } // At this point, we're set up to do binding. We need to do the following: // // 1) Create the EXPRLOCALs for the arguments, linking them to the local // variable symbols defined above. // 2) Create the EXPRMEMGRP for the call and the EXPRLOCAL for the object // of the call, and link the correct local variable symbol as above. // 3) Do overload resolution to get back an EXPRCALL. // // Our caller takes care of the rest. // First we need to check the sym that we got back. If we got back a static // method, then we may be in the situation where the user called the method // via a simple name call through the phantom overload. If thats the case, // then we want to sub in a type instead of the object. ExprMemberGroup memGroup = CreateMemberGroupExpr(payload.Name, payload.TypeArguments, callingObject, swt.Sym.getKind()); if ((payload.Flags & CSharpCallFlags.SimpleNameCall) != 0) { callingObject.Flags |= EXPRFLAG.EXF_SIMPLENAME; } if ((payload.Flags & CSharpCallFlags.EventHookup) != 0) { mem = new MemberLookup(); SymWithType swtEvent = SymbolTable.LookupMember( payload.Name.Split('_')[1], callingObject, _binder.Context.ContextForMemberLookup, arity, mem, (payload.Flags & CSharpCallFlags.EventHookup) != 0, true); if (swtEvent == null) { throw mem.ReportErrors(); } CType eventCType = null; if (swtEvent.Sym.getKind() == SYMKIND.SK_FieldSymbol) { eventCType = swtEvent.Field().GetType(); } else if (swtEvent.Sym.getKind() == SYMKIND.SK_EventSymbol) { eventCType = swtEvent.Event().type; } Type eventType = TypeManager.SubstType(eventCType, swtEvent.Ats).AssociatedSystemType; if (eventType != null) { // If we have an event hookup, first find the event itself. BindImplicitConversion(new ArgumentObject[] { arguments[1] }, eventType, locals, false); } memGroup.Flags &= ~EXPRFLAG.EXF_USERCALLABLE; } // Check if we have a potential call to an indexed property accessor. // If so, we'll flag overload resolution to let us call non-callables. if ((payload.Name.StartsWith("set_", StringComparison.Ordinal) && ((MethodSymbol)swt.Sym).Params.Count > 1) || (payload.Name.StartsWith("get_", StringComparison.Ordinal) && ((MethodSymbol)swt.Sym).Params.Count > 0)) { memGroup.Flags &= ~EXPRFLAG.EXF_USERCALLABLE; } ExprCall result = _binder.BindMethodGroupToArguments(// Tree BindingFlag.BIND_RVALUEREQUIRED | BindingFlag.BIND_STMTEXPRONLY, memGroup, CreateArgumentListEXPR(arguments, locals, 1, arguments.Length)) as ExprCall; Debug.Assert(result != null); CheckForConditionalMethodError(result); ReorderArgumentsForNamedAndOptional(callingObject, result); return result; } private static void CheckForConditionalMethodError(ExprCall call) { MethodSymbol method = call.MethWithInst.Meth(); object[] conditions = method.AssociatedMemberInfo.GetCustomAttributes(typeof(ConditionalAttribute), true); if (conditions.Length > 0) { throw Error.BindCallToConditionalMethod(method.name); } } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private void ReorderArgumentsForNamedAndOptional(Expr callingObject, ExprWithArgs result) { Expr arguments = result.OptionalArguments; AggregateType type; MethodOrPropertySymbol methprop; ExprMemberGroup memgroup; TypeArray typeArgs; if (result is ExprCall call) { type = call.MethWithInst.Ats; methprop = call.MethWithInst.Meth(); memgroup = call.MemberGroup; typeArgs = call.MethWithInst.TypeArgs; } else { ExprProperty prop = result as ExprProperty; Debug.Assert(prop != null); type = prop.PropWithTypeSlot.Ats; methprop = prop.PropWithTypeSlot.Prop(); memgroup = prop.MemberGroup; typeArgs = null; } ArgInfos argInfo = new ArgInfos { carg = ExpressionBinder.CountArguments(arguments) }; ExpressionBinder.FillInArgInfoFromArgList(argInfo, arguments); // We need to substitute type parameters BEFORE getting the most derived one because // we're binding against the base method, and the derived method may change the // generic arguments. TypeArray parameters = TypeManager.SubstTypeArray(methprop.Params, type, typeArgs); methprop = ExpressionBinder.GroupToArgsBinder.FindMostDerivedMethod(methprop, callingObject.Type); ExpressionBinder.GroupToArgsBinder.ReOrderArgsForNamedArguments( methprop, parameters, type, memgroup, argInfo); Expr pList = null; // We reordered, so make a new list of them and set them on the constructor. // Go backwards cause lists are right-flushed. // Also perform the conversions to the right types. for (int i = argInfo.carg - 1; i >= 0; i--) { Expr pArg = argInfo.prgexpr[i]; // Strip the name-ness away, since we don't need it. pArg = StripNamedArgument(pArg); // Perform the correct conversion. pArg = _binder.tryConvert(pArg, parameters[i]); pList = pList == null ? pArg : ExprFactory.CreateList(pArg, pList); } result.OptionalArguments = pList; } private Expr StripNamedArgument(Expr pArg) { if (pArg is ExprNamedArgumentSpecification named) { pArg = named.Value; } else if (pArg is ExprArrayInit init) { init.OptionalArguments = StripNamedArguments(init.OptionalArguments); } return pArg; } private Expr StripNamedArguments(Expr pArg) { if (pArg is ExprList list) { while (true) { list.OptionalElement = StripNamedArgument(list.OptionalElement); if (list.OptionalNextListNode is ExprList next) { list = next; } else { list.OptionalNextListNode = StripNamedArgument(list.OptionalNextListNode); break; } } } return StripNamedArgument(pArg); } #endregion #region Operators #region UnaryOperators ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindUnaryOperation( CSharpUnaryOperationBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { Debug.Assert(arguments.Length == 1); OperatorKind op = GetOperatorKind(payload.Operation); Expr arg1 = CreateArgumentEXPR(arguments[0], locals[0]); arg1.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation)); if (op == OperatorKind.OP_TRUE || op == OperatorKind.OP_FALSE) { // For true and false, we try to convert to bool first. If that // doesn't work, then we look for user defined operators. Expr result = _binder.tryConvert(arg1, SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL)); if (result != null && op == OperatorKind.OP_FALSE) { // If we can convert to bool, we need to negate the thing if we're looking for false. result = _binder.BindStandardUnaryOperator(OperatorKind.OP_LOGNOT, result); } return result ?? _binder.bindUDUnop(op == OperatorKind.OP_TRUE ? ExpressionKind.True : ExpressionKind.False, arg1) // If the result is STILL null, then that means theres no implicit conversion to bool, // and no user-defined operators for true and false. Just do a must convert to report // the error. ?? _binder.mustConvert(arg1, SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL)); } return _binder.BindStandardUnaryOperator(op, arg1); } #endregion #region BinaryOperators ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindBinaryOperation( CSharpBinaryOperationBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { Debug.Assert(arguments.Length == 2); ExpressionKind ek = Operators.GetExpressionKind(GetOperatorKind(payload.Operation, payload.IsLogicalOperation)); Expr arg1 = CreateArgumentEXPR(arguments[0], locals[0]); Expr arg2 = CreateArgumentEXPR(arguments[1], locals[1]); arg1.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation, payload.IsLogicalOperation)); arg2.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation, payload.IsLogicalOperation)); if (ek > ExpressionKind.MultiOffset) { ek = (ExpressionKind)(ek - ExpressionKind.MultiOffset); } return _binder.BindStandardBinop(ek, arg1, arg2); } #endregion ///////////////////////////////////////////////////////////////////////////////// private static OperatorKind GetOperatorKind(ExpressionType p) { return GetOperatorKind(p, false); } private static OperatorKind GetOperatorKind(ExpressionType p, bool bIsLogical) { switch (p) { default: Debug.Fail("Unknown operator: " + p); throw Error.InternalCompilerError(); // Binary Operators case ExpressionType.Add: return OperatorKind.OP_ADD; case ExpressionType.Subtract: return OperatorKind.OP_SUB; case ExpressionType.Multiply: return OperatorKind.OP_MUL; case ExpressionType.Divide: return OperatorKind.OP_DIV; case ExpressionType.Modulo: return OperatorKind.OP_MOD; case ExpressionType.LeftShift: return OperatorKind.OP_LSHIFT; case ExpressionType.RightShift: return OperatorKind.OP_RSHIFT; case ExpressionType.LessThan: return OperatorKind.OP_LT; case ExpressionType.GreaterThan: return OperatorKind.OP_GT; case ExpressionType.LessThanOrEqual: return OperatorKind.OP_LE; case ExpressionType.GreaterThanOrEqual: return OperatorKind.OP_GE; case ExpressionType.Equal: return OperatorKind.OP_EQ; case ExpressionType.NotEqual: return OperatorKind.OP_NEQ; case ExpressionType.And: return bIsLogical ? OperatorKind.OP_LOGAND : OperatorKind.OP_BITAND; case ExpressionType.ExclusiveOr: return OperatorKind.OP_BITXOR; case ExpressionType.Or: return bIsLogical ? OperatorKind.OP_LOGOR : OperatorKind.OP_BITOR; // Binary in place operators. case ExpressionType.AddAssign: return OperatorKind.OP_ADDEQ; case ExpressionType.SubtractAssign: return OperatorKind.OP_SUBEQ; case ExpressionType.MultiplyAssign: return OperatorKind.OP_MULEQ; case ExpressionType.DivideAssign: return OperatorKind.OP_DIVEQ; case ExpressionType.ModuloAssign: return OperatorKind.OP_MODEQ; case ExpressionType.AndAssign: return OperatorKind.OP_ANDEQ; case ExpressionType.ExclusiveOrAssign: return OperatorKind.OP_XOREQ; case ExpressionType.OrAssign: return OperatorKind.OP_OREQ; case ExpressionType.LeftShiftAssign: return OperatorKind.OP_LSHIFTEQ; case ExpressionType.RightShiftAssign: return OperatorKind.OP_RSHIFTEQ; // Unary Operators case ExpressionType.Negate: return OperatorKind.OP_NEG; case ExpressionType.UnaryPlus: return OperatorKind.OP_UPLUS; case ExpressionType.Not: return OperatorKind.OP_LOGNOT; case ExpressionType.OnesComplement: return OperatorKind.OP_BITNOT; case ExpressionType.IsTrue: return OperatorKind.OP_TRUE; case ExpressionType.IsFalse: return OperatorKind.OP_FALSE; // Increment/Decrement. case ExpressionType.Increment: return OperatorKind.OP_PREINC; case ExpressionType.Decrement: return OperatorKind.OP_PREDEC; } } ///////////////////////////////////////////////////////////////////////////////// #endregion #region Properties ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindProperty( ICSharpBinder payload, ArgumentObject argument, LocalVariableSymbol local, Expr optionalIndexerArguments) { // If our argument is a static type, then we're calling a static property. Expr callingObject = argument.Info.IsStaticType ? ExprFactory.CreateClass(SymbolTable.GetCTypeFromType(argument.Value as Type)) : CreateLocal(argument.Type, argument.Info.IsOut, local); if (!argument.Info.UseCompileTimeType && argument.Value == null) { throw Error.NullReferenceOnMemberException(); } // If our argument is a struct type, unbox it. if (argument.Type.IsValueType && callingObject is ExprCast) { // If we have a struct type, unbox it. callingObject.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } string name = payload.Name; BindingFlag bindFlags = payload.BindingFlags; MemberLookup mem = new MemberLookup(); SymWithType swt = SymbolTable.LookupMember(name, callingObject, _binder.Context.ContextForMemberLookup, 0, mem, false, false); if (swt == null) { if (optionalIndexerArguments != null) { int numIndexArguments = ExpressionIterator.Count(optionalIndexerArguments); // We could have an array access here. See if its just an array. Type type = argument.Type; Debug.Assert(type != typeof(string)); if (type.IsArray) { if (type.IsArray && type.GetArrayRank() != numIndexArguments) { throw ErrorHandling.Error(ErrorCode.ERR_BadIndexCount, type.GetArrayRank()); } Debug.Assert(callingObject.Type is ArrayType); return CreateArray(callingObject, optionalIndexerArguments); } } throw mem.ReportErrors(); } switch (swt.Sym.getKind()) { case SYMKIND.SK_MethodSymbol: throw Error.BindPropertyFailedMethodGroup(name); case SYMKIND.SK_PropertySymbol: if (swt.Sym is IndexerSymbol) { return CreateIndexer(swt, callingObject, optionalIndexerArguments, bindFlags); } else { // Properties can be LValues. callingObject.Flags |= EXPRFLAG.EXF_LVALUE; return CreateProperty(swt, callingObject, payload.BindingFlags); } case SYMKIND.SK_FieldSymbol: return CreateField(swt, callingObject); case SYMKIND.SK_EventSymbol: throw Error.BindPropertyFailedEvent(name); default: Debug.Fail("Unexpected type returned from lookup"); throw Error.InternalCompilerError(); } } #endregion #region Casts ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindImplicitConversion( ArgumentObject[] arguments, Type returnType, LocalVariableSymbol[] locals, bool bIsArrayCreationConversion) { Debug.Assert(arguments.Length == 1); // Load the conversions on the target. SymbolTable.AddConversionsForType(returnType); Expr argument = CreateArgumentEXPR(arguments[0], locals[0]); CType destinationType = SymbolTable.GetCTypeFromType(returnType); if (bIsArrayCreationConversion) { // If we are converting for an array index, we want to convert to int, uint, // long, or ulong, depending on what the argument will allow. However, since // the compiler had to pick a particular type for the return value when it // made the callsite, we need to make sure that we ultimately return a type // of that value. So we "mustConvert" to the best type that chooseArrayIndexType // can find, and then we cast the result of that to the returnType, which is // incidentally Int32 in the existing compiler. For that cast, we do not consider // user defined conversions (since the convert is guaranteed to return one of // the primitive types), and we check for overflow since we don't want truncation. CType pDestType = _binder.ChooseArrayIndexType(argument); return _binder.mustCast( _binder.mustConvert(argument, pDestType), destinationType, CONVERTTYPE.CHECKOVERFLOW | CONVERTTYPE.NOUDC); } return _binder.mustConvert(argument, destinationType); } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindExplicitConversion(ArgumentObject[] arguments, Type returnType, LocalVariableSymbol[] locals) { Debug.Assert(arguments.Length == 1); // Load the conversions on the target. SymbolTable.AddConversionsForType(returnType); Expr argument = CreateArgumentEXPR(arguments[0], locals[0]); CType destinationType = SymbolTable.GetCTypeFromType(returnType); return _binder.mustCast(argument, destinationType); } #endregion #region Assignments ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindAssignment( ICSharpBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { Debug.Assert(arguments.Length >= 2); Debug.Assert(Array.TrueForAll(arguments, a => a.Type != null)); string name = payload.Name; // Find the lhs and rhs. Expr indexerArguments; bool bIsCompound; CSharpSetIndexBinder setIndexBinder = payload as CSharpSetIndexBinder; if (setIndexBinder != null) { // Get the list of indexer arguments - this is the list of arguments minus the last one. indexerArguments = CreateArgumentListEXPR(arguments, locals, 1, arguments.Length - 1); bIsCompound = setIndexBinder.IsCompoundAssignment; } else { indexerArguments = null; bIsCompound = (payload as CSharpSetMemberBinder).IsCompoundAssignment; } SymbolTable.PopulateSymbolTableWithName(name, null, arguments[0].Type); Expr lhs = BindProperty(payload, arguments[0], locals[0], indexerArguments); int indexOfLast = arguments.Length - 1; Expr rhs = CreateArgumentEXPR(arguments[indexOfLast], locals[indexOfLast]); return _binder.BindAssignment(lhs, rhs, bIsCompound); } #endregion #region Events ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindIsEvent( CSharpIsEventBinder binder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { // The IsEvent binder will never be called without an instance object. This // is because the compiler only gen's this code for dynamic dots. Expr callingObject = CreateLocal(arguments[0].Type, false, locals[0]); MemberLookup mem = new MemberLookup(); CType boolType = SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL); bool result = false; if (arguments[0].Value == null) { throw Error.NullReferenceOnMemberException(); } SymWithType swt = SymbolTable.LookupMember( binder.Name, callingObject, _binder.Context.ContextForMemberLookup, 0, mem, false, false); if (swt != null) { // If lookup returns an actual event, then this is an event. if (swt.Sym.getKind() == SYMKIND.SK_EventSymbol) { result = true; } // If lookup returns the backing field of a field-like event, then // this is an event. This is due to the Dev10 design change around // the binding of +=, and the fact that the "IsEvent" binding question // is only ever asked about the LHS of a += or -=. else if (swt.Sym is FieldSymbol field && field.isEvent) { result = true; } } return ExprFactory.CreateConstant(boolType, ConstVal.Get(result)); } #endregion } }
// 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.Dynamic; using System.Linq.Expressions; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Semantics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder { internal readonly struct RuntimeBinder { private static readonly object s_bindLock = new object(); private readonly ExpressionBinder _binder; internal bool IsChecked => _binder.Context.Checked; [RequiresUnreferencedCode(Binder.TrimmerWarning)] public RuntimeBinder(Type contextType, bool isChecked = false) { AggregateSymbol context; if (contextType != null) { lock (s_bindLock) { context = ((AggregateType)SymbolTable.GetCTypeFromType(contextType)).OwningAggregate; } } else { context = null; } _binder = new ExpressionBinder(new BindingContext(context, isChecked)); } [RequiresUnreferencedCode(Binder.TrimmerWarning)] public Expression Bind(ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding) { // The lock is here to protect this instance of the binder from itself // when called on multiple threads. The cost in time of a single lock // on a single thread appears to be negligible and dominated by the cost // of the bind itself. My timing of 4000 consecutive dynamic calls with // bind, where the body of the called method is empty, are as follows // (five samples): // // Without lock() With lock() // = 00:00:10.7597696 = 00:00:10.7222606 // = 00:00:10.0711116 = 00:00:10.1818496 // = 00:00:09.9905507 = 00:00:10.1628693 // = 00:00:09.9892183 = 00:00:10.0750007 // = 00:00:09.9253234 = 00:00:10.0340266 // // ...subsequent calls that were cache hits, i.e., already bound, took less // than 1/1000 sec for the whole 4000 of them. lock (s_bindLock) { return BindCore(payload, parameters, args, out deferredBinding); } } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expression BindCore( ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args, out DynamicMetaObject deferredBinding) { Debug.Assert(args.Length >= 1); ArgumentObject[] arguments = CreateArgumentArray(payload, parameters, args); // On any given bind call, we populate the symbol table with any new // conversions that we find for any of the types specified. We keep a // running SymbolTable so that we don't have to reflect over types if // we've seen them already in the table. // // Once we've loaded all the standard conversions into the symbol table, // we can call into the binder to bind the actual call. payload.PopulateSymbolTableWithName(arguments[0].Type, arguments); AddConversionsForArguments(arguments); // When we do any bind, we perform the following steps: // // 1) Create a local variable scope which contains local variable symbols // for each of the parameters, and the instance argument. // 2) If we have operators, then we don't need to do lookup. Otherwise, // look for the name and switch on the result - dispatch according to // the symbol kind. This results in an Expr being bound that is the expression. // 3) Create the EXPRRETURN which returns the call and wrap it in // an EXPRBOUNDLAMBDA which uses the local variable scope // created in step (1) as its local scope. // 4) Call the ExpressionTreeRewriter to generate a set of EXPRCALLs // that call the static ExpressionTree factory methods. // 5) Call the EXPRTreeToExpressionTreeVisitor to generate the actual // Linq expression tree for the whole thing and return it. // (1) - Create the locals Scope pScope = SymFactory.CreateScope(); LocalVariableSymbol[] locals = PopulateLocalScope(payload, pScope, arguments, parameters); // (1.5) - Check to see if we need to defer. if (DeferBinding(payload, arguments, args, locals, out deferredBinding)) { return null; } // (2) - look the thing up and dispatch. Expr pResult = payload.DispatchPayload(this, arguments, locals); Debug.Assert(pResult != null); return CreateExpressionTreeFromResult(parameters, pScope, pResult); } #region Helpers [ConditionalAttribute("DEBUG")] internal static void EnsureLockIsTaken() { // Make sure that the binder lock is taken Debug.Assert(System.Threading.Monitor.IsEntered(s_bindLock)); } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private bool DeferBinding( ICSharpBinder payload, ArgumentObject[] arguments, DynamicMetaObject[] args, LocalVariableSymbol[] locals, out DynamicMetaObject deferredBinding) { // This method deals with any deferrals we need to do. We check deferrals up front // and bail early if we need to do them. // (1) InvokeMember deferral. // // This is the deferral for the d.Foo() scenario where Foo actually binds to a // field or property, and not a method group that is invocable. We defer to // the standard GetMember/Invoke pattern. CSharpInvokeMemberBinder callPayload = payload as CSharpInvokeMemberBinder; if (callPayload != null) { int arity = callPayload.TypeArguments?.Length ?? 0; MemberLookup mem = new MemberLookup(); Expr callingObject = CreateCallingObjectForCall(callPayload, arguments, locals); SymWithType swt = SymbolTable.LookupMember( callPayload.Name, callingObject, _binder.Context.ContextForMemberLookup, arity, mem, (callPayload.Flags & CSharpCallFlags.EventHookup) != 0, true); if (swt != null && swt.Sym.getKind() != SYMKIND.SK_MethodSymbol) { // The GetMember only has one argument, and we need to just take the first arg info. CSharpGetMemberBinder getMember = new CSharpGetMemberBinder(callPayload.Name, false, callPayload.CallingContext, new CSharpArgumentInfo[] { callPayload.GetArgumentInfo(0) }).TryGetExisting(); // The Invoke has the remaining argument infos. However, we need to redo the first one // to correspond to the GetMember result. CSharpArgumentInfo[] argInfos = callPayload.ArgumentInfoArray(); argInfos[0] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null); CSharpInvokeBinder invoke = new CSharpInvokeBinder(callPayload.Flags, callPayload.CallingContext, argInfos).TryGetExisting(); DynamicMetaObject[] newArgs = new DynamicMetaObject[args.Length - 1]; Array.Copy(args, 1, newArgs, 0, args.Length - 1); deferredBinding = invoke.Defer(getMember.Defer(args[0]), newArgs); return true; } } deferredBinding = null; return false; } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static Expression CreateExpressionTreeFromResult(Expression[] parameters, Scope pScope, Expr pResult) { // (3) - Place the result in a return statement and create the ExprBoundLambda. ExprBoundLambda boundLambda = GenerateBoundLambda(pScope, pResult); // (4) - Rewrite the ExprBoundLambda into an expression tree. ExprBinOp exprTree = ExpressionTreeRewriter.Rewrite(boundLambda); // (5) - Create the actual Expression Tree Expression e = ExpressionTreeCallRewriter.Rewrite(exprTree, parameters); return e; } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Type GetArgumentType(ICSharpBinder p, CSharpArgumentInfo argInfo, Expression param, DynamicMetaObject arg, int index) { Type t = argInfo.UseCompileTimeType ? param.Type : arg.LimitType; Debug.Assert(t != null); if (argInfo.IsByRefOrOut) { // If we have a ref our an out parameter, make the byref type. // If we have the receiver of a call or invoke that is ref, it must be because of // a struct caller. Don't persist the ref for that. if (!(index == 0 && p.IsBinderThatCanHaveRefReceiver)) { t = t.MakeByRefType(); } } else if (!argInfo.UseCompileTimeType) { // If we don't have ref or out, then pick the best type to represent this value. // If the runtime value has a type that is not accessible, then we pick an // accessible type that is "closest" in some sense, where we recursively widen // components of type that can validly vary covariantly. // This ensures that the type we pick is something that the user could have written. // Since the actual type of these arguments are never going to be pointer // types or ref/out types (they are in fact boxed into an object), we have // a guarantee that we will always be able to find a best accessible type // (which, in the worst case, may be object). CType actualType = SymbolTable.GetCTypeFromType(t); CType bestType = TypeManager.GetBestAccessibleType(_binder.Context.ContextForMemberLookup, actualType); t = bestType.AssociatedSystemType; } return t; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private ArgumentObject[] CreateArgumentArray( ICSharpBinder payload, Expression[] parameters, DynamicMetaObject[] args) { // Check the payloads to see whether or not we need to get the runtime types for // these arguments. ArgumentObject[] array = new ArgumentObject[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { CSharpArgumentInfo info = payload.GetArgumentInfo(i); array[i] = new ArgumentObject(args[i].Value, info, GetArgumentType(payload, info, parameters[i], args[i], i)); Debug.Assert(array[i].Type != null); } return array; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal static void PopulateSymbolTableWithPayloadInformation( ICSharpInvokeOrInvokeMemberBinder callOrInvoke, Type callingType, ArgumentObject[] arguments) { Type type; if (callOrInvoke.StaticCall) { type = arguments[0].Value as Type; if (type == null) { throw Error.BindStaticRequiresType(arguments[0].Info.Name); } } else { type = callingType; } SymbolTable.PopulateSymbolTableWithName( callOrInvoke.Name, callOrInvoke.TypeArguments, type); // If it looks like we're invoking a get_ or a set_, load the property as well. // This is because we need COM indexed properties called via method calls to // work the same as it used to. if (callOrInvoke.Name.StartsWith("set_", StringComparison.Ordinal) || callOrInvoke.Name.StartsWith("get_", StringComparison.Ordinal)) { SymbolTable.PopulateSymbolTableWithName( callOrInvoke.Name.Substring(4), //remove prefix callOrInvoke.TypeArguments, type); } } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static void AddConversionsForArguments(ArgumentObject[] arguments) { foreach (ArgumentObject arg in arguments) { SymbolTable.AddConversionsForType(arg.Type); } } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal ExprWithArgs DispatchPayload(ICSharpInvokeOrInvokeMemberBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) => BindCall(payload, CreateCallingObjectForCall(payload, arguments, locals), arguments, locals); ///////////////////////////////////////////////////////////////////////////////// // We take the ArgumentObjects to verify - if the parameter expression tells us // we have a ref parameter, but the argument object tells us we're not passed by ref, // then it means it was a ref that the compiler had to insert. This is used when // we have a call off of a struct for example. If thats the case, don't treat the // local as a ref type. [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static LocalVariableSymbol[] PopulateLocalScope( ICSharpBinder payload, Scope pScope, ArgumentObject[] arguments, Expression[] parameterExpressions) { // We use the compile time types for the local variables, and then // cast them to the runtime types for the expression tree. LocalVariableSymbol[] locals = new LocalVariableSymbol[parameterExpressions.Length]; for (int i = 0; i < parameterExpressions.Length; i++) { Expression parameter = parameterExpressions[i]; CType type = SymbolTable.GetCTypeFromType(parameter.Type); // Make sure we're not setting ref for the receiver of a call - the argument // will be marked as ref if we're calling off a struct, but we don't want // to persist that in our system. // If we're the first param of a call or invoke, and we're ref, it must be // because of structs. Don't persist the parameter modifier type. if (i != 0 || !payload.IsBinderThatCanHaveRefReceiver) { // If we have a ref or out, get the parameter modifier type. ParameterExpression paramExp = parameter as ParameterExpression; if (paramExp != null && paramExp.IsByRef) { CSharpArgumentInfo info = arguments[i].Info; if (info.IsByRefOrOut) { type = TypeManager.GetParameterModifier(type, info.IsOut); } } } LocalVariableSymbol local = SymFactory.CreateLocalVar(NameManager.Add("p" + i), pScope, type); locals[i] = local; } return locals; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static ExprBoundLambda GenerateBoundLambda(Scope pScope, Expr call) { // We don't actually need the real delegate type here - we just need SOME delegate type. // This is because we never attempt any conversions on the lambda itself. AggregateType delegateType = SymbolLoader.GetPredefindType(PredefinedType.PT_FUNC); return ExprFactory.CreateAnonymousMethod(delegateType, pScope, call); } #region ExprCreation ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateLocal(Type type, bool isOut, LocalVariableSymbol local) { CType ctype; if (isOut) { // We need to record the out state, but GetCTypeFromType will only determine that // it should be some sort of ParameterType but not be able to deduce that it needs // IsOut to be true. So do that logic here rather than create a ref type to then // throw away. Debug.Assert(type.IsByRef); ctype = TypeManager.GetParameterModifier(SymbolTable.GetCTypeFromType(type.GetElementType()), true); } else { ctype = SymbolTable.GetCTypeFromType(type); } // If we can convert, do that. If not, cast it. ExprLocal exprLocal = ExprFactory.CreateLocal(local); Expr result = _binder.tryConvert(exprLocal, ctype) ?? _binder.mustCast(exprLocal, ctype); result.Flags |= EXPRFLAG.EXF_LVALUE; return result; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr CreateArgumentListEXPR( ArgumentObject[] arguments, LocalVariableSymbol[] locals, int startIndex, int endIndex) { Expr args = null; Expr last = null; if (arguments != null) { for (int i = startIndex; i < endIndex; i++) { ArgumentObject argument = arguments[i]; Expr arg = CreateArgumentEXPR(argument, locals[i]); if (args == null) { args = arg; last = args; } else { // Lists are right-heavy. ExprFactory.AppendItemToList(arg, ref args, ref last); } } } return args; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateArgumentEXPR(ArgumentObject argument, LocalVariableSymbol local) { Expr arg; if (argument.Info.LiteralConstant) { if (argument.Value == null) { if (argument.Info.UseCompileTimeType) { arg = ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), default(ConstVal)); } else { arg = ExprFactory.CreateNull(); } } else { arg = ExprFactory.CreateConstant(SymbolTable.GetCTypeFromType(argument.Type), ConstVal.Get(argument.Value)); } } else { // If we have a dynamic argument and it was null, the type is going to be Object. // But we want it to be typed NullType so we can have null conversions. if (!argument.Info.UseCompileTimeType && argument.Value == null) { arg = ExprFactory.CreateNull(); } else { arg = CreateLocal(argument.Type, argument.Info.IsOut, local); } } // Now check if we have a named thing. If so, wrap this thing in a named argument. if (argument.Info.NamedArgument) { Debug.Assert(argument.Info.Name != null); arg = ExprFactory.CreateNamedArgumentSpecification(NameManager.Add(argument.Info.Name), arg); } // If we have an object that was "dynamic" at compile time, we need // to be able to convert it to every interface that the actual value // implements. This allows conversion binders and overload resolution // to behave as though type information is available for these Exprs, // even though it may be the case that the actual runtime type is // inaccessible and therefore unused. // This comes in handy for, e.g., iterators (they are nested private // classes), and COM RCWs without type information (they do not expose // their interfaces in a usual way). // It is critical that arg.RuntimeObject is non-null only when the // compile time type of the argument is dynamic, otherwise normal C# // semantics on typed arguments will be broken. if (!argument.Info.UseCompileTimeType && argument.Value != null) { arg.RuntimeObject = argument.Value; arg.RuntimeObjectActualType = SymbolTable.GetCTypeFromType(argument.Value.GetType()); } return arg; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private static ExprMemberGroup CreateMemberGroupExpr( string Name, Type[] typeArguments, Expr callingObject, SYMKIND kind) { Name name = NameManager.Add(Name); AggregateType callingType; CType callingObjectType = callingObject.Type; if (callingObjectType is ArrayType) { callingType = SymbolLoader.GetPredefindType(PredefinedType.PT_ARRAY); } else if (callingObjectType is NullableType callingNub) { callingType = callingNub.GetAts(); } else { callingType = (AggregateType)callingObjectType; } // The C# binder expects that only the base virtual method is inserted // into the list of candidates, and only the type containing the base // virtual method is inserted into the list of types. However, since we // don't want to do all the logic, we're just going to insert every type // that has a member of the given name, and allow the C# binder to filter // out all overrides. // CONSIDER: using a hashset to filter out duplicate interface types. // Adopt a smarter algorithm to filter types before creating the exception. HashSet<CType> distinctCallingTypes = new HashSet<CType>(); List<CType> callingTypes = new List<CType>(); // Find that set of types now. symbmask_t mask = symbmask_t.MASK_MethodSymbol; switch (kind) { case SYMKIND.SK_PropertySymbol: case SYMKIND.SK_IndexerSymbol: mask = symbmask_t.MASK_PropertySymbol; break; case SYMKIND.SK_MethodSymbol: mask = symbmask_t.MASK_MethodSymbol; break; default: Debug.Fail("Unhandled kind"); break; } // If we have a constructor, only find its type. bool bIsConstructor = name == NameManager.GetPredefinedName(PredefinedName.PN_CTOR); foreach (AggregateType t in callingType.TypeHierarchy) { if (SymbolTable.AggregateContainsMethod(t.OwningAggregate, Name, mask) && distinctCallingTypes.Add(t)) { callingTypes.Add(t); } // If we have a constructor, run the loop once for the constructor's type, and thats it. if (bIsConstructor) { break; } } EXPRFLAG flags = EXPRFLAG.EXF_USERCALLABLE; // If its a delegate, mark that on the memgroup. if (Name == SpecialNames.Invoke && callingObject.Type.IsDelegateType) { flags |= EXPRFLAG.EXF_DELEGATE; } // For a constructor, we need to seed the memgroup with the constructor flag. if (Name == SpecialNames.Constructor) { flags |= EXPRFLAG.EXF_CTOR; } // If we have an indexer, mark that. if (Name == SpecialNames.Indexer) { flags |= EXPRFLAG.EXF_INDEXER; } TypeArray typeArgumentsAsTypeArray = typeArguments?.Length > 0 ? TypeArray.Allocate(SymbolTable.GetCTypeArrayFromTypes(typeArguments)) : TypeArray.Empty; ExprMemberGroup memgroup = ExprFactory.CreateMemGroup( // Tree flags, name, typeArgumentsAsTypeArray, kind, callingType, null, new CMemberLookupResults(TypeArray.Allocate(callingTypes.ToArray()), name)); if (!(callingObject is ExprClass)) { memgroup.OptionalObject = callingObject; } return memgroup; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateProperty( SymWithType swt, Expr callingObject, BindingFlag flags) { // For a property, we simply create the EXPRPROP for the thing, call the // expression tree rewriter, rewrite it, and send it on its way. PropertySymbol property = swt.Prop(); AggregateType propertyType = swt.GetType(); PropWithType pwt = new PropWithType(property, propertyType); ExprMemberGroup pMemGroup = CreateMemberGroupExpr(property.name.Text, null, callingObject, SYMKIND.SK_PropertySymbol); return _binder.BindToProperty(// For a static property instance, don't set the object. callingObject is ExprClass ? null : callingObject, pwt, flags, null, pMemGroup); } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private ExprWithArgs CreateIndexer(SymWithType swt, Expr callingObject, Expr arguments, BindingFlag bindFlags) { IndexerSymbol index = swt.Sym as IndexerSymbol; ExprMemberGroup memgroup = CreateMemberGroupExpr(index.name.Text, null, callingObject, SYMKIND.SK_PropertySymbol); ExprWithArgs result = _binder.BindMethodGroupToArguments(bindFlags, memgroup, arguments); ReorderArgumentsForNamedAndOptional(callingObject, result); return result; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateArray(Expr callingObject, Expr optionalIndexerArguments) { return _binder.BindArrayIndexCore(callingObject, optionalIndexerArguments); } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateField( SymWithType swt, Expr callingObject) { // For a field, simply create the EXPRFIELD and our caller takes care of the rest. FieldSymbol fieldSymbol = swt.Field(); AggregateType fieldType = swt.GetType(); FieldWithType fwt = new FieldWithType(fieldSymbol, fieldType); Expr field = _binder.BindToField(callingObject is ExprClass ? null : callingObject, fwt, 0); return field; } ///////////////////////////////////////////////////////////////////////////////// #endregion #endregion #region Calls ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private Expr CreateCallingObjectForCall( ICSharpInvokeOrInvokeMemberBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { // Here we have a regular call, so create the calling object off of the first // parameter and pass it through. Expr callingObject; if (payload.StaticCall) { Type t = arguments[0].Value as Type; Debug.Assert(t != null); // Would have thrown in PopulateSymbolTableWithPayloadInformation already callingObject = ExprFactory.CreateClass(SymbolTable.GetCTypeFromType(t)); } else { // If we have a null argument, just bail and throw. if (!arguments[0].Info.UseCompileTimeType && arguments[0].Value == null) { throw Error.NullReferenceOnMemberException(); } callingObject = _binder.mustConvert( CreateArgumentEXPR(arguments[0], locals[0]), SymbolTable.GetCTypeFromType(arguments[0].Type)); if (arguments[0].Type.IsValueType && callingObject is ExprCast) { // If we have a struct type, unbox it. callingObject.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } } return callingObject; } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] private ExprWithArgs BindCall( ICSharpInvokeOrInvokeMemberBinder payload, Expr callingObject, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { if (payload is InvokeBinder && !callingObject.Type.IsDelegateType) { throw Error.BindInvokeFailedNonDelegate(); } int arity = payload.TypeArguments?.Length ?? 0; MemberLookup mem = new MemberLookup(); SymWithType swt = SymbolTable.LookupMember( payload.Name, callingObject, _binder.Context.ContextForMemberLookup, arity, mem, (payload.Flags & CSharpCallFlags.EventHookup) != 0, true); if (swt == null) { throw mem.ReportErrors(); } if (swt.Sym.getKind() != SYMKIND.SK_MethodSymbol) { Debug.Fail("Unexpected type returned from lookup"); throw Error.InternalCompilerError(); } // At this point, we're set up to do binding. We need to do the following: // // 1) Create the EXPRLOCALs for the arguments, linking them to the local // variable symbols defined above. // 2) Create the EXPRMEMGRP for the call and the EXPRLOCAL for the object // of the call, and link the correct local variable symbol as above. // 3) Do overload resolution to get back an EXPRCALL. // // Our caller takes care of the rest. // First we need to check the sym that we got back. If we got back a static // method, then we may be in the situation where the user called the method // via a simple name call through the phantom overload. If thats the case, // then we want to sub in a type instead of the object. ExprMemberGroup memGroup = CreateMemberGroupExpr(payload.Name, payload.TypeArguments, callingObject, swt.Sym.getKind()); if ((payload.Flags & CSharpCallFlags.SimpleNameCall) != 0) { callingObject.Flags |= EXPRFLAG.EXF_SIMPLENAME; } if ((payload.Flags & CSharpCallFlags.EventHookup) != 0) { mem = new MemberLookup(); SymWithType swtEvent = SymbolTable.LookupMember( payload.Name.Split('_')[1], callingObject, _binder.Context.ContextForMemberLookup, arity, mem, (payload.Flags & CSharpCallFlags.EventHookup) != 0, true); if (swtEvent == null) { throw mem.ReportErrors(); } CType eventCType = null; if (swtEvent.Sym.getKind() == SYMKIND.SK_FieldSymbol) { eventCType = swtEvent.Field().GetType(); } else if (swtEvent.Sym.getKind() == SYMKIND.SK_EventSymbol) { eventCType = swtEvent.Event().type; } Type eventType = TypeManager.SubstType(eventCType, swtEvent.Ats).AssociatedSystemType; if (eventType != null) { // If we have an event hookup, first find the event itself. BindImplicitConversion(new ArgumentObject[] { arguments[1] }, eventType, locals, false); } memGroup.Flags &= ~EXPRFLAG.EXF_USERCALLABLE; } // Check if we have a potential call to an indexed property accessor. // If so, we'll flag overload resolution to let us call non-callables. if ((payload.Name.StartsWith("set_", StringComparison.Ordinal) && ((MethodSymbol)swt.Sym).Params.Count > 1) || (payload.Name.StartsWith("get_", StringComparison.Ordinal) && ((MethodSymbol)swt.Sym).Params.Count > 0)) { memGroup.Flags &= ~EXPRFLAG.EXF_USERCALLABLE; } ExprCall result = _binder.BindMethodGroupToArguments(// Tree BindingFlag.BIND_RVALUEREQUIRED | BindingFlag.BIND_STMTEXPRONLY, memGroup, CreateArgumentListEXPR(arguments, locals, 1, arguments.Length)) as ExprCall; Debug.Assert(result != null); CheckForConditionalMethodError(result); ReorderArgumentsForNamedAndOptional(callingObject, result); return result; } private static void CheckForConditionalMethodError(ExprCall call) { MethodSymbol method = call.MethWithInst.Meth(); object[] conditions = method.AssociatedMemberInfo.GetCustomAttributes(typeof(ConditionalAttribute), true); if (conditions.Length > 0) { throw Error.BindCallToConditionalMethod(method.name); } } [RequiresUnreferencedCode(Binder.TrimmerWarning)] private void ReorderArgumentsForNamedAndOptional(Expr callingObject, ExprWithArgs result) { Expr arguments = result.OptionalArguments; AggregateType type; MethodOrPropertySymbol methprop; ExprMemberGroup memgroup; TypeArray typeArgs; if (result is ExprCall call) { type = call.MethWithInst.Ats; methprop = call.MethWithInst.Meth(); memgroup = call.MemberGroup; typeArgs = call.MethWithInst.TypeArgs; } else { ExprProperty prop = result as ExprProperty; Debug.Assert(prop != null); type = prop.PropWithTypeSlot.Ats; methprop = prop.PropWithTypeSlot.Prop(); memgroup = prop.MemberGroup; typeArgs = null; } ArgInfos argInfo = new ArgInfos { carg = ExpressionBinder.CountArguments(arguments) }; ExpressionBinder.FillInArgInfoFromArgList(argInfo, arguments); // We need to substitute type parameters BEFORE getting the most derived one because // we're binding against the base method, and the derived method may change the // generic arguments. TypeArray parameters = TypeManager.SubstTypeArray(methprop.Params, type, typeArgs); methprop = ExpressionBinder.GroupToArgsBinder.FindMostDerivedMethod(methprop, callingObject.Type); ExpressionBinder.GroupToArgsBinder.ReOrderArgsForNamedArguments( methprop, parameters, type, memgroup, argInfo); Expr pList = null; // We reordered, so make a new list of them and set them on the constructor. // Go backwards cause lists are right-flushed. // Also perform the conversions to the right types. for (int i = argInfo.carg - 1; i >= 0; i--) { Expr pArg = argInfo.prgexpr[i]; // Strip the name-ness away, since we don't need it. pArg = StripNamedArgument(pArg); // Perform the correct conversion. pArg = _binder.tryConvert(pArg, parameters[i]); pList = pList == null ? pArg : ExprFactory.CreateList(pArg, pList); } result.OptionalArguments = pList; } private Expr StripNamedArgument(Expr pArg) { if (pArg is ExprNamedArgumentSpecification named) { pArg = named.Value; } else if (pArg is ExprArrayInit init) { init.OptionalArguments = StripNamedArguments(init.OptionalArguments); } return pArg; } private Expr StripNamedArguments(Expr pArg) { if (pArg is ExprList list) { while (true) { list.OptionalElement = StripNamedArgument(list.OptionalElement); if (list.OptionalNextListNode is ExprList next) { list = next; } else { list.OptionalNextListNode = StripNamedArgument(list.OptionalNextListNode); break; } } } return StripNamedArgument(pArg); } #endregion #region Operators #region UnaryOperators ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindUnaryOperation( CSharpUnaryOperationBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { Debug.Assert(arguments.Length == 1); OperatorKind op = GetOperatorKind(payload.Operation); Expr arg1 = CreateArgumentEXPR(arguments[0], locals[0]); arg1.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation)); if (op == OperatorKind.OP_TRUE || op == OperatorKind.OP_FALSE) { // For true and false, we try to convert to bool first. If that // doesn't work, then we look for user defined operators. Expr result = _binder.tryConvert(arg1, SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL)); if (result != null && op == OperatorKind.OP_FALSE) { // If we can convert to bool, we need to negate the thing if we're looking for false. result = _binder.BindStandardUnaryOperator(OperatorKind.OP_LOGNOT, result); } return result ?? _binder.bindUDUnop(op == OperatorKind.OP_TRUE ? ExpressionKind.True : ExpressionKind.False, arg1) // If the result is STILL null, then that means theres no implicit conversion to bool, // and no user-defined operators for true and false. Just do a must convert to report // the error. ?? _binder.mustConvert(arg1, SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL)); } return _binder.BindStandardUnaryOperator(op, arg1); } #endregion #region BinaryOperators ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindBinaryOperation( CSharpBinaryOperationBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { Debug.Assert(arguments.Length == 2); ExpressionKind ek = Operators.GetExpressionKind(GetOperatorKind(payload.Operation, payload.IsLogicalOperation)); Expr arg1 = CreateArgumentEXPR(arguments[0], locals[0]); Expr arg2 = CreateArgumentEXPR(arguments[1], locals[1]); arg1.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation, payload.IsLogicalOperation)); arg2.ErrorString = Operators.GetDisplayName(GetOperatorKind(payload.Operation, payload.IsLogicalOperation)); if (ek > ExpressionKind.MultiOffset) { ek = (ExpressionKind)(ek - ExpressionKind.MultiOffset); } return _binder.BindStandardBinop(ek, arg1, arg2); } #endregion ///////////////////////////////////////////////////////////////////////////////// private static OperatorKind GetOperatorKind(ExpressionType p) { return GetOperatorKind(p, false); } private static OperatorKind GetOperatorKind(ExpressionType p, bool bIsLogical) { switch (p) { default: Debug.Fail("Unknown operator: " + p); throw Error.InternalCompilerError(); // Binary Operators case ExpressionType.Add: return OperatorKind.OP_ADD; case ExpressionType.Subtract: return OperatorKind.OP_SUB; case ExpressionType.Multiply: return OperatorKind.OP_MUL; case ExpressionType.Divide: return OperatorKind.OP_DIV; case ExpressionType.Modulo: return OperatorKind.OP_MOD; case ExpressionType.LeftShift: return OperatorKind.OP_LSHIFT; case ExpressionType.RightShift: return OperatorKind.OP_RSHIFT; case ExpressionType.LessThan: return OperatorKind.OP_LT; case ExpressionType.GreaterThan: return OperatorKind.OP_GT; case ExpressionType.LessThanOrEqual: return OperatorKind.OP_LE; case ExpressionType.GreaterThanOrEqual: return OperatorKind.OP_GE; case ExpressionType.Equal: return OperatorKind.OP_EQ; case ExpressionType.NotEqual: return OperatorKind.OP_NEQ; case ExpressionType.And: return bIsLogical ? OperatorKind.OP_LOGAND : OperatorKind.OP_BITAND; case ExpressionType.ExclusiveOr: return OperatorKind.OP_BITXOR; case ExpressionType.Or: return bIsLogical ? OperatorKind.OP_LOGOR : OperatorKind.OP_BITOR; // Binary in place operators. case ExpressionType.AddAssign: return OperatorKind.OP_ADDEQ; case ExpressionType.SubtractAssign: return OperatorKind.OP_SUBEQ; case ExpressionType.MultiplyAssign: return OperatorKind.OP_MULEQ; case ExpressionType.DivideAssign: return OperatorKind.OP_DIVEQ; case ExpressionType.ModuloAssign: return OperatorKind.OP_MODEQ; case ExpressionType.AndAssign: return OperatorKind.OP_ANDEQ; case ExpressionType.ExclusiveOrAssign: return OperatorKind.OP_XOREQ; case ExpressionType.OrAssign: return OperatorKind.OP_OREQ; case ExpressionType.LeftShiftAssign: return OperatorKind.OP_LSHIFTEQ; case ExpressionType.RightShiftAssign: return OperatorKind.OP_RSHIFTEQ; // Unary Operators case ExpressionType.Negate: return OperatorKind.OP_NEG; case ExpressionType.UnaryPlus: return OperatorKind.OP_UPLUS; case ExpressionType.Not: return OperatorKind.OP_LOGNOT; case ExpressionType.OnesComplement: return OperatorKind.OP_BITNOT; case ExpressionType.IsTrue: return OperatorKind.OP_TRUE; case ExpressionType.IsFalse: return OperatorKind.OP_FALSE; // Increment/Decrement. case ExpressionType.Increment: return OperatorKind.OP_PREINC; case ExpressionType.Decrement: return OperatorKind.OP_PREDEC; } } ///////////////////////////////////////////////////////////////////////////////// #endregion #region Properties ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindProperty( ICSharpBinder payload, ArgumentObject argument, LocalVariableSymbol local, Expr optionalIndexerArguments) { // If our argument is a static type, then we're calling a static property. Expr callingObject = argument.Info.IsStaticType ? ExprFactory.CreateClass(SymbolTable.GetCTypeFromType(argument.Value as Type)) : CreateLocal(argument.Type, argument.Info.IsOut, local); if (!argument.Info.UseCompileTimeType && argument.Value == null) { throw Error.NullReferenceOnMemberException(); } // If our argument is a struct type, unbox it. if (argument.Type.IsValueType && callingObject is ExprCast) { // If we have a struct type, unbox it. callingObject.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } string name = payload.Name; BindingFlag bindFlags = payload.BindingFlags; MemberLookup mem = new MemberLookup(); SymWithType swt = SymbolTable.LookupMember(name, callingObject, _binder.Context.ContextForMemberLookup, 0, mem, false, false); if (swt == null) { if (optionalIndexerArguments != null) { int numIndexArguments = ExpressionIterator.Count(optionalIndexerArguments); // We could have an array access here. See if its just an array. Type type = argument.Type; Debug.Assert(type != typeof(string)); if (type.IsArray) { if (type.IsArray && type.GetArrayRank() != numIndexArguments) { throw ErrorHandling.Error(ErrorCode.ERR_BadIndexCount, type.GetArrayRank()); } Debug.Assert(callingObject.Type is ArrayType); return CreateArray(callingObject, optionalIndexerArguments); } } throw mem.ReportErrors(); } switch (swt.Sym.getKind()) { case SYMKIND.SK_MethodSymbol: throw Error.BindPropertyFailedMethodGroup(name); case SYMKIND.SK_PropertySymbol: if (swt.Sym is IndexerSymbol) { return CreateIndexer(swt, callingObject, optionalIndexerArguments, bindFlags); } else { // Properties can be LValues. callingObject.Flags |= EXPRFLAG.EXF_LVALUE; return CreateProperty(swt, callingObject, payload.BindingFlags); } case SYMKIND.SK_FieldSymbol: return CreateField(swt, callingObject); case SYMKIND.SK_EventSymbol: throw Error.BindPropertyFailedEvent(name); default: Debug.Fail("Unexpected type returned from lookup"); throw Error.InternalCompilerError(); } } #endregion #region Casts ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindImplicitConversion( ArgumentObject[] arguments, Type returnType, LocalVariableSymbol[] locals, bool bIsArrayCreationConversion) { Debug.Assert(arguments.Length == 1); // Load the conversions on the target. SymbolTable.AddConversionsForType(returnType); Expr argument = CreateArgumentEXPR(arguments[0], locals[0]); CType destinationType = SymbolTable.GetCTypeFromType(returnType); if (bIsArrayCreationConversion) { // If we are converting for an array index, we want to convert to int, uint, // long, or ulong, depending on what the argument will allow. However, since // the compiler had to pick a particular type for the return value when it // made the callsite, we need to make sure that we ultimately return a type // of that value. So we "mustConvert" to the best type that chooseArrayIndexType // can find, and then we cast the result of that to the returnType, which is // incidentally Int32 in the existing compiler. For that cast, we do not consider // user defined conversions (since the convert is guaranteed to return one of // the primitive types), and we check for overflow since we don't want truncation. CType pDestType = _binder.ChooseArrayIndexType(argument); return _binder.mustCast( _binder.mustConvert(argument, pDestType), destinationType, CONVERTTYPE.CHECKOVERFLOW | CONVERTTYPE.NOUDC); } return _binder.mustConvert(argument, destinationType); } ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindExplicitConversion(ArgumentObject[] arguments, Type returnType, LocalVariableSymbol[] locals) { Debug.Assert(arguments.Length == 1); // Load the conversions on the target. SymbolTable.AddConversionsForType(returnType); Expr argument = CreateArgumentEXPR(arguments[0], locals[0]); CType destinationType = SymbolTable.GetCTypeFromType(returnType); return _binder.mustCast(argument, destinationType); } #endregion #region Assignments ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindAssignment( ICSharpBinder payload, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { Debug.Assert(arguments.Length >= 2); Debug.Assert(Array.TrueForAll(arguments, a => a.Type != null)); string name = payload.Name; // Find the lhs and rhs. Expr indexerArguments; bool bIsCompound; CSharpSetIndexBinder setIndexBinder = payload as CSharpSetIndexBinder; if (setIndexBinder != null) { // Get the list of indexer arguments - this is the list of arguments minus the last one. indexerArguments = CreateArgumentListEXPR(arguments, locals, 1, arguments.Length - 1); bIsCompound = setIndexBinder.IsCompoundAssignment; } else { indexerArguments = null; bIsCompound = (payload as CSharpSetMemberBinder).IsCompoundAssignment; } SymbolTable.PopulateSymbolTableWithName(name, null, arguments[0].Type); Expr lhs = BindProperty(payload, arguments[0], locals[0], indexerArguments); int indexOfLast = arguments.Length - 1; Expr rhs = CreateArgumentEXPR(arguments[indexOfLast], locals[indexOfLast]); return _binder.BindAssignment(lhs, rhs, bIsCompound); } #endregion #region Events ///////////////////////////////////////////////////////////////////////////////// [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal Expr BindIsEvent( CSharpIsEventBinder binder, ArgumentObject[] arguments, LocalVariableSymbol[] locals) { // The IsEvent binder will never be called without an instance object. This // is because the compiler only gen's this code for dynamic dots. Expr callingObject = CreateLocal(arguments[0].Type, false, locals[0]); MemberLookup mem = new MemberLookup(); CType boolType = SymbolLoader.GetPredefindType(PredefinedType.PT_BOOL); bool result = false; if (arguments[0].Value == null) { throw Error.NullReferenceOnMemberException(); } SymWithType swt = SymbolTable.LookupMember( binder.Name, callingObject, _binder.Context.ContextForMemberLookup, 0, mem, false, false); if (swt != null) { // If lookup returns an actual event, then this is an event. if (swt.Sym.getKind() == SYMKIND.SK_EventSymbol) { result = true; } // If lookup returns the backing field of a field-like event, then // this is an event. This is due to the Dev10 design change around // the binding of +=, and the fact that the "IsEvent" binding question // is only ever asked about the LHS of a += or -=. else if (swt.Sym is FieldSymbol field && field.isEvent) { result = true; } } return ExprFactory.CreateConstant(boolType, ConstVal.Get(result)); } #endregion } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Data.Common/tests/System/Data/MissingPrimaryKeyExceptionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Copyright (c) 2004 Mainsoft Co. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; namespace System.Data.Tests { public class MissingPrimaryKeyExceptionTest { [Fact] public void Generate1() { DataTable tbl = DataProvider.CreateParentDataTable(); //can't invoke Find method with no primary key Assert.Throws<MissingPrimaryKeyException>(() => tbl.Rows.Find("Something")); } [Fact] public void Generate2() { DataTable tbl = DataProvider.CreateParentDataTable(); //can't invoke Contains method with no primary key Assert.Throws<MissingPrimaryKeyException>(() => tbl.Rows.Contains("Something")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Copyright (c) 2004 Mainsoft Co. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; namespace System.Data.Tests { public class MissingPrimaryKeyExceptionTest { [Fact] public void Generate1() { DataTable tbl = DataProvider.CreateParentDataTable(); //can't invoke Find method with no primary key Assert.Throws<MissingPrimaryKeyException>(() => tbl.Rows.Find("Something")); } [Fact] public void Generate2() { DataTable tbl = DataProvider.CreateParentDataTable(); //can't invoke Contains method with no primary key Assert.Throws<MissingPrimaryKeyException>(() => tbl.Rows.Contains("Something")); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Asn1/ReasonFlagsAsn.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.X509Certificates.Asn1 { // https://tools.ietf.org/html/rfc5280#section-4.2.1.13 // // ReasonFlags ::= BIT STRING { // unused (0), // keyCompromise (1), // cACompromise (2), // affiliationChanged (3), // superseded (4), // cessationOfOperation (5), // certificateHold (6), // privilegeWithdrawn (7), // aACompromise (8) // } [Flags] internal enum ReasonFlagsAsn { Unused = 1 << 0, KeyCompromise = 1 << 1, CACompromise = 1 << 2, AffiliationChanged = 1 << 3, Superseded = 1 << 4, CessationOfOperation = 1 << 5, CertificateHold = 1 << 6, PrivilegeWithdrawn = 1 << 7, AACompromise = 1 << 8, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.X509Certificates.Asn1 { // https://tools.ietf.org/html/rfc5280#section-4.2.1.13 // // ReasonFlags ::= BIT STRING { // unused (0), // keyCompromise (1), // cACompromise (2), // affiliationChanged (3), // superseded (4), // cessationOfOperation (5), // certificateHold (6), // privilegeWithdrawn (7), // aACompromise (8) // } [Flags] internal enum ReasonFlagsAsn { Unused = 1 << 0, KeyCompromise = 1 << 1, CACompromise = 1 << 2, AffiliationChanged = 1 << 3, Superseded = 1 << 4, CessationOfOperation = 1 << 5, CertificateHold = 1 << 6, PrivilegeWithdrawn = 1 << 7, AACompromise = 1 << 8, } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/Regression/JitBlue/Runtime_53549/Runtime_53549.cs
// 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.Threading; interface I { public Decimal F(); } class Runtime_53549 : I { Decimal z; public Decimal F() => z; public static bool G(object o) { return ((decimal) o).Equals(100M); } // This method will have bad codegen if // we allow GDV on i.F(). // [MethodImpl(MethodImplOptions.NoInlining)] public static int H(I i) { return G(i.F()) ? 100 : -1; } public static int Main() { Runtime_53549 x = new Runtime_53549(); x.z = 100M; for (int i = 0; i < 100; i++) { _ = H(x); Thread.Sleep(15); } return H(x); } }
// 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.Threading; interface I { public Decimal F(); } class Runtime_53549 : I { Decimal z; public Decimal F() => z; public static bool G(object o) { return ((decimal) o).Equals(100M); } // This method will have bad codegen if // we allow GDV on i.F(). // [MethodImpl(MethodImplOptions.NoInlining)] public static int H(I i) { return G(i.F()) ? 100 : -1; } public static int Main() { Runtime_53549 x = new Runtime_53549(); x.z = 100M; for (int i = 0; i < 100; i++) { _ = H(x); Thread.Sleep(15); } return H(x); } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/Regression/CLR-x86-EJIT/v1-m10/b02353/b02353.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <!-- Set to 'Full' if the Debug? column is marked in the spreadsheet. Leave blank otherwise. --> <DebugType>PdbOnly</DebugType> <NoStandardLib>True</NoStandardLib> <Noconfig>True</Noconfig> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/Performance/CodeQuality/Benchstones/MDBenchI/MDXposMatrix/MDXposMatrix.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> <PropertyGroup> <ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> </PropertyGroup> <PropertyGroup> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> <PropertyGroup> <ProjectAssetsFile>$(JitPackagesConfigFileDirectory)benchmark\obj\project.assets.json</ProjectAssetsFile> </PropertyGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DelegateCreationInfo.cs
// 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 Internal.IL; using Internal.TypeSystem; using Internal.Text; using ILCompiler.DependencyAnalysis; using Debug = System.Diagnostics.Debug; namespace ILCompiler { /// <summary> /// Captures information required to generate a ReadyToRun helper to create a delegate type instance /// pointing to a specific target method. /// </summary> public sealed class DelegateCreationInfo { private enum TargetKind { CanonicalEntrypoint, ExactCallableAddress, InterfaceDispatch, VTableLookup, MethodHandle, } private TargetKind _targetKind; /// <summary> /// Gets the node corresponding to the method that initializes the delegate. /// </summary> public IMethodNode Constructor { get; } public MethodDesc TargetMethod { get; } private bool TargetMethodIsUnboxingThunk { get { return TargetMethod.OwningType.IsValueType && !TargetMethod.Signature.IsStatic; } } public bool TargetNeedsVTableLookup => _targetKind == TargetKind.VTableLookup; public bool NeedsVirtualMethodUseTracking { get { return _targetKind == TargetKind.VTableLookup || _targetKind == TargetKind.InterfaceDispatch; } } public bool NeedsRuntimeLookup { get { switch (_targetKind) { case TargetKind.VTableLookup: return false; case TargetKind.CanonicalEntrypoint: case TargetKind.ExactCallableAddress: case TargetKind.InterfaceDispatch: case TargetKind.MethodHandle: return TargetMethod.IsRuntimeDeterminedExactMethod; default: Debug.Assert(false); return false; } } } // None of the data structures that support shared generics have been ported to the JIT // codebase which makes this a huge PITA. Not including the method for JIT since nobody // uses it in that mode anyway. #if !SUPPORT_JIT public GenericLookupResult GetLookupKind(NodeFactory factory) { Debug.Assert(NeedsRuntimeLookup); switch (_targetKind) { case TargetKind.ExactCallableAddress: return factory.GenericLookup.MethodEntry(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.InterfaceDispatch: return factory.GenericLookup.VirtualDispatchCell(TargetMethod); case TargetKind.MethodHandle: return factory.GenericLookup.MethodHandle(TargetMethod); default: Debug.Assert(false); return null; } } #endif /// <summary> /// Gets the node representing the target method of the delegate if no runtime lookup is needed. /// </summary> public ISymbolNode GetTargetNode(NodeFactory factory) { Debug.Assert(!NeedsRuntimeLookup); switch (_targetKind) { case TargetKind.CanonicalEntrypoint: return factory.CanonicalEntrypoint(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.ExactCallableAddress: return factory.ExactCallableAddress(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.InterfaceDispatch: return factory.InterfaceDispatchCell(TargetMethod); case TargetKind.MethodHandle: return factory.RuntimeMethodHandle(TargetMethod); case TargetKind.VTableLookup: Debug.Fail("Need to do runtime lookup"); return null; default: Debug.Assert(false); return null; } } /// <summary> /// Gets an optional node passed as an additional argument to the constructor. /// </summary> public IMethodNode Thunk { get; } private DelegateCreationInfo(IMethodNode constructor, MethodDesc targetMethod, TargetKind targetKind, IMethodNode thunk = null) { Debug.Assert(targetKind != TargetKind.VTableLookup || MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(targetMethod) == targetMethod); Constructor = constructor; TargetMethod = targetMethod; _targetKind = targetKind; Thunk = thunk; } /// <summary> /// Constructs a new instance of <see cref="DelegateCreationInfo"/> set up to construct a delegate of type /// '<paramref name="delegateType"/>' pointing to '<paramref name="targetMethod"/>'. /// </summary> public static DelegateCreationInfo Create(TypeDesc delegateType, MethodDesc targetMethod, NodeFactory factory, bool followVirtualDispatch) { CompilerTypeSystemContext context = factory.TypeSystemContext; DefType systemDelegate = context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType; int paramCountTargetMethod = targetMethod.Signature.Length; if (!targetMethod.Signature.IsStatic) { paramCountTargetMethod++; } DelegateInfo delegateInfo = context.GetDelegateInfo(delegateType.GetTypeDefinition()); int paramCountDelegateClosed = delegateInfo.Signature.Length + 1; bool closed = false; if (paramCountDelegateClosed == paramCountTargetMethod) { closed = true; } else { Debug.Assert(paramCountDelegateClosed == paramCountTargetMethod + 1); } if (targetMethod.Signature.IsStatic) { MethodDesc invokeThunk; MethodDesc initMethod; if (!closed) { initMethod = systemDelegate.GetKnownMethod("InitializeOpenStaticThunk", null); invokeThunk = delegateInfo.Thunks[DelegateThunkKind.OpenStaticThunk]; } else { // Closed delegate to a static method (i.e. delegate to an extension method that locks the first parameter) invokeThunk = delegateInfo.Thunks[DelegateThunkKind.ClosedStaticThunk]; initMethod = systemDelegate.GetKnownMethod("InitializeClosedStaticThunk", null); } var instantiatedDelegateType = delegateType as InstantiatedType; if (instantiatedDelegateType != null) invokeThunk = context.GetMethodForInstantiatedType(invokeThunk, instantiatedDelegateType); return new DelegateCreationInfo( factory.MethodEntrypoint(initMethod), targetMethod, TargetKind.ExactCallableAddress, factory.MethodEntrypoint(invokeThunk)); } else { if (!closed) throw new NotImplementedException("Open instance delegates"); string initializeMethodName = "InitializeClosedInstance"; MethodDesc targetCanonMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); TargetKind kind; if (targetMethod.HasInstantiation) { if (followVirtualDispatch && targetMethod.IsVirtual) { initializeMethodName = "InitializeClosedInstanceWithGVMResolution"; kind = TargetKind.MethodHandle; } else { if (targetMethod != targetCanonMethod) { // Closed delegates to generic instance methods need to be constructed through a slow helper that // checks for the fat function pointer case (function pointer + instantiation argument in a single // pointer) and injects an invocation thunk to unwrap the fat function pointer as part of // the invocation if necessary. initializeMethodName = "InitializeClosedInstanceSlow"; } kind = TargetKind.ExactCallableAddress; } } else { if (followVirtualDispatch && targetMethod.IsVirtual) { if (targetMethod.OwningType.IsInterface) { kind = TargetKind.InterfaceDispatch; initializeMethodName = "InitializeClosedInstanceToInterface"; } else { kind = TargetKind.VTableLookup; targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); } } else { kind = TargetKind.CanonicalEntrypoint; targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); } } return new DelegateCreationInfo( factory.MethodEntrypoint(systemDelegate.GetKnownMethod(initializeMethodName, null)), targetMethod, kind); } } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append("__DelegateCtor_"); if (TargetNeedsVTableLookup) sb.Append("FromVtbl_"); Constructor.AppendMangledName(nameMangler, sb); sb.Append("__"); sb.Append(nameMangler.GetMangledMethodName(TargetMethod)); if (Thunk != null) { sb.Append("__"); Thunk.AppendMangledName(nameMangler, sb); } } public override bool Equals(object obj) { var other = obj as DelegateCreationInfo; return other != null && Constructor == other.Constructor && TargetMethod == other.TargetMethod && _targetKind == other._targetKind && Thunk == other.Thunk; } public override int GetHashCode() { return Constructor.GetHashCode() ^ TargetMethod.GetHashCode(); } #if !SUPPORT_JIT internal int CompareTo(DelegateCreationInfo other, TypeSystemComparer comparer) { var compare = _targetKind - other._targetKind; if (compare != 0) return compare; compare = comparer.Compare(TargetMethod, other.TargetMethod); if (compare != 0) return compare; compare = comparer.Compare(Constructor.Method, other.Constructor.Method); if (compare != 0) return compare; if (Thunk == other.Thunk) return 0; if (Thunk == null) return -1; if (other.Thunk == null) return 1; return comparer.Compare(Thunk.Method, other.Thunk.Method); } #endif } }
// 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 Internal.IL; using Internal.TypeSystem; using Internal.Text; using ILCompiler.DependencyAnalysis; using Debug = System.Diagnostics.Debug; namespace ILCompiler { /// <summary> /// Captures information required to generate a ReadyToRun helper to create a delegate type instance /// pointing to a specific target method. /// </summary> public sealed class DelegateCreationInfo { private enum TargetKind { CanonicalEntrypoint, ExactCallableAddress, InterfaceDispatch, VTableLookup, MethodHandle, } private TargetKind _targetKind; /// <summary> /// Gets the node corresponding to the method that initializes the delegate. /// </summary> public IMethodNode Constructor { get; } public MethodDesc TargetMethod { get; } private bool TargetMethodIsUnboxingThunk { get { return TargetMethod.OwningType.IsValueType && !TargetMethod.Signature.IsStatic; } } public bool TargetNeedsVTableLookup => _targetKind == TargetKind.VTableLookup; public bool NeedsVirtualMethodUseTracking { get { return _targetKind == TargetKind.VTableLookup || _targetKind == TargetKind.InterfaceDispatch; } } public bool NeedsRuntimeLookup { get { switch (_targetKind) { case TargetKind.VTableLookup: return false; case TargetKind.CanonicalEntrypoint: case TargetKind.ExactCallableAddress: case TargetKind.InterfaceDispatch: case TargetKind.MethodHandle: return TargetMethod.IsRuntimeDeterminedExactMethod; default: Debug.Assert(false); return false; } } } // None of the data structures that support shared generics have been ported to the JIT // codebase which makes this a huge PITA. Not including the method for JIT since nobody // uses it in that mode anyway. #if !SUPPORT_JIT public GenericLookupResult GetLookupKind(NodeFactory factory) { Debug.Assert(NeedsRuntimeLookup); switch (_targetKind) { case TargetKind.ExactCallableAddress: return factory.GenericLookup.MethodEntry(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.InterfaceDispatch: return factory.GenericLookup.VirtualDispatchCell(TargetMethod); case TargetKind.MethodHandle: return factory.GenericLookup.MethodHandle(TargetMethod); default: Debug.Assert(false); return null; } } #endif /// <summary> /// Gets the node representing the target method of the delegate if no runtime lookup is needed. /// </summary> public ISymbolNode GetTargetNode(NodeFactory factory) { Debug.Assert(!NeedsRuntimeLookup); switch (_targetKind) { case TargetKind.CanonicalEntrypoint: return factory.CanonicalEntrypoint(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.ExactCallableAddress: return factory.ExactCallableAddress(TargetMethod, TargetMethodIsUnboxingThunk); case TargetKind.InterfaceDispatch: return factory.InterfaceDispatchCell(TargetMethod); case TargetKind.MethodHandle: return factory.RuntimeMethodHandle(TargetMethod); case TargetKind.VTableLookup: Debug.Fail("Need to do runtime lookup"); return null; default: Debug.Assert(false); return null; } } /// <summary> /// Gets an optional node passed as an additional argument to the constructor. /// </summary> public IMethodNode Thunk { get; } private DelegateCreationInfo(IMethodNode constructor, MethodDesc targetMethod, TargetKind targetKind, IMethodNode thunk = null) { Debug.Assert(targetKind != TargetKind.VTableLookup || MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(targetMethod) == targetMethod); Constructor = constructor; TargetMethod = targetMethod; _targetKind = targetKind; Thunk = thunk; } /// <summary> /// Constructs a new instance of <see cref="DelegateCreationInfo"/> set up to construct a delegate of type /// '<paramref name="delegateType"/>' pointing to '<paramref name="targetMethod"/>'. /// </summary> public static DelegateCreationInfo Create(TypeDesc delegateType, MethodDesc targetMethod, NodeFactory factory, bool followVirtualDispatch) { CompilerTypeSystemContext context = factory.TypeSystemContext; DefType systemDelegate = context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType; int paramCountTargetMethod = targetMethod.Signature.Length; if (!targetMethod.Signature.IsStatic) { paramCountTargetMethod++; } DelegateInfo delegateInfo = context.GetDelegateInfo(delegateType.GetTypeDefinition()); int paramCountDelegateClosed = delegateInfo.Signature.Length + 1; bool closed = false; if (paramCountDelegateClosed == paramCountTargetMethod) { closed = true; } else { Debug.Assert(paramCountDelegateClosed == paramCountTargetMethod + 1); } if (targetMethod.Signature.IsStatic) { MethodDesc invokeThunk; MethodDesc initMethod; if (!closed) { initMethod = systemDelegate.GetKnownMethod("InitializeOpenStaticThunk", null); invokeThunk = delegateInfo.Thunks[DelegateThunkKind.OpenStaticThunk]; } else { // Closed delegate to a static method (i.e. delegate to an extension method that locks the first parameter) invokeThunk = delegateInfo.Thunks[DelegateThunkKind.ClosedStaticThunk]; initMethod = systemDelegate.GetKnownMethod("InitializeClosedStaticThunk", null); } var instantiatedDelegateType = delegateType as InstantiatedType; if (instantiatedDelegateType != null) invokeThunk = context.GetMethodForInstantiatedType(invokeThunk, instantiatedDelegateType); return new DelegateCreationInfo( factory.MethodEntrypoint(initMethod), targetMethod, TargetKind.ExactCallableAddress, factory.MethodEntrypoint(invokeThunk)); } else { if (!closed) throw new NotImplementedException("Open instance delegates"); string initializeMethodName = "InitializeClosedInstance"; MethodDesc targetCanonMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); TargetKind kind; if (targetMethod.HasInstantiation) { if (followVirtualDispatch && targetMethod.IsVirtual) { initializeMethodName = "InitializeClosedInstanceWithGVMResolution"; kind = TargetKind.MethodHandle; } else { if (targetMethod != targetCanonMethod) { // Closed delegates to generic instance methods need to be constructed through a slow helper that // checks for the fat function pointer case (function pointer + instantiation argument in a single // pointer) and injects an invocation thunk to unwrap the fat function pointer as part of // the invocation if necessary. initializeMethodName = "InitializeClosedInstanceSlow"; } kind = TargetKind.ExactCallableAddress; } } else { if (followVirtualDispatch && targetMethod.IsVirtual) { if (targetMethod.OwningType.IsInterface) { kind = TargetKind.InterfaceDispatch; initializeMethodName = "InitializeClosedInstanceToInterface"; } else { kind = TargetKind.VTableLookup; targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); } } else { kind = TargetKind.CanonicalEntrypoint; targetMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); } } return new DelegateCreationInfo( factory.MethodEntrypoint(systemDelegate.GetKnownMethod(initializeMethodName, null)), targetMethod, kind); } } public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append("__DelegateCtor_"); if (TargetNeedsVTableLookup) sb.Append("FromVtbl_"); Constructor.AppendMangledName(nameMangler, sb); sb.Append("__"); sb.Append(nameMangler.GetMangledMethodName(TargetMethod)); if (Thunk != null) { sb.Append("__"); Thunk.AppendMangledName(nameMangler, sb); } } public override bool Equals(object obj) { var other = obj as DelegateCreationInfo; return other != null && Constructor == other.Constructor && TargetMethod == other.TargetMethod && _targetKind == other._targetKind && Thunk == other.Thunk; } public override int GetHashCode() { return Constructor.GetHashCode() ^ TargetMethod.GetHashCode(); } #if !SUPPORT_JIT internal int CompareTo(DelegateCreationInfo other, TypeSystemComparer comparer) { var compare = _targetKind - other._targetKind; if (compare != 0) return compare; compare = comparer.Compare(TargetMethod, other.TargetMethod); if (compare != 0) return compare; compare = comparer.Compare(Constructor.Method, other.Constructor.Method); if (compare != 0) return compare; if (Thunk == other.Thunk) return 0; if (Thunk == null) return -1; if (other.Thunk == null) return 1; return comparer.Compare(Thunk.Method, other.Thunk.Method); } #endif } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/HardwareIntrinsics/General/Vector128_1/As.Double.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsDouble() { var test = new VectorAs__AsDouble(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsDouble { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector128<Double> value; value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector128<Double> value; value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<byte> byteResult = value.As<Double, byte>(); ValidateResult(byteResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<double> doubleResult = value.As<Double, double>(); ValidateResult(doubleResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<short> shortResult = value.As<Double, short>(); ValidateResult(shortResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<int> intResult = value.As<Double, int>(); ValidateResult(intResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<long> longResult = value.As<Double, long>(); ValidateResult(longResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<sbyte> sbyteResult = value.As<Double, sbyte>(); ValidateResult(sbyteResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<float> floatResult = value.As<Double, float>(); ValidateResult(floatResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<ushort> ushortResult = value.As<Double, ushort>(); ValidateResult(ushortResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<uint> uintResult = value.As<Double, uint>(); ValidateResult(uintResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<ulong> ulongResult = value.As<Double, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector128<Double> value; value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object byteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsByte)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<byte>)(byteResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object doubleResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsDouble)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<double>)(doubleResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object shortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt16)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<short>)(shortResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object intResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt32)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<int>)(intResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object longResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt64)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<long>)(longResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object sbyteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSByte)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<sbyte>)(sbyteResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object floatResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSingle)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<float>)(floatResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object ushortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt16)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ushort>)(ushortResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object uintResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt32)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<uint>)(uintResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object ulongResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt64)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector128<T> result, Vector128<Double> value, [CallerMemberName] string method = "") where T : struct { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); Double[] valueElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(Double[] resultElements, Double[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Double>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsDouble() { var test = new VectorAs__AsDouble(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsDouble { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector128<Double> value; value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector128<Double> value; value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<byte> byteResult = value.As<Double, byte>(); ValidateResult(byteResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<double> doubleResult = value.As<Double, double>(); ValidateResult(doubleResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<short> shortResult = value.As<Double, short>(); ValidateResult(shortResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<int> intResult = value.As<Double, int>(); ValidateResult(intResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<long> longResult = value.As<Double, long>(); ValidateResult(longResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<sbyte> sbyteResult = value.As<Double, sbyte>(); ValidateResult(sbyteResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<float> floatResult = value.As<Double, float>(); ValidateResult(floatResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<ushort> ushortResult = value.As<Double, ushort>(); ValidateResult(ushortResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<uint> uintResult = value.As<Double, uint>(); ValidateResult(uintResult, value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); Vector128<ulong> ulongResult = value.As<Double, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector128<Double> value; value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object byteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsByte)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<byte>)(byteResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object doubleResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsDouble)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<double>)(doubleResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object shortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt16)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<short>)(shortResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object intResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt32)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<int>)(intResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object longResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt64)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<long>)(longResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object sbyteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSByte)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<sbyte>)(sbyteResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object floatResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSingle)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<float>)(floatResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object ushortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt16)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ushort>)(ushortResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object uintResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt32)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<uint>)(uintResult), value); value = Vector128.Create((double)TestLibrary.Generator.GetDouble()); object ulongResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt64)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector128<T> result, Vector128<Double> value, [CallerMemberName] string method = "") where T : struct { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); Double[] valueElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(Double[] resultElements, Double[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Double>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/coreclr/tools/Common/TypeSystem/Common/MethodDesc.cs
// 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.Runtime.CompilerServices; using Internal.NativeFormat; namespace Internal.TypeSystem { [Flags] public enum MethodSignatureFlags { None = 0x0000, // TODO: Generic, etc. UnmanagedCallingConventionMask = 0x000F, UnmanagedCallingConventionCdecl = 0x0001, UnmanagedCallingConventionStdCall = 0x0002, UnmanagedCallingConventionThisCall = 0x0003, CallingConventionVarargs = 0x0005, UnmanagedCallingConvention = 0x0009, Static = 0x0010, } public enum EmbeddedSignatureDataKind { RequiredCustomModifier = 0, OptionalCustomModifier = 1, ArrayShape = 2 } public struct EmbeddedSignatureData { public string index; public EmbeddedSignatureDataKind kind; public TypeDesc type; } /// <summary> /// Represents the parameter types, the return type, and flags of a method. /// </summary> public sealed partial class MethodSignature : TypeSystemEntity { internal MethodSignatureFlags _flags; internal int _genericParameterCount; internal TypeDesc _returnType; internal TypeDesc[] _parameters; internal EmbeddedSignatureData[] _embeddedSignatureData; // Value of <see cref="EmbeddedSignatureData.index" /> for any custom modifiers on the return type public const string IndexOfCustomModifiersOnReturnType = "0.1.1.1"; // Value of <see cref="EmbeddedSignatureData.index" /> for any custom modifiers on // SomeStruct when SomeStruct *, or SomeStruct & is the type of a parameter or return type // Parameter index 0 represents the return type, and indices 1-n represent the parameters to the signature public static string GetIndexOfCustomModifierOnPointedAtTypeByParameterIndex(int parameterIndex) { return $"0.1.1.2.{(parameterIndex + 1).ToStringInvariant()}.1"; } // Provide a means to create a MethodSignature which ignores EmbeddedSignature data in the MethodSignatures it is compared to public static EmbeddedSignatureData[] EmbeddedSignatureMismatchPermittedFlag = new EmbeddedSignatureData[0]; public MethodSignature(MethodSignatureFlags flags, int genericParameterCount, TypeDesc returnType, TypeDesc[] parameters, EmbeddedSignatureData[] embeddedSignatureData = null) { _flags = flags; _genericParameterCount = genericParameterCount; _returnType = returnType; _parameters = parameters; _embeddedSignatureData = embeddedSignatureData; Debug.Assert(parameters != null, "Parameters must not be null"); } public MethodSignature ApplySubstitution(Instantiation substitution) { if (substitution.IsNull) return this; bool needsNewMethodSignature = false; TypeDesc[] newParameters = _parameters; // Re-use existing array until conflict appears TypeDesc returnTypeNew = _returnType.InstantiateSignature(substitution, default(Instantiation)); if (returnTypeNew != _returnType) { needsNewMethodSignature = true; newParameters = (TypeDesc[])_parameters.Clone(); } for (int i = 0; i < newParameters.Length; i++) { TypeDesc newParameter = newParameters[i].InstantiateSignature(substitution, default(Instantiation)); if (newParameter != newParameters[i]) { if (!needsNewMethodSignature) { needsNewMethodSignature = true; newParameters = (TypeDesc[])_parameters.Clone(); } newParameters[i] = newParameter; } } if (needsNewMethodSignature) { return new MethodSignature(_flags, _genericParameterCount, returnTypeNew, newParameters, _embeddedSignatureData); } else { return this; } } public MethodSignatureFlags Flags { get { return _flags; } } public bool IsStatic { get { return (_flags & MethodSignatureFlags.Static) != 0; } } public int GenericParameterCount { get { return _genericParameterCount; } } public TypeDesc ReturnType { get { return _returnType; } } /// <summary> /// Gets the parameter type at the specified index. /// </summary> [IndexerName("Parameter")] public TypeDesc this[int index] { get { return _parameters[index]; } } /// <summary> /// Gets the number of parameters of this method signature. /// </summary> public int Length { get { return _parameters.Length; } } public bool HasEmbeddedSignatureData { get { return _embeddedSignatureData != null && _embeddedSignatureData.Length != 0; } } public bool EmbeddedSignatureMismatchPermitted { get { return _embeddedSignatureData == EmbeddedSignatureMismatchPermittedFlag; } } public EmbeddedSignatureData[] GetEmbeddedSignatureData() { if ((_embeddedSignatureData == null) || (_embeddedSignatureData.Length == 0)) return null; return (EmbeddedSignatureData[])_embeddedSignatureData.Clone(); } public bool Equals(MethodSignature otherSignature) { return Equals(otherSignature, allowCovariantReturn: false); } public bool EqualsWithCovariantReturnType(MethodSignature otherSignature) { return Equals(otherSignature, allowCovariantReturn: true); } private bool Equals(MethodSignature otherSignature, bool allowCovariantReturn) { // TODO: Generics, etc. if (this._flags != otherSignature._flags) return false; if (this._genericParameterCount != otherSignature._genericParameterCount) return false; if (this._returnType != otherSignature._returnType) { if (!allowCovariantReturn) return false; if (!otherSignature._returnType.IsCompatibleWith(this._returnType)) return false; } if (this._parameters.Length != otherSignature._parameters.Length) return false; for (int i = 0; i < this._parameters.Length; i++) { if (this._parameters[i] != otherSignature._parameters[i]) return false; } if (this._embeddedSignatureData == null && otherSignature._embeddedSignatureData == null) { return true; } // Array methods do not need to have matching details for the array parameters they support if (this.EmbeddedSignatureMismatchPermitted || otherSignature.EmbeddedSignatureMismatchPermitted) { return true; } if (this._embeddedSignatureData != null && otherSignature._embeddedSignatureData != null) { if (this._embeddedSignatureData.Length != otherSignature._embeddedSignatureData.Length) { return false; } for (int i = 0; i < this._embeddedSignatureData.Length; i++) { if (this._embeddedSignatureData[i].index != otherSignature._embeddedSignatureData[i].index) return false; if (this._embeddedSignatureData[i].kind != otherSignature._embeddedSignatureData[i].kind) return false; if (this._embeddedSignatureData[i].type != otherSignature._embeddedSignatureData[i].type) return false; } return true; } return false; } public override bool Equals(object obj) { return obj is MethodSignature && Equals((MethodSignature)obj); } public override int GetHashCode() { return TypeHashingAlgorithms.ComputeMethodSignatureHashCode(_returnType.GetHashCode(), _parameters); } public SignatureEnumerator GetEnumerator() { return new SignatureEnumerator(this); } public override TypeSystemContext Context => _returnType.Context; public struct SignatureEnumerator { private int _index; private MethodSignature _signature; public SignatureEnumerator(MethodSignature signature) { _signature = signature; _index = -1; } public TypeDesc Current => _signature[_index]; public bool MoveNext() { _index++; return _index < _signature.Length; } } } /// <summary> /// Helper structure for building method signatures by cloning an existing method signature. /// </summary> /// <remarks> /// This can potentially avoid array allocation costs for allocating the parameter type list. /// </remarks> public struct MethodSignatureBuilder { private MethodSignature _template; private MethodSignatureFlags _flags; private int _genericParameterCount; private TypeDesc _returnType; private TypeDesc[] _parameters; private EmbeddedSignatureData[] _customModifiers; public MethodSignatureBuilder(MethodSignature template) { _template = template; _flags = template._flags; _genericParameterCount = template._genericParameterCount; _returnType = template._returnType; _parameters = template._parameters; _customModifiers = template._embeddedSignatureData; } public MethodSignatureFlags Flags { set { _flags = value; } } public TypeDesc ReturnType { set { _returnType = value; } } [System.Runtime.CompilerServices.IndexerName("Parameter")] public TypeDesc this[int index] { set { if (_parameters[index] == value) return; if (_template != null && _parameters == _template._parameters) { TypeDesc[] parameters = new TypeDesc[_parameters.Length]; for (int i = 0; i < parameters.Length; i++) parameters[i] = _parameters[i]; _parameters = parameters; } _parameters[index] = value; } } public int Length { set { _parameters = new TypeDesc[value]; _template = null; } } public MethodSignature ToSignature() { if (_template == null || _flags != _template._flags || _genericParameterCount != _template._genericParameterCount || _returnType != _template._returnType || _parameters != _template._parameters) { _template = new MethodSignature(_flags, _genericParameterCount, _returnType, _parameters, _customModifiers); } return _template; } } /// <summary> /// Represents the fundamental base type for all methods within the type system. /// </summary> public abstract partial class MethodDesc : TypeSystemEntity { #pragma warning disable CA1825 // avoid Array.Empty<T>() instantiation for TypeLoader public static readonly MethodDesc[] EmptyMethods = new MethodDesc[0]; #pragma warning restore CA1825 private int _hashcode; /// <summary> /// Allows a performance optimization that skips the potentially expensive /// construction of a hash code if a hash code has already been computed elsewhere. /// Use to allow objects to have their hashcode computed /// independently of the allocation of a MethodDesc object /// For instance, compute the hashcode when looking up the object, /// then when creating the object, pass in the hashcode directly. /// The hashcode specified MUST exactly match the algorithm implemented /// on this type normally. /// </summary> protected void SetHashCode(int hashcode) { _hashcode = hashcode; Debug.Assert(hashcode == ComputeHashCode()); } public sealed override int GetHashCode() { if (_hashcode != 0) return _hashcode; return AcquireHashCode(); } private int AcquireHashCode() { _hashcode = ComputeHashCode(); return _hashcode; } /// <summary> /// Compute HashCode. Should only be overriden by a MethodDesc that represents an instantiated method. /// </summary> protected virtual int ComputeHashCode() { return TypeHashingAlgorithms.ComputeMethodHashCode(OwningType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name)); } public override bool Equals(object o) { // Its only valid to compare two MethodDescs in the same context Debug.Assert(o is not MethodDesc || object.ReferenceEquals(((MethodDesc)o).Context, this.Context)); return object.ReferenceEquals(this, o); } /// <summary> /// Gets the type that owns this method. This will be a <see cref="DefType"/> or /// an <see cref="ArrayType"/>. /// </summary> public abstract TypeDesc OwningType { get; } /// <summary> /// Gets the signature of the method. /// </summary> public abstract MethodSignature Signature { get; } /// <summary> /// Gets the generic instantiation information of this method. /// For generic definitions, retrieves the generic parameters of the method. /// For generic instantiation, retrieves the generic arguments of the method. /// </summary> public virtual Instantiation Instantiation { get { return Instantiation.Empty; } } /// <summary> /// Gets a value indicating whether this method has a generic instantiation. /// This will be true for generic method instantiations and generic definitions. /// </summary> public bool HasInstantiation { get { return this.Instantiation.Length != 0; } } /// <summary> /// Gets a value indicating whether this method is an instance constructor. /// </summary> public bool IsConstructor { get { // TODO: Precise check // TODO: Cache? return this.Name == ".ctor"; } } /// <summary> /// Gets a value indicating whether this is a public parameterless instance constructor /// on a non-abstract type. /// </summary> public virtual bool IsDefaultConstructor { get { return OwningType.GetDefaultConstructor() == this; } } /// <summary> /// Gets a value indicating whether this method is a static constructor. /// </summary> public bool IsStaticConstructor { get { return this == this.OwningType.GetStaticConstructor(); } } /// <summary> /// Gets the name of the method as specified in the metadata. /// </summary> public virtual string Name { get { return null; } } /// <summary> /// Gets a value indicating whether the method is virtual. /// </summary> public virtual bool IsVirtual { get { return false; } } /// <summary> /// Gets a value indicating whether this virtual method should not override any /// virtual methods defined in any of the base classes. /// </summary> public virtual bool IsNewSlot { get { return false; } } /// <summary> /// Gets a value indicating whether this virtual method needs to be overriden /// by all non-abstract classes deriving from the method's owning type. /// </summary> public virtual bool IsAbstract { get { return false; } } /// <summary> /// Gets a value indicating that this method cannot be overriden. /// </summary> public virtual bool IsFinal { get { return false; } } public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName); /// <summary> /// Retrieves the uninstantiated form of the method on the method's <see cref="OwningType"/>. /// For generic methods, this strips method instantiation. For non-generic methods, returns 'this'. /// To also strip instantiation of the owning type, use <see cref="GetTypicalMethodDefinition"/>. /// </summary> public virtual MethodDesc GetMethodDefinition() { return this; } /// <summary> /// Gets a value indicating whether this is a method definition. This property /// is true for non-generic methods and for uninstantiated generic methods. /// </summary> public bool IsMethodDefinition { get { return GetMethodDefinition() == this; } } /// <summary> /// Retrieves the generic definition of the method on the generic definition of the owning type. /// To only uninstantiate the method without uninstantiating the owning type, use <see cref="GetMethodDefinition"/>. /// </summary> public virtual MethodDesc GetTypicalMethodDefinition() { return this; } /// <summary> /// Gets a value indicating whether this is a typical definition. This property is true /// if neither the owning type, nor the method are instantiated. /// </summary> public bool IsTypicalMethodDefinition { get { return GetTypicalMethodDefinition() == this; } } /// <summary> /// Gets a value indicating whether this is an uninstantiated generic method. /// </summary> public bool IsGenericMethodDefinition { get { return HasInstantiation && IsMethodDefinition; } } public bool IsFinalizer { get { TypeDesc owningType = OwningType; return (owningType.IsObject && Name == "Finalize") || (owningType.HasFinalizer && owningType.GetFinalizer() == this); } } public virtual MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { Instantiation instantiation = Instantiation; TypeDesc[] clone = null; for (int i = 0; i < instantiation.Length; i++) { TypeDesc uninst = instantiation[i]; TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation); if (inst != uninst) { if (clone == null) { clone = new TypeDesc[instantiation.Length]; for (int j = 0; j < clone.Length; j++) { clone[j] = instantiation[j]; } } clone[i] = inst; } } MethodDesc method = this; TypeDesc owningType = method.OwningType; TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation); if (owningType != instantiatedOwningType) { method = Context.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)instantiatedOwningType); if (clone == null && instantiation.Length != 0) return Context.GetInstantiatedMethod(method, instantiation); } return (clone == null) ? method : Context.GetInstantiatedMethod(method.GetMethodDefinition(), new Instantiation(clone)); } } }
// 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.Runtime.CompilerServices; using Internal.NativeFormat; namespace Internal.TypeSystem { [Flags] public enum MethodSignatureFlags { None = 0x0000, // TODO: Generic, etc. UnmanagedCallingConventionMask = 0x000F, UnmanagedCallingConventionCdecl = 0x0001, UnmanagedCallingConventionStdCall = 0x0002, UnmanagedCallingConventionThisCall = 0x0003, CallingConventionVarargs = 0x0005, UnmanagedCallingConvention = 0x0009, Static = 0x0010, } public enum EmbeddedSignatureDataKind { RequiredCustomModifier = 0, OptionalCustomModifier = 1, ArrayShape = 2 } public struct EmbeddedSignatureData { public string index; public EmbeddedSignatureDataKind kind; public TypeDesc type; } /// <summary> /// Represents the parameter types, the return type, and flags of a method. /// </summary> public sealed partial class MethodSignature : TypeSystemEntity { internal MethodSignatureFlags _flags; internal int _genericParameterCount; internal TypeDesc _returnType; internal TypeDesc[] _parameters; internal EmbeddedSignatureData[] _embeddedSignatureData; // Value of <see cref="EmbeddedSignatureData.index" /> for any custom modifiers on the return type public const string IndexOfCustomModifiersOnReturnType = "0.1.1.1"; // Value of <see cref="EmbeddedSignatureData.index" /> for any custom modifiers on // SomeStruct when SomeStruct *, or SomeStruct & is the type of a parameter or return type // Parameter index 0 represents the return type, and indices 1-n represent the parameters to the signature public static string GetIndexOfCustomModifierOnPointedAtTypeByParameterIndex(int parameterIndex) { return $"0.1.1.2.{(parameterIndex + 1).ToStringInvariant()}.1"; } // Provide a means to create a MethodSignature which ignores EmbeddedSignature data in the MethodSignatures it is compared to public static EmbeddedSignatureData[] EmbeddedSignatureMismatchPermittedFlag = new EmbeddedSignatureData[0]; public MethodSignature(MethodSignatureFlags flags, int genericParameterCount, TypeDesc returnType, TypeDesc[] parameters, EmbeddedSignatureData[] embeddedSignatureData = null) { _flags = flags; _genericParameterCount = genericParameterCount; _returnType = returnType; _parameters = parameters; _embeddedSignatureData = embeddedSignatureData; Debug.Assert(parameters != null, "Parameters must not be null"); } public MethodSignature ApplySubstitution(Instantiation substitution) { if (substitution.IsNull) return this; bool needsNewMethodSignature = false; TypeDesc[] newParameters = _parameters; // Re-use existing array until conflict appears TypeDesc returnTypeNew = _returnType.InstantiateSignature(substitution, default(Instantiation)); if (returnTypeNew != _returnType) { needsNewMethodSignature = true; newParameters = (TypeDesc[])_parameters.Clone(); } for (int i = 0; i < newParameters.Length; i++) { TypeDesc newParameter = newParameters[i].InstantiateSignature(substitution, default(Instantiation)); if (newParameter != newParameters[i]) { if (!needsNewMethodSignature) { needsNewMethodSignature = true; newParameters = (TypeDesc[])_parameters.Clone(); } newParameters[i] = newParameter; } } if (needsNewMethodSignature) { return new MethodSignature(_flags, _genericParameterCount, returnTypeNew, newParameters, _embeddedSignatureData); } else { return this; } } public MethodSignatureFlags Flags { get { return _flags; } } public bool IsStatic { get { return (_flags & MethodSignatureFlags.Static) != 0; } } public int GenericParameterCount { get { return _genericParameterCount; } } public TypeDesc ReturnType { get { return _returnType; } } /// <summary> /// Gets the parameter type at the specified index. /// </summary> [IndexerName("Parameter")] public TypeDesc this[int index] { get { return _parameters[index]; } } /// <summary> /// Gets the number of parameters of this method signature. /// </summary> public int Length { get { return _parameters.Length; } } public bool HasEmbeddedSignatureData { get { return _embeddedSignatureData != null && _embeddedSignatureData.Length != 0; } } public bool EmbeddedSignatureMismatchPermitted { get { return _embeddedSignatureData == EmbeddedSignatureMismatchPermittedFlag; } } public EmbeddedSignatureData[] GetEmbeddedSignatureData() { if ((_embeddedSignatureData == null) || (_embeddedSignatureData.Length == 0)) return null; return (EmbeddedSignatureData[])_embeddedSignatureData.Clone(); } public bool Equals(MethodSignature otherSignature) { return Equals(otherSignature, allowCovariantReturn: false); } public bool EqualsWithCovariantReturnType(MethodSignature otherSignature) { return Equals(otherSignature, allowCovariantReturn: true); } private bool Equals(MethodSignature otherSignature, bool allowCovariantReturn) { // TODO: Generics, etc. if (this._flags != otherSignature._flags) return false; if (this._genericParameterCount != otherSignature._genericParameterCount) return false; if (this._returnType != otherSignature._returnType) { if (!allowCovariantReturn) return false; if (!otherSignature._returnType.IsCompatibleWith(this._returnType)) return false; } if (this._parameters.Length != otherSignature._parameters.Length) return false; for (int i = 0; i < this._parameters.Length; i++) { if (this._parameters[i] != otherSignature._parameters[i]) return false; } if (this._embeddedSignatureData == null && otherSignature._embeddedSignatureData == null) { return true; } // Array methods do not need to have matching details for the array parameters they support if (this.EmbeddedSignatureMismatchPermitted || otherSignature.EmbeddedSignatureMismatchPermitted) { return true; } if (this._embeddedSignatureData != null && otherSignature._embeddedSignatureData != null) { if (this._embeddedSignatureData.Length != otherSignature._embeddedSignatureData.Length) { return false; } for (int i = 0; i < this._embeddedSignatureData.Length; i++) { if (this._embeddedSignatureData[i].index != otherSignature._embeddedSignatureData[i].index) return false; if (this._embeddedSignatureData[i].kind != otherSignature._embeddedSignatureData[i].kind) return false; if (this._embeddedSignatureData[i].type != otherSignature._embeddedSignatureData[i].type) return false; } return true; } return false; } public override bool Equals(object obj) { return obj is MethodSignature && Equals((MethodSignature)obj); } public override int GetHashCode() { return TypeHashingAlgorithms.ComputeMethodSignatureHashCode(_returnType.GetHashCode(), _parameters); } public SignatureEnumerator GetEnumerator() { return new SignatureEnumerator(this); } public override TypeSystemContext Context => _returnType.Context; public struct SignatureEnumerator { private int _index; private MethodSignature _signature; public SignatureEnumerator(MethodSignature signature) { _signature = signature; _index = -1; } public TypeDesc Current => _signature[_index]; public bool MoveNext() { _index++; return _index < _signature.Length; } } } /// <summary> /// Helper structure for building method signatures by cloning an existing method signature. /// </summary> /// <remarks> /// This can potentially avoid array allocation costs for allocating the parameter type list. /// </remarks> public struct MethodSignatureBuilder { private MethodSignature _template; private MethodSignatureFlags _flags; private int _genericParameterCount; private TypeDesc _returnType; private TypeDesc[] _parameters; private EmbeddedSignatureData[] _customModifiers; public MethodSignatureBuilder(MethodSignature template) { _template = template; _flags = template._flags; _genericParameterCount = template._genericParameterCount; _returnType = template._returnType; _parameters = template._parameters; _customModifiers = template._embeddedSignatureData; } public MethodSignatureFlags Flags { set { _flags = value; } } public TypeDesc ReturnType { set { _returnType = value; } } [System.Runtime.CompilerServices.IndexerName("Parameter")] public TypeDesc this[int index] { set { if (_parameters[index] == value) return; if (_template != null && _parameters == _template._parameters) { TypeDesc[] parameters = new TypeDesc[_parameters.Length]; for (int i = 0; i < parameters.Length; i++) parameters[i] = _parameters[i]; _parameters = parameters; } _parameters[index] = value; } } public int Length { set { _parameters = new TypeDesc[value]; _template = null; } } public MethodSignature ToSignature() { if (_template == null || _flags != _template._flags || _genericParameterCount != _template._genericParameterCount || _returnType != _template._returnType || _parameters != _template._parameters) { _template = new MethodSignature(_flags, _genericParameterCount, _returnType, _parameters, _customModifiers); } return _template; } } /// <summary> /// Represents the fundamental base type for all methods within the type system. /// </summary> public abstract partial class MethodDesc : TypeSystemEntity { #pragma warning disable CA1825 // avoid Array.Empty<T>() instantiation for TypeLoader public static readonly MethodDesc[] EmptyMethods = new MethodDesc[0]; #pragma warning restore CA1825 private int _hashcode; /// <summary> /// Allows a performance optimization that skips the potentially expensive /// construction of a hash code if a hash code has already been computed elsewhere. /// Use to allow objects to have their hashcode computed /// independently of the allocation of a MethodDesc object /// For instance, compute the hashcode when looking up the object, /// then when creating the object, pass in the hashcode directly. /// The hashcode specified MUST exactly match the algorithm implemented /// on this type normally. /// </summary> protected void SetHashCode(int hashcode) { _hashcode = hashcode; Debug.Assert(hashcode == ComputeHashCode()); } public sealed override int GetHashCode() { if (_hashcode != 0) return _hashcode; return AcquireHashCode(); } private int AcquireHashCode() { _hashcode = ComputeHashCode(); return _hashcode; } /// <summary> /// Compute HashCode. Should only be overriden by a MethodDesc that represents an instantiated method. /// </summary> protected virtual int ComputeHashCode() { return TypeHashingAlgorithms.ComputeMethodHashCode(OwningType.GetHashCode(), TypeHashingAlgorithms.ComputeNameHashCode(Name)); } public override bool Equals(object o) { // Its only valid to compare two MethodDescs in the same context Debug.Assert(o is not MethodDesc || object.ReferenceEquals(((MethodDesc)o).Context, this.Context)); return object.ReferenceEquals(this, o); } /// <summary> /// Gets the type that owns this method. This will be a <see cref="DefType"/> or /// an <see cref="ArrayType"/>. /// </summary> public abstract TypeDesc OwningType { get; } /// <summary> /// Gets the signature of the method. /// </summary> public abstract MethodSignature Signature { get; } /// <summary> /// Gets the generic instantiation information of this method. /// For generic definitions, retrieves the generic parameters of the method. /// For generic instantiation, retrieves the generic arguments of the method. /// </summary> public virtual Instantiation Instantiation { get { return Instantiation.Empty; } } /// <summary> /// Gets a value indicating whether this method has a generic instantiation. /// This will be true for generic method instantiations and generic definitions. /// </summary> public bool HasInstantiation { get { return this.Instantiation.Length != 0; } } /// <summary> /// Gets a value indicating whether this method is an instance constructor. /// </summary> public bool IsConstructor { get { // TODO: Precise check // TODO: Cache? return this.Name == ".ctor"; } } /// <summary> /// Gets a value indicating whether this is a public parameterless instance constructor /// on a non-abstract type. /// </summary> public virtual bool IsDefaultConstructor { get { return OwningType.GetDefaultConstructor() == this; } } /// <summary> /// Gets a value indicating whether this method is a static constructor. /// </summary> public bool IsStaticConstructor { get { return this == this.OwningType.GetStaticConstructor(); } } /// <summary> /// Gets the name of the method as specified in the metadata. /// </summary> public virtual string Name { get { return null; } } /// <summary> /// Gets a value indicating whether the method is virtual. /// </summary> public virtual bool IsVirtual { get { return false; } } /// <summary> /// Gets a value indicating whether this virtual method should not override any /// virtual methods defined in any of the base classes. /// </summary> public virtual bool IsNewSlot { get { return false; } } /// <summary> /// Gets a value indicating whether this virtual method needs to be overriden /// by all non-abstract classes deriving from the method's owning type. /// </summary> public virtual bool IsAbstract { get { return false; } } /// <summary> /// Gets a value indicating that this method cannot be overriden. /// </summary> public virtual bool IsFinal { get { return false; } } public abstract bool HasCustomAttribute(string attributeNamespace, string attributeName); /// <summary> /// Retrieves the uninstantiated form of the method on the method's <see cref="OwningType"/>. /// For generic methods, this strips method instantiation. For non-generic methods, returns 'this'. /// To also strip instantiation of the owning type, use <see cref="GetTypicalMethodDefinition"/>. /// </summary> public virtual MethodDesc GetMethodDefinition() { return this; } /// <summary> /// Gets a value indicating whether this is a method definition. This property /// is true for non-generic methods and for uninstantiated generic methods. /// </summary> public bool IsMethodDefinition { get { return GetMethodDefinition() == this; } } /// <summary> /// Retrieves the generic definition of the method on the generic definition of the owning type. /// To only uninstantiate the method without uninstantiating the owning type, use <see cref="GetMethodDefinition"/>. /// </summary> public virtual MethodDesc GetTypicalMethodDefinition() { return this; } /// <summary> /// Gets a value indicating whether this is a typical definition. This property is true /// if neither the owning type, nor the method are instantiated. /// </summary> public bool IsTypicalMethodDefinition { get { return GetTypicalMethodDefinition() == this; } } /// <summary> /// Gets a value indicating whether this is an uninstantiated generic method. /// </summary> public bool IsGenericMethodDefinition { get { return HasInstantiation && IsMethodDefinition; } } public bool IsFinalizer { get { TypeDesc owningType = OwningType; return (owningType.IsObject && Name == "Finalize") || (owningType.HasFinalizer && owningType.GetFinalizer() == this); } } public virtual MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { Instantiation instantiation = Instantiation; TypeDesc[] clone = null; for (int i = 0; i < instantiation.Length; i++) { TypeDesc uninst = instantiation[i]; TypeDesc inst = uninst.InstantiateSignature(typeInstantiation, methodInstantiation); if (inst != uninst) { if (clone == null) { clone = new TypeDesc[instantiation.Length]; for (int j = 0; j < clone.Length; j++) { clone[j] = instantiation[j]; } } clone[i] = inst; } } MethodDesc method = this; TypeDesc owningType = method.OwningType; TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation); if (owningType != instantiatedOwningType) { method = Context.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)instantiatedOwningType); if (clone == null && instantiation.Length != 0) return Context.GetInstantiatedMethod(method, instantiation); } return (clone == null) ? method : Context.GetInstantiatedMethod(method.GetMethodDefinition(), new Instantiation(clone)); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs
// 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.Xml.Schema; namespace System.Xml { // Contains information associated with the document type declaration. public class XmlDocumentType : XmlLinkedNode { private readonly string _name; private readonly string? _publicId; private readonly string? _systemId; private readonly string? _internalSubset; private bool _namespaces; private XmlNamedNodeMap? _entities; private XmlNamedNodeMap? _notations; // parsed DTD private SchemaInfo? _schemaInfo; protected internal XmlDocumentType(string name, string? publicId, string? systemId, string? internalSubset, XmlDocument doc) : base(doc) { _name = name; _publicId = publicId; _systemId = systemId; _namespaces = true; _internalSubset = internalSubset; Debug.Assert(doc != null); if (!doc.IsLoading) { doc.IsLoading = true; XmlLoader loader = new XmlLoader(); loader.ParseDocumentType(this); // will edit notation nodes, etc. doc.IsLoading = false; } } // Gets the name of the node. public override string Name { get { return _name; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { get { return _name; } } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.DocumentType; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { Debug.Assert(OwnerDocument != null); return OwnerDocument.CreateDocumentType(_name, _publicId, _systemId, _internalSubset); } // // Microsoft extensions // // Gets a value indicating whether the node is read-only. public override bool IsReadOnly { get { return true; // Make entities and notations readonly } } // Gets the collection of XmlEntity nodes declared in the document type declaration. public XmlNamedNodeMap Entities { get { if (_entities == null) _entities = new XmlNamedNodeMap(this); return _entities; } } // Gets the collection of XmlNotation nodes present in the document type declaration. public XmlNamedNodeMap Notations { get { if (_notations == null) _notations = new XmlNamedNodeMap(this); return _notations; } } // // DOM Level 2 // // Gets the value of the public identifier on the DOCTYPE declaration. public string? PublicId { get { return _publicId; } } // Gets the value of // the system identifier on the DOCTYPE declaration. public string? SystemId { get { return _systemId; } } // Gets the entire value of the DTD internal subset // on the DOCTYPE declaration. public string? InternalSubset { get { return _internalSubset; } } internal bool ParseWithNamespaces { get { return _namespaces; } set { _namespaces = value; } } // Saves the node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { w.WriteDocType(_name, _publicId, _systemId, _internalSubset); } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { // Intentionally do nothing } internal SchemaInfo? DtdSchemaInfo { get { return _schemaInfo; } set { _schemaInfo = value; } } } }
// 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.Xml.Schema; namespace System.Xml { // Contains information associated with the document type declaration. public class XmlDocumentType : XmlLinkedNode { private readonly string _name; private readonly string? _publicId; private readonly string? _systemId; private readonly string? _internalSubset; private bool _namespaces; private XmlNamedNodeMap? _entities; private XmlNamedNodeMap? _notations; // parsed DTD private SchemaInfo? _schemaInfo; protected internal XmlDocumentType(string name, string? publicId, string? systemId, string? internalSubset, XmlDocument doc) : base(doc) { _name = name; _publicId = publicId; _systemId = systemId; _namespaces = true; _internalSubset = internalSubset; Debug.Assert(doc != null); if (!doc.IsLoading) { doc.IsLoading = true; XmlLoader loader = new XmlLoader(); loader.ParseDocumentType(this); // will edit notation nodes, etc. doc.IsLoading = false; } } // Gets the name of the node. public override string Name { get { return _name; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { get { return _name; } } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.DocumentType; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { Debug.Assert(OwnerDocument != null); return OwnerDocument.CreateDocumentType(_name, _publicId, _systemId, _internalSubset); } // // Microsoft extensions // // Gets a value indicating whether the node is read-only. public override bool IsReadOnly { get { return true; // Make entities and notations readonly } } // Gets the collection of XmlEntity nodes declared in the document type declaration. public XmlNamedNodeMap Entities { get { if (_entities == null) _entities = new XmlNamedNodeMap(this); return _entities; } } // Gets the collection of XmlNotation nodes present in the document type declaration. public XmlNamedNodeMap Notations { get { if (_notations == null) _notations = new XmlNamedNodeMap(this); return _notations; } } // // DOM Level 2 // // Gets the value of the public identifier on the DOCTYPE declaration. public string? PublicId { get { return _publicId; } } // Gets the value of // the system identifier on the DOCTYPE declaration. public string? SystemId { get { return _systemId; } } // Gets the entire value of the DTD internal subset // on the DOCTYPE declaration. public string? InternalSubset { get { return _internalSubset; } } internal bool ParseWithNamespaces { get { return _namespaces; } set { _namespaces = value; } } // Saves the node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { w.WriteDocType(_name, _publicId, _systemId, _internalSubset); } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { // Intentionally do nothing } internal SchemaInfo? DtdSchemaInfo { get { return _schemaInfo; } set { _schemaInfo = value; } } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComInvokeAction.cs
// 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.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Linq.Expressions; using System.Runtime.CompilerServices; namespace Microsoft.CSharp.RuntimeBinder.ComInterop { /// <summary> /// Invokes the object. If it falls back, just produce an error. /// </summary> internal sealed class ComInvokeAction : InvokeBinder { [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal ComInvokeAction(CallInfo callInfo) : base(callInfo) { } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { if (ComBinder.TryBindInvoke(this, target, args, out DynamicMetaObject res)) { return res; } return errorSuggestion ?? new DynamicMetaObject( Expression.Throw( Expression.New( typeof(NotSupportedException).GetConstructor(new[] { typeof(string) }), Expression.Constant(SR.COMCannotPerformCall) ), typeof(object) ), target.Restrictions.Merge(BindingRestrictions.Combine(args)) ); } } /// <summary> /// Splats the arguments to another nested dynamic site, which does the /// real invocation of the IDynamicMetaObjectProvider. /// </summary> internal sealed class SplatInvokeBinder : CallSiteBinder { private static readonly SplatInvokeBinder s_instance = new SplatInvokeBinder(); internal static SplatInvokeBinder Instance { [RequiresUnreferencedCode(Binder.TrimmerWarning)] get => s_instance; } private SplatInvokeBinder() { } // Just splat the args and dispatch through a nested site [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This whole class is unsafe. The only entry-point to this class is through Instance property which is marked as unsafe.")] public override Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel) { Debug.Assert(args.Length == 2); int count = ((object[])args[1]).Length; ParameterExpression array = parameters[1]; var nestedArgs = new ReadOnlyCollectionBuilder<Expression>(count + 1); var delegateArgs = new Type[count + 3]; // args + target + returnType + CallSite nestedArgs.Add(parameters[0]); delegateArgs[0] = typeof(CallSite); delegateArgs[1] = typeof(object); for (int i = 0; i < count; i++) { nestedArgs.Add(Expression.ArrayAccess(array, Expression.Constant(i))); delegateArgs[i + 2] = typeof(object).MakeByRefType(); } delegateArgs[delegateArgs.Length - 1] = typeof(object); return Expression.IfThen( Expression.Equal(Expression.ArrayLength(array), Expression.Constant(count)), Expression.Return( returnLabel, Expression.MakeDynamic( Expression.GetDelegateType(delegateArgs), new ComInvokeAction(new CallInfo(count)), nestedArgs ) ) ); } } }
// 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.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Linq.Expressions; using System.Runtime.CompilerServices; namespace Microsoft.CSharp.RuntimeBinder.ComInterop { /// <summary> /// Invokes the object. If it falls back, just produce an error. /// </summary> internal sealed class ComInvokeAction : InvokeBinder { [RequiresUnreferencedCode(Binder.TrimmerWarning)] internal ComInvokeAction(CallInfo callInfo) : base(callInfo) { } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This whole class is unsafe. Constructors are marked as such.")] public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { if (ComBinder.TryBindInvoke(this, target, args, out DynamicMetaObject res)) { return res; } return errorSuggestion ?? new DynamicMetaObject( Expression.Throw( Expression.New( typeof(NotSupportedException).GetConstructor(new[] { typeof(string) }), Expression.Constant(SR.COMCannotPerformCall) ), typeof(object) ), target.Restrictions.Merge(BindingRestrictions.Combine(args)) ); } } /// <summary> /// Splats the arguments to another nested dynamic site, which does the /// real invocation of the IDynamicMetaObjectProvider. /// </summary> internal sealed class SplatInvokeBinder : CallSiteBinder { private static readonly SplatInvokeBinder s_instance = new SplatInvokeBinder(); internal static SplatInvokeBinder Instance { [RequiresUnreferencedCode(Binder.TrimmerWarning)] get => s_instance; } private SplatInvokeBinder() { } // Just splat the args and dispatch through a nested site [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "This whole class is unsafe. The only entry-point to this class is through Instance property which is marked as unsafe.")] public override Expression Bind(object[] args, ReadOnlyCollection<ParameterExpression> parameters, LabelTarget returnLabel) { Debug.Assert(args.Length == 2); int count = ((object[])args[1]).Length; ParameterExpression array = parameters[1]; var nestedArgs = new ReadOnlyCollectionBuilder<Expression>(count + 1); var delegateArgs = new Type[count + 3]; // args + target + returnType + CallSite nestedArgs.Add(parameters[0]); delegateArgs[0] = typeof(CallSite); delegateArgs[1] = typeof(object); for (int i = 0; i < count; i++) { nestedArgs.Add(Expression.ArrayAccess(array, Expression.Constant(i))); delegateArgs[i + 2] = typeof(object).MakeByRefType(); } delegateArgs[delegateArgs.Length - 1] = typeof(object); return Expression.IfThen( Expression.Equal(Expression.ArrayLength(array), Expression.Constant(count)), Expression.Return( returnLabel, Expression.MakeDynamic( Expression.GetDelegateType(delegateArgs), new ComInvokeAction(new CallInfo(count)), nestedArgs ) ) ); } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/InsertSelectedScalar.Vector128.UInt32.3.Vector64.UInt32.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1() { var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector64<UInt32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); return testStruct; } public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1 testClass) { var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 3, _fld3, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt32>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)pFld1), 3, AdvSimd.LoadVector64((UInt32*)pFld2), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte ElementIndex1 = 3; private static readonly byte ElementIndex2 = 1; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data3 = new UInt32[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector64<UInt32> _clsVar3; private Vector128<UInt32> _fld1; private Vector64<UInt32> _fld3; private DataTable _dataTable; static InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); } public InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data3, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.InsertSelectedScalar( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), 3, Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), 3, AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<UInt32>), typeof(byte), typeof(Vector64<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), ElementIndex1, Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<UInt32>), typeof(byte), typeof(Vector64<UInt32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), ElementIndex1, AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr)), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar( _clsVar1, 3, _clsVar3, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt32>* pClsVar3 = &_clsVar3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), 3, AdvSimd.LoadVector64((UInt32*)(pClsVar3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 3, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr)); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 3, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 3, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector64<UInt32>* pFld2 = &test._fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)pFld1), 3, AdvSimd.LoadVector64((UInt32*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 3, _fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt32>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)pFld1), 3, AdvSimd.LoadVector64((UInt32*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 3, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), 3, AdvSimd.LoadVector64((UInt32*)(&test._fld3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector64<UInt32> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray3 = new UInt32[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray3 = new UInt32[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<UInt32>(Vector128<UInt32>, {3}, Vector64<UInt32>, {1}): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1() { var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray3, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<UInt32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt32> _fld1; public Vector64<UInt32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref testStruct._fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); return testStruct; } public void RunStructFldScenario(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1 testClass) { var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 3, _fld3, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt32>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)pFld1), 3, AdvSimd.LoadVector64((UInt32*)pFld2), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly byte ElementIndex1 = 3; private static readonly byte ElementIndex2 = 1; private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data3 = new UInt32[Op3ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector64<UInt32> _clsVar3; private Vector128<UInt32> _fld1; private Vector64<UInt32> _fld3; private DataTable _dataTable; static InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _clsVar3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); } public InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt32>, byte>(ref _fld3), ref Unsafe.As<UInt32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data3, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.Arm64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Arm64.InsertSelectedScalar( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), 3, Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), 3, AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<UInt32>), typeof(byte), typeof(Vector64<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), ElementIndex1, Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.InsertSelectedScalar), new Type[] { typeof(Vector128<UInt32>), typeof(byte), typeof(Vector64<UInt32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), ElementIndex1, AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr)), ElementIndex2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar( _clsVar1, 3, _clsVar3, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector64<UInt32>* pClsVar3 = &_clsVar3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)(pClsVar1)), 3, AdvSimd.LoadVector64((UInt32*)(pClsVar3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var op3 = Unsafe.Read<Vector64<UInt32>>(_dataTable.inArray3Ptr); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 3, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var op3 = AdvSimd.LoadVector64((UInt32*)(_dataTable.inArray3Ptr)); var result = AdvSimd.Arm64.InsertSelectedScalar(op1, 3, op3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 3, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new InsertSelectedScalarTest__InsertSelectedScalar_Vector128_UInt32_3_Vector64_UInt32_1(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector64<UInt32>* pFld2 = &test._fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)pFld1), 3, AdvSimd.LoadVector64((UInt32*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.InsertSelectedScalar(_fld1, 3, _fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector64<UInt32>* pFld2 = &_fld3) { var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)pFld1), 3, AdvSimd.LoadVector64((UInt32*)pFld2), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar(test._fld1, 3, test._fld3, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.InsertSelectedScalar( AdvSimd.LoadVector128((UInt32*)(&test._fld1)), 3, AdvSimd.LoadVector64((UInt32*)(&test._fld3)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> op1, Vector64<UInt32> op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray3 = new UInt32[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op3, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray3 = new UInt32[Op3ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray3, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] thirdOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.Insert(firstOp, ElementIndex1, thirdOp[ElementIndex2], i) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.InsertSelectedScalar)}<UInt32>(Vector128<UInt32>, {3}, Vector64<UInt32>, {1}): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs
// 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; namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Xml; using System.Linq; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Security; using System.Diagnostics.CodeAnalysis; // The interface is a perf optimization. // Only KeyValuePairAdapter should implement the interface. internal interface IKeyValuePairAdapter { } //Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved [DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")] internal sealed class KeyValuePairAdapter<K, T> : IKeyValuePairAdapter { private K _kvpKey; private T _kvpValue; public KeyValuePairAdapter(KeyValuePair<K, T> kvPair) { _kvpKey = kvPair.Key; _kvpValue = kvPair.Value; } [DataMember(Name = "key")] public K Key { get { return _kvpKey; } set { _kvpKey = value; } } [DataMember(Name = "value")] public T Value { get { return _kvpValue; } set { _kvpValue = value; } } internal KeyValuePair<K, T> GetKeyValuePair() { return new KeyValuePair<K, T>(_kvpKey, _kvpValue); } internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair) { return new KeyValuePairAdapter<K, T>(kvPair); } } internal interface IKeyValue { object? Key { get; set; } object? Value { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")] internal struct KeyValue<K, V> : IKeyValue { private K _key; private V _value; internal KeyValue(K key, V value) { _key = key; _value = value; } [DataMember(IsRequired = true)] public K Key { get { return _key; } set { _key = value; } } [DataMember(IsRequired = true)] public V Value { get { return _value; } set { _value = value; } } object? IKeyValue.Key { get { return _key; } set { _key = (K)value!; } } object? IKeyValue.Value { get { return _value; } set { _value = (V)value!; } } } internal enum CollectionKind : byte { None, GenericDictionary, Dictionary, GenericList, GenericCollection, List, GenericEnumerable, Collection, Enumerable, Array, } internal sealed class CollectionDataContract : DataContract { private XmlDictionaryString _collectionItemName; private XmlDictionaryString? _childElementNamespace; private DataContract? _itemContract; private CollectionDataContractCriticalHelper _helper; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type)) { InitCollectionDataContract(this); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor, bool isConstructorCheckRequired) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [MemberNotNull(nameof(_helper))] [MemberNotNull(nameof(_collectionItemName))] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void InitCollectionDataContract(DataContract? sharedTypeContract) { _helper = (base.Helper as CollectionDataContractCriticalHelper)!; _collectionItemName = _helper.CollectionItemName; if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary) { _itemContract = _helper.ItemContract; } _helper.SharedTypeContract = sharedTypeContract; } private static Type[] KnownInterfaces { get { return CollectionDataContractCriticalHelper.KnownInterfaces; } } internal CollectionKind Kind { get { return _helper.Kind; } } public Type ItemType { get { return _helper.ItemType; } set { _helper.ItemType = value; } } public DataContract ItemContract { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { return _itemContract ?? _helper.ItemContract; } set { _itemContract = value; _helper.ItemContract = value; } } internal DataContract? SharedTypeContract { get { return _helper.SharedTypeContract; } } public string ItemName { get { return _helper.ItemName; } set { _helper.ItemName = value; } } public XmlDictionaryString CollectionItemName { get { return _collectionItemName; } set { _collectionItemName = value; } } public string? KeyName { get { return _helper.KeyName; } set { _helper.KeyName = value; } } public string? ValueName { get { return _helper.ValueName; } set { _helper.ValueName = value; } } internal bool IsDictionary { get { return KeyName != null; } } public XmlDictionaryString? ChildElementNamespace { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_childElementNamespace == null) { lock (this) { if (_childElementNamespace == null) { if (_helper.ChildElementNamespace == null && !IsDictionary) { XmlDictionaryString? tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); Interlocked.MemoryBarrier(); _helper.ChildElementNamespace = tempChildElementNamespace; } _childElementNamespace = _helper.ChildElementNamespace; } } } return _childElementNamespace; } } internal bool IsItemTypeNullable { get { return _helper.IsItemTypeNullable; } set { _helper.IsItemTypeNullable = value; } } internal bool IsConstructorCheckRequired { get { return _helper.IsConstructorCheckRequired; } set { _helper.IsConstructorCheckRequired = value; } } internal MethodInfo? GetEnumeratorMethod { get { return _helper.GetEnumeratorMethod; } } internal MethodInfo? AddMethod { get { return _helper.AddMethod; } } internal ConstructorInfo? Constructor { get { return _helper.Constructor; } } public override DataContractDictionary? KnownDataContracts { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { return _helper.KnownDataContracts; } set { _helper.KnownDataContracts = value; } } internal string? InvalidCollectionInSharedContractMessage { get { return _helper.InvalidCollectionInSharedContractMessage; } } internal string? DeserializationExceptionMessage { get { return _helper.DeserializationExceptionMessage; } } internal bool IsReadOnlyContract { get { return DeserializationExceptionMessage != null; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private XmlFormatCollectionWriterDelegate CreateXmlFormatWriterDelegate() { return new XmlFormatWriterGenerator().GenerateCollectionWriter(this); } internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_helper.XmlFormatWriterDelegate == null) { lock (this) { if (_helper.XmlFormatWriterDelegate == null) { XmlFormatCollectionWriterDelegate tempDelegate = CreateXmlFormatWriterDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatWriterDelegate = tempDelegate; } } } return _helper.XmlFormatWriterDelegate; } set { } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private XmlFormatCollectionReaderDelegate CreateXmlFormatReaderDelegate() { return new XmlFormatReaderGenerator().GenerateCollectionReader(this); } internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_helper.XmlFormatReaderDelegate == null) { lock (this) { if (_helper.XmlFormatReaderDelegate == null) { if (IsReadOnlyContract) { ThrowInvalidDataContractException(_helper.DeserializationExceptionMessage, type: null); } XmlFormatCollectionReaderDelegate tempDelegate = CreateXmlFormatReaderDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatReaderDelegate = tempDelegate; } } } return _helper.XmlFormatReaderDelegate; } set { } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private XmlFormatGetOnlyCollectionReaderDelegate CreateXmlFormatGetOnlyCollectionReaderDelegate() { return new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this); } internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { lock (this) { if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { if (UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType)))); } if (IsReadOnlyContract) { ThrowInvalidDataContractException(_helper.DeserializationExceptionMessage, type: null); } if (Kind != CollectionKind.Array && AddMethod == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType)))); } XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = CreateXmlFormatGetOnlyCollectionReaderDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate; } } } return _helper.XmlFormatGetOnlyCollectionReaderDelegate; } set { } } internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { _helper.IncrementCollectionCount(xmlWriter, obj, context); } internal IEnumerator GetEnumeratorForCollection(object obj) { return _helper.GetEnumeratorForCollection(obj); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal Type GetCollectionElementType() { return _helper.GetCollectionElementType(); } private sealed class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private static Type[]? s_knownInterfaces; private Type _itemType = null!; // _itemType is always set except for the "invalid" CollectionDataContract private bool _isItemTypeNullable; private CollectionKind _kind; private readonly MethodInfo? _getEnumeratorMethod; private readonly MethodInfo? _addMethod; private readonly ConstructorInfo? _constructor; private readonly string? _deserializationExceptionMessage; private DataContract? _itemContract; private DataContract? _sharedTypeContract; private DataContractDictionary? _knownDataContracts; private bool _isKnownTypeAttributeChecked; private string _itemName = null!; // _itemName is always set except for the "invalid" CollectionDataContract private bool _itemNameSetExplicit; private XmlDictionaryString _collectionItemName = null!; // _itemName is always set except for the "invalid" CollectionDataContract private string? _keyName; private string? _valueName; private XmlDictionaryString? _childElementNamespace; private readonly string? _invalidCollectionInSharedContractMessage; private XmlFormatCollectionReaderDelegate? _xmlFormatReaderDelegate; private XmlFormatGetOnlyCollectionReaderDelegate? _xmlFormatGetOnlyCollectionReaderDelegate; private XmlFormatCollectionWriterDelegate? _xmlFormatWriterDelegate; private bool _isConstructorCheckRequired; internal static Type[] KnownInterfaces { get { if (s_knownInterfaces == null) { // Listed in priority order s_knownInterfaces = new Type[] { Globals.TypeOfIDictionaryGeneric, Globals.TypeOfIDictionary, Globals.TypeOfIListGeneric, Globals.TypeOfICollectionGeneric, Globals.TypeOfIList, Globals.TypeOfIEnumerableGeneric, Globals.TypeOfICollection, Globals.TypeOfIEnumerable }; } return s_knownInterfaces; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAttribute? collectionContractAttribute) { _kind = kind; if (itemType != null) { _itemType = itemType; _isItemTypeNullable = DataContract.IsTypeNullable(itemType); bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary); string? itemName = null, keyName = null, valueName = null; if (collectionContractAttribute != null) { if (collectionContractAttribute.IsItemNameSetExplicitly) { if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType)))); itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName); _itemNameSetExplicit = true; } if (collectionContractAttribute.IsKeyNameSetExplicitly) { if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName))); keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName); } if (collectionContractAttribute.IsValueNameSetExplicitly) { if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName))); valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName); } } XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3); this.Name = dictionary.Add(this.StableName.Name); this.Namespace = dictionary.Add(this.StableName.Namespace); _itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name; _collectionItemName = dictionary.Add(_itemName); if (isDictionary) { _keyName = keyName ?? Globals.KeyLocalName; _valueName = valueName ?? Globals.ValueLocalName; } } if (collectionContractAttribute != null) { this.IsReference = collectionContractAttribute.IsReference; } } // array [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type) : base(type) { if (type == Globals.TypeOfArray) type = Globals.TypeOfObjectArray; if (type.GetArrayRank() > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SupportForMultidimensionalArraysNotPresent)); this.StableName = DataContract.GetStableName(type); Init(CollectionKind.Array, type.GetElementType(), null); } // read-only collection [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage) : base(type) { if (getEnumeratorMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, GetClrTypeFullName(type)))); if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, GetClrTypeFullName(type)))); CollectionDataContractAttribute? collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); _getEnumeratorMethod = getEnumeratorMethod; _deserializationExceptionMessage = deserializationExceptionMessage; } // collection [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor) : base(type) { if (getEnumeratorMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type)))); if (addMethod == null && !type.IsInterface) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type)))); if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type)))); CollectionDataContractAttribute? collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); _getEnumeratorMethod = getEnumeratorMethod; _addMethod = addMethod; _constructor = constructor; } // collection [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor, bool isConstructorCheckRequired) : this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor) { _isConstructorCheckRequired = isConstructorCheckRequired; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type, string invalidCollectionInSharedContractMessage) : base(type) { Init(CollectionKind.Collection, null /*itemType*/, null); _invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage; } internal CollectionKind Kind { get { return _kind; } } internal Type ItemType { get { return _itemType; } set { _itemType = value; } } internal DataContract ItemContract { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_itemContract == null) { if (IsDictionary) { if (string.CompareOrdinal(KeyName, ValueName) == 0) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName), UnderlyingType); } Debug.Assert(KeyName != null); Debug.Assert(ValueName != null); _itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName }); // Ensure that DataContract gets added to the static DataContract cache for dictionary items DataContract.GetDataContract(ItemType); } else { _itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType); if (_itemContract == null) { _itemContract = DataContract.GetDataContract(ItemType); } } } return _itemContract; } set { _itemContract = value; } } internal DataContract? SharedTypeContract { get { return _sharedTypeContract; } set { _sharedTypeContract = value; } } internal string ItemName { get { return _itemName; } set { _itemName = value; } } internal bool IsConstructorCheckRequired { get { return _isConstructorCheckRequired; } set { _isConstructorCheckRequired = value; } } public XmlDictionaryString CollectionItemName { get { return _collectionItemName; } } internal string? KeyName { get { return _keyName; } set { _keyName = value; } } internal string? ValueName { get { return _valueName; } set { _valueName = value; } } internal bool IsDictionary => KeyName != null; public string? DeserializationExceptionMessage => _deserializationExceptionMessage; public XmlDictionaryString? ChildElementNamespace { get { return _childElementNamespace; } set { _childElementNamespace = value; } } internal bool IsItemTypeNullable { get { return _isItemTypeNullable; } set { _isItemTypeNullable = value; } } internal MethodInfo? GetEnumeratorMethod => _getEnumeratorMethod; internal MethodInfo? AddMethod => _addMethod; internal ConstructorInfo? Constructor => _constructor; internal override DataContractDictionary? KnownDataContracts { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } set { _knownDataContracts = value; } } internal string? InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage; internal bool ItemNameSetExplicit => _itemNameSetExplicit; internal XmlFormatCollectionWriterDelegate? XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } internal XmlFormatCollectionReaderDelegate? XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } internal XmlFormatGetOnlyCollectionReaderDelegate? XmlFormatGetOnlyCollectionReaderDelegate { get { return _xmlFormatGetOnlyCollectionReaderDelegate; } set { _xmlFormatGetOnlyCollectionReaderDelegate = value; } } private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context); private IncrementCollectionCountDelegate? _incrementCollectionCountDelegate; private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { } internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (_incrementCollectionCountDelegate == null) { switch (Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: { _incrementCollectionCountDelegate = (x, o, c) => { c.IncrementCollectionCount(x, (ICollection)o); }; } break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: { var buildIncrementCollectionCountDelegate = GetBuildIncrementCollectionCountGenericDelegate(ItemType); _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>())!; } break; case CollectionKind.GenericDictionary: { var buildIncrementCollectionCountDelegate = GetBuildIncrementCollectionCountGenericDelegate(typeof(KeyValuePair<,>).MakeGenericType(ItemType.GetGenericArguments())); _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>())!; } break; default: // Do nothing. _incrementCollectionCountDelegate = DummyIncrementCollectionCount; break; } } _incrementCollectionCountDelegate(xmlWriter, obj, context); [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "The call to MakeGenericMethod is safe due to the fact that CollectionDataContractCriticalHelper.BuildIncrementCollectionCountDelegate<T> is not annotated.")] static MethodInfo GetBuildIncrementCollectionCountGenericDelegate(Type type) => BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(type); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "The call to MakeGenericMethod is safe due to the fact that CollectionDataContractCriticalHelper.BuildIncrementCollectionCountDelegate<T> is not annotated.")] private MethodInfo GetBuildIncrementCollectionCountGenericDelegate(Type type) => BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(type); private static MethodInfo? s_buildIncrementCollectionCountDelegateMethod; private static MethodInfo BuildIncrementCollectionCountDelegateMethod { get { if (s_buildIncrementCollectionCountDelegateMethod == null) { s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!; } return s_buildIncrementCollectionCountDelegateMethod; } } private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>() { return (xmlwriter, obj, context) => { context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj); }; } private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator); private CreateGenericDictionaryEnumeratorDelegate? _createGenericDictionaryEnumeratorDelegate; internal IEnumerator GetEnumeratorForCollection(object obj) { IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator(); if (Kind == CollectionKind.GenericDictionary) { if (_createGenericDictionaryEnumeratorDelegate == null) { var keyValueTypes = ItemType.GetGenericArguments(); MethodInfo buildCreateGenericDictionaryEnumerator = GetBuildCreateGenericDictionaryEnumeratorGenericMethod(keyValueTypes); _createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>())!; } enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator); } else if (Kind == CollectionKind.Dictionary) { enumerator = new DictionaryEnumerator(((IDictionary)obj).GetEnumerator()); } return enumerator; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "The call to MakeGenericMethod is safe due to the fact that CollectionDataContractCriticalHelper.BuildCreateGenericDictionaryEnumerator<K,V> is not annotated.")] static MethodInfo GetBuildCreateGenericDictionaryEnumeratorGenericMethod(Type[] keyValueTypes) => GetBuildCreateGenericDictionaryEnumeratorMethodInfo.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] 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; if (Kind == CollectionKind.GenericDictionary) { Type[] keyValueTypes = ItemType.GetGenericArguments(); enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes); } else if (Kind == CollectionKind.Dictionary) { enumeratorType = Globals.TypeOfDictionaryEnumerator; } else { enumeratorType = GetEnumeratorMethod.ReturnType; } MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Type.EmptyTypes); if (getCurrentMethod == null) { if (enumeratorType.IsInterface) { getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; } else { Type ienumeratorInterface = Globals.TypeOfIEnumerator; if (Kind == CollectionKind.GenericDictionary || Kind == CollectionKind.GenericCollection || Kind == CollectionKind.GenericEnumerable) { Type[] interfaceTypes = enumeratorType.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && interfaceType.GetGenericArguments()[0] == ItemType) { ienumeratorInterface = interfaceType; break; } } } getCurrentMethod = GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } Type elementType = getCurrentMethod.ReturnType; return elementType; } private static MethodInfo? s_buildCreateGenericDictionaryEnumerator; private static MethodInfo GetBuildCreateGenericDictionaryEnumeratorMethodInfo { get { if (s_buildCreateGenericDictionaryEnumerator == null) { s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!; } return s_buildCreateGenericDictionaryEnumerator; } } private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>() { return (enumerator) => { return new GenericDictionaryEnumerator<K, V>((IEnumerator<KeyValuePair<K, V>>)enumerator); }; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private DataContract? GetSharedTypeContract(Type type) { if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) { return this; } if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return new ClassDataContract(type); } return null; } internal static bool IsCollectionInterface(Type type) { if (type.IsGenericType) type = type.GetGenericTypeDefinition(); return ((IList<Type>)KnownInterfaces).Contains(type); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsCollection(Type type) { return IsCollection(type, out _); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsCollection(Type type, [NotNullWhen(true)] out Type? itemType) { return IsCollectionHelper(type, out itemType, true /*constructorRequired*/); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsCollection(Type type, bool constructorRequired) { return IsCollectionHelper(type, out _, constructorRequired); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool IsCollectionHelper(Type type, [NotNullWhen(true)] out Type? itemType, bool constructorRequired) { if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null) { itemType = type.GetElementType()!; return true; } return IsCollectionOrTryCreate(type, tryCreate: false, out _, out itemType, constructorRequired); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool TryCreate(Type type, [NotNullWhen(true)] out DataContract? dataContract) { return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: true); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool CreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: false); } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool TryCreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract == null) { if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: false); } } else { if (dataContract is CollectionDataContract) { return true; } else { dataContract = null; return false; } } } // Once https://github.com/mono/linker/issues/1731 is fixed we can remove the suppression from here as it won't be needed any longer. [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:GetMethod", Justification = "The DynamicallyAccessedMembers declarations will ensure the interface methods will be preserved.")] internal static MethodInfo? GetTargetMethodWithName(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type interfaceType) { Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); return t?.GetMethod(name); } private static bool IsArraySegment(Type t) { return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract? dataContract, out Type itemType, bool constructorRequired) { dataContract = null; itemType = Globals.TypeOfObject; if (DataContract.GetBuiltInDataContract(type) != null) { return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/, SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract); } MethodInfo? addMethod, getEnumeratorMethod; bool hasCollectionDataContract = IsCollectionDataContract(type); bool isReadOnlyContract = false; string? deserializationExceptionMessage = null; Type? baseType = type.BaseType; bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false; // Avoid creating an invalid collection contract for Serializable types since we can create a ClassDataContract instead bool createContractWithException = isBaseTypeCollection && !type.IsSerializable; if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeCannotHaveDataContract, null, ref dataContract); } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type)) { return false; } if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } if (type.IsInterface) { Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { addMethod = null; if (type.IsGenericType) { Type[] genericArgs = type.GetGenericArguments(); if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric) { itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs); addMethod = type.GetMethod(Globals.AddMethodName); getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName)!; } else { itemType = genericArgs[0]; if (interfaceTypeToCheck == Globals.TypeOfICollectionGeneric || interfaceTypeToCheck == Globals.TypeOfIListGeneric) { addMethod = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType).GetMethod(Globals.AddMethodName); } getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName)!; } } else { if (interfaceTypeToCheck == Globals.TypeOfIDictionary) { itemType = typeof(KeyValue<object, object>); addMethod = type.GetMethod(Globals.AddMethodName); } else { itemType = Globals.TypeOfObject; // IList has AddMethod if (interfaceTypeToCheck == Globals.TypeOfIList) { addMethod = type.GetMethod(Globals.AddMethodName); } } getEnumeratorMethod = typeof(IEnumerable).GetMethod(Globals.GetEnumeratorMethodName)!; } if (tryCreate) dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/); return true; } } } ConstructorInfo? defaultCtor = null; if (!type.IsValueType) { defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.EmptyTypes); if (defaultCtor == null && constructorRequired) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. // Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons. // DataContract types and POCO types cannot be collection types, so they don't need to be factored in if (type.IsSerializable) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract); } else { isReadOnlyContract = true; GetReadOnlyCollectionExceptionMessages(type, SR.CollectionTypeDoesNotHaveDefaultCtor, null, out deserializationExceptionMessage); } } } Type? knownInterfaceType = null; CollectionKind kind = CollectionKind.None; bool multipleDefinitions = false; Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { CollectionKind currentKind = (CollectionKind)(i + 1); if (kind == CollectionKind.None || currentKind < kind) { kind = currentKind; knownInterfaceType = interfaceType; multipleDefinitions = false; } else if ((kind & currentKind) == currentKind) multipleDefinitions = true; break; } } } if (kind == CollectionKind.None) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } Debug.Assert(knownInterfaceType != null); if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable) { if (multipleDefinitions) knownInterfaceType = Globals.TypeOfIEnumerable; itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject; GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType }, false /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); Debug.Assert(getEnumeratorMethod != null); if (addMethod == null) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. // Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons. // DataContract types and POCO types cannot be collection types, so they don't need to be factored in. if (type.IsSerializable) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract); } else { isReadOnlyContract = true; GetReadOnlyCollectionExceptionMessages(type, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), out deserializationExceptionMessage); } } if (tryCreate) { dataContract = isReadOnlyContract ? new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) : new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } } else { if (multipleDefinitions) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract); } Type[]? addMethodTypeArray = null; switch (kind) { case CollectionKind.GenericDictionary: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition || (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter); itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.Dictionary: addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); itemType = addMethodTypeArray[0]; break; case CollectionKind.List: itemType = Globals.TypeOfObject; addMethodTypeArray = new Type[] { itemType }; break; } if (tryCreate) { Debug.Assert(addMethodTypeArray != null); GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray, true /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); Debug.Assert(getEnumeratorMethod != null); dataContract = isReadOnlyContract ? new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) : new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } } return true; } internal static bool IsCollectionDataContract(Type type) { return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string? param, ref DataContract? dataContract) { if (hasCollectionDataContract) { if (tryCreate) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param))); return true; } if (createContractWithException) { if (tryCreate) dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param)); return true; } return false; } private static void GetReadOnlyCollectionExceptionMessages(Type type, string message, string? param, out string deserializationExceptionMessage) { deserializationExceptionMessage = GetInvalidCollectionMessage(message, SR.Format(SR.ReadOnlyCollectionDeserialization, GetClrTypeFullName(type)), param); } private static string GetInvalidCollectionMessage(string message, string nestedMessage, string? param) { return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param); } // Once https://github.com/mono/linker/issues/1731 is fixed we can remove the suppression from here as it won't be needed any longer. [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:GetMethod", Justification = "The DynamicallyAccessedMembers declarations will ensure the interface methods will be preserved.")] private static void FindCollectionMethodsOnInterface( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type interfaceType, ref MethodInfo? addMethod, ref MethodInfo? getEnumeratorMethod) { Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); if (t != null) { addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod; getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static void GetCollectionMethods( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo? getEnumeratorMethod, out MethodInfo? addMethod) { addMethod = getEnumeratorMethod = null; if (addMethodOnInterface) { addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, addMethodTypeArray); if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0]) { FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { Type[] parentInterfaceTypes = interfaceType.GetInterfaces(); // The for loop below depeneds on the order for the items in parentInterfaceTypes, which // doesnt' seem right. But it's the behavior of DCS on the full framework. // Sorting the array to make sure the behavior is consistent with Desktop's. Array.Sort(parentInterfaceTypes, (x, y) => string.Compare(x.FullName, y.FullName)); foreach (Type parentInterfaceType in parentInterfaceTypes) { if (IsKnownInterface(parentInterfaceType)) { FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { break; } } } } } } else { // GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, addMethodTypeArray); } if (getEnumeratorMethod == null) { getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Type.EmptyTypes); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { Type? ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); if (ienumerableInterface == null) ienumerableInterface = Globals.TypeOfIEnumerable; getEnumeratorMethod = GetIEnumerableGetEnumeratorMethod(type, ienumerableInterface); } } } private static MethodInfo? GetIEnumerableGetEnumeratorMethod( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type ienumerableInterface) => GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface); private static bool IsKnownInterface(Type type) { Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type; foreach (Type knownInterfaceType in KnownInterfaces) { if (typeToCheck == knownInterfaceType) { return true; } } return false; } internal override DataContract GetValidContract(SerializationMode mode) { if (InvalidCollectionInSharedContractMessage != null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage)); return this; } internal override DataContract GetValidContract() { if (this.IsConstructorCheckRequired) { CheckConstructor(); } return this; } private void CheckConstructor() { if (this.Constructor == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType)))); } else { this.IsConstructorCheckRequired = false; } } internal override bool IsValidContract(SerializationMode mode) { return (InvalidCollectionInSharedContractMessage == null); } /// <SecurityNote> /// Review - calculates whether this collection requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForRead(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(Constructor)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.AddMethod)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractAddMethodNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.AddMethod!.Name), securityException)); } return true; } return false; } /// <SecurityNote> /// Review - calculates whether this collection requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForWrite(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } return false; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { Debug.Assert(context != null); // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatWriterDelegate(xmlWriter, obj, context, this); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { Debug.Assert(context != null); xmlReader.Read(); object? o = null; if (context.IsGetOnlyCollection) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } else { o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } xmlReader.ReadEndElement(); return o; } internal sealed class DictionaryEnumerator : IEnumerator<KeyValue<object, object?>> { private readonly IDictionaryEnumerator _enumerator; public DictionaryEnumerator(IDictionaryEnumerator enumerator) { _enumerator = enumerator; } public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { return _enumerator.MoveNext(); } public KeyValue<object, object?> Current { get { return new KeyValue<object, object?>(_enumerator.Key, _enumerator.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { _enumerator.Reset(); } } internal sealed class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>> { private readonly IEnumerator<KeyValuePair<K, V>> _enumerator; public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator) { _enumerator = enumerator; } public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { return _enumerator.MoveNext(); } public KeyValue<K, V> Current { get { KeyValuePair<K, V> current = _enumerator.Current; return new KeyValue<K, V>(current.Key, current.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { _enumerator.Reset(); } } } }
// 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; namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Xml; using System.Linq; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Security; using System.Diagnostics.CodeAnalysis; // The interface is a perf optimization. // Only KeyValuePairAdapter should implement the interface. internal interface IKeyValuePairAdapter { } //Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved [DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")] internal sealed class KeyValuePairAdapter<K, T> : IKeyValuePairAdapter { private K _kvpKey; private T _kvpValue; public KeyValuePairAdapter(KeyValuePair<K, T> kvPair) { _kvpKey = kvPair.Key; _kvpValue = kvPair.Value; } [DataMember(Name = "key")] public K Key { get { return _kvpKey; } set { _kvpKey = value; } } [DataMember(Name = "value")] public T Value { get { return _kvpValue; } set { _kvpValue = value; } } internal KeyValuePair<K, T> GetKeyValuePair() { return new KeyValuePair<K, T>(_kvpKey, _kvpValue); } internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair) { return new KeyValuePairAdapter<K, T>(kvPair); } } internal interface IKeyValue { object? Key { get; set; } object? Value { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")] internal struct KeyValue<K, V> : IKeyValue { private K _key; private V _value; internal KeyValue(K key, V value) { _key = key; _value = value; } [DataMember(IsRequired = true)] public K Key { get { return _key; } set { _key = value; } } [DataMember(IsRequired = true)] public V Value { get { return _value; } set { _value = value; } } object? IKeyValue.Key { get { return _key; } set { _key = (K)value!; } } object? IKeyValue.Value { get { return _value; } set { _value = (V)value!; } } } internal enum CollectionKind : byte { None, GenericDictionary, Dictionary, GenericList, GenericCollection, List, GenericEnumerable, Collection, Enumerable, Array, } internal sealed class CollectionDataContract : DataContract { private XmlDictionaryString _collectionItemName; private XmlDictionaryString? _childElementNamespace; private DataContract? _itemContract; private CollectionDataContractCriticalHelper _helper; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type)) { InitCollectionDataContract(this); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor, bool isConstructorCheckRequired) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } [MemberNotNull(nameof(_helper))] [MemberNotNull(nameof(_collectionItemName))] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void InitCollectionDataContract(DataContract? sharedTypeContract) { _helper = (base.Helper as CollectionDataContractCriticalHelper)!; _collectionItemName = _helper.CollectionItemName; if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary) { _itemContract = _helper.ItemContract; } _helper.SharedTypeContract = sharedTypeContract; } private static Type[] KnownInterfaces { get { return CollectionDataContractCriticalHelper.KnownInterfaces; } } internal CollectionKind Kind { get { return _helper.Kind; } } public Type ItemType { get { return _helper.ItemType; } set { _helper.ItemType = value; } } public DataContract ItemContract { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { return _itemContract ?? _helper.ItemContract; } set { _itemContract = value; _helper.ItemContract = value; } } internal DataContract? SharedTypeContract { get { return _helper.SharedTypeContract; } } public string ItemName { get { return _helper.ItemName; } set { _helper.ItemName = value; } } public XmlDictionaryString CollectionItemName { get { return _collectionItemName; } set { _collectionItemName = value; } } public string? KeyName { get { return _helper.KeyName; } set { _helper.KeyName = value; } } public string? ValueName { get { return _helper.ValueName; } set { _helper.ValueName = value; } } internal bool IsDictionary { get { return KeyName != null; } } public XmlDictionaryString? ChildElementNamespace { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_childElementNamespace == null) { lock (this) { if (_childElementNamespace == null) { if (_helper.ChildElementNamespace == null && !IsDictionary) { XmlDictionaryString? tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); Interlocked.MemoryBarrier(); _helper.ChildElementNamespace = tempChildElementNamespace; } _childElementNamespace = _helper.ChildElementNamespace; } } } return _childElementNamespace; } } internal bool IsItemTypeNullable { get { return _helper.IsItemTypeNullable; } set { _helper.IsItemTypeNullable = value; } } internal bool IsConstructorCheckRequired { get { return _helper.IsConstructorCheckRequired; } set { _helper.IsConstructorCheckRequired = value; } } internal MethodInfo? GetEnumeratorMethod { get { return _helper.GetEnumeratorMethod; } } internal MethodInfo? AddMethod { get { return _helper.AddMethod; } } internal ConstructorInfo? Constructor { get { return _helper.Constructor; } } public override DataContractDictionary? KnownDataContracts { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { return _helper.KnownDataContracts; } set { _helper.KnownDataContracts = value; } } internal string? InvalidCollectionInSharedContractMessage { get { return _helper.InvalidCollectionInSharedContractMessage; } } internal string? DeserializationExceptionMessage { get { return _helper.DeserializationExceptionMessage; } } internal bool IsReadOnlyContract { get { return DeserializationExceptionMessage != null; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private XmlFormatCollectionWriterDelegate CreateXmlFormatWriterDelegate() { return new XmlFormatWriterGenerator().GenerateCollectionWriter(this); } internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_helper.XmlFormatWriterDelegate == null) { lock (this) { if (_helper.XmlFormatWriterDelegate == null) { XmlFormatCollectionWriterDelegate tempDelegate = CreateXmlFormatWriterDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatWriterDelegate = tempDelegate; } } } return _helper.XmlFormatWriterDelegate; } set { } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private XmlFormatCollectionReaderDelegate CreateXmlFormatReaderDelegate() { return new XmlFormatReaderGenerator().GenerateCollectionReader(this); } internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_helper.XmlFormatReaderDelegate == null) { lock (this) { if (_helper.XmlFormatReaderDelegate == null) { if (IsReadOnlyContract) { ThrowInvalidDataContractException(_helper.DeserializationExceptionMessage, type: null); } XmlFormatCollectionReaderDelegate tempDelegate = CreateXmlFormatReaderDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatReaderDelegate = tempDelegate; } } } return _helper.XmlFormatReaderDelegate; } set { } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private XmlFormatGetOnlyCollectionReaderDelegate CreateXmlFormatGetOnlyCollectionReaderDelegate() { return new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this); } internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { lock (this) { if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { if (UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType)))); } if (IsReadOnlyContract) { ThrowInvalidDataContractException(_helper.DeserializationExceptionMessage, type: null); } if (Kind != CollectionKind.Array && AddMethod == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType)))); } XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = CreateXmlFormatGetOnlyCollectionReaderDelegate(); Interlocked.MemoryBarrier(); _helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate; } } } return _helper.XmlFormatGetOnlyCollectionReaderDelegate; } set { } } internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { _helper.IncrementCollectionCount(xmlWriter, obj, context); } internal IEnumerator GetEnumeratorForCollection(object obj) { return _helper.GetEnumeratorForCollection(obj); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal Type GetCollectionElementType() { return _helper.GetCollectionElementType(); } private sealed class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private static Type[]? s_knownInterfaces; private Type _itemType = null!; // _itemType is always set except for the "invalid" CollectionDataContract private bool _isItemTypeNullable; private CollectionKind _kind; private readonly MethodInfo? _getEnumeratorMethod; private readonly MethodInfo? _addMethod; private readonly ConstructorInfo? _constructor; private readonly string? _deserializationExceptionMessage; private DataContract? _itemContract; private DataContract? _sharedTypeContract; private DataContractDictionary? _knownDataContracts; private bool _isKnownTypeAttributeChecked; private string _itemName = null!; // _itemName is always set except for the "invalid" CollectionDataContract private bool _itemNameSetExplicit; private XmlDictionaryString _collectionItemName = null!; // _itemName is always set except for the "invalid" CollectionDataContract private string? _keyName; private string? _valueName; private XmlDictionaryString? _childElementNamespace; private readonly string? _invalidCollectionInSharedContractMessage; private XmlFormatCollectionReaderDelegate? _xmlFormatReaderDelegate; private XmlFormatGetOnlyCollectionReaderDelegate? _xmlFormatGetOnlyCollectionReaderDelegate; private XmlFormatCollectionWriterDelegate? _xmlFormatWriterDelegate; private bool _isConstructorCheckRequired; internal static Type[] KnownInterfaces { get { if (s_knownInterfaces == null) { // Listed in priority order s_knownInterfaces = new Type[] { Globals.TypeOfIDictionaryGeneric, Globals.TypeOfIDictionary, Globals.TypeOfIListGeneric, Globals.TypeOfICollectionGeneric, Globals.TypeOfIList, Globals.TypeOfIEnumerableGeneric, Globals.TypeOfICollection, Globals.TypeOfIEnumerable }; } return s_knownInterfaces; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAttribute? collectionContractAttribute) { _kind = kind; if (itemType != null) { _itemType = itemType; _isItemTypeNullable = DataContract.IsTypeNullable(itemType); bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary); string? itemName = null, keyName = null, valueName = null; if (collectionContractAttribute != null) { if (collectionContractAttribute.IsItemNameSetExplicitly) { if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType)))); itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName); _itemNameSetExplicit = true; } if (collectionContractAttribute.IsKeyNameSetExplicitly) { if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName))); keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName); } if (collectionContractAttribute.IsValueNameSetExplicitly) { if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName))); valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName); } } XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3); this.Name = dictionary.Add(this.StableName.Name); this.Namespace = dictionary.Add(this.StableName.Namespace); _itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name; _collectionItemName = dictionary.Add(_itemName); if (isDictionary) { _keyName = keyName ?? Globals.KeyLocalName; _valueName = valueName ?? Globals.ValueLocalName; } } if (collectionContractAttribute != null) { this.IsReference = collectionContractAttribute.IsReference; } } // array [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type) : base(type) { if (type == Globals.TypeOfArray) type = Globals.TypeOfObjectArray; if (type.GetArrayRank() > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SupportForMultidimensionalArraysNotPresent)); this.StableName = DataContract.GetStableName(type); Init(CollectionKind.Array, type.GetElementType(), null); } // read-only collection [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage) : base(type) { if (getEnumeratorMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, GetClrTypeFullName(type)))); if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, GetClrTypeFullName(type)))); CollectionDataContractAttribute? collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); _getEnumeratorMethod = getEnumeratorMethod; _deserializationExceptionMessage = deserializationExceptionMessage; } // collection [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor) : base(type) { if (getEnumeratorMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type)))); if (addMethod == null && !type.IsInterface) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type)))); if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type)))); CollectionDataContractAttribute? collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); _getEnumeratorMethod = getEnumeratorMethod; _addMethod = addMethod; _constructor = constructor; } // collection [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor, bool isConstructorCheckRequired) : this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor) { _isConstructorCheckRequired = isConstructorCheckRequired; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal CollectionDataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] Type type, string invalidCollectionInSharedContractMessage) : base(type) { Init(CollectionKind.Collection, null /*itemType*/, null); _invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage; } internal CollectionKind Kind { get { return _kind; } } internal Type ItemType { get { return _itemType; } set { _itemType = value; } } internal DataContract ItemContract { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (_itemContract == null) { if (IsDictionary) { if (string.CompareOrdinal(KeyName, ValueName) == 0) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName), UnderlyingType); } Debug.Assert(KeyName != null); Debug.Assert(ValueName != null); _itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName }); // Ensure that DataContract gets added to the static DataContract cache for dictionary items DataContract.GetDataContract(ItemType); } else { _itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType); if (_itemContract == null) { _itemContract = DataContract.GetDataContract(ItemType); } } } return _itemContract; } set { _itemContract = value; } } internal DataContract? SharedTypeContract { get { return _sharedTypeContract; } set { _sharedTypeContract = value; } } internal string ItemName { get { return _itemName; } set { _itemName = value; } } internal bool IsConstructorCheckRequired { get { return _isConstructorCheckRequired; } set { _isConstructorCheckRequired = value; } } public XmlDictionaryString CollectionItemName { get { return _collectionItemName; } } internal string? KeyName { get { return _keyName; } set { _keyName = value; } } internal string? ValueName { get { return _valueName; } set { _valueName = value; } } internal bool IsDictionary => KeyName != null; public string? DeserializationExceptionMessage => _deserializationExceptionMessage; public XmlDictionaryString? ChildElementNamespace { get { return _childElementNamespace; } set { _childElementNamespace = value; } } internal bool IsItemTypeNullable { get { return _isItemTypeNullable; } set { _isItemTypeNullable = value; } } internal MethodInfo? GetEnumeratorMethod => _getEnumeratorMethod; internal MethodInfo? AddMethod => _addMethod; internal ConstructorInfo? Constructor => _constructor; internal override DataContractDictionary? KnownDataContracts { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get { if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } set { _knownDataContracts = value; } } internal string? InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage; internal bool ItemNameSetExplicit => _itemNameSetExplicit; internal XmlFormatCollectionWriterDelegate? XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } internal XmlFormatCollectionReaderDelegate? XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } internal XmlFormatGetOnlyCollectionReaderDelegate? XmlFormatGetOnlyCollectionReaderDelegate { get { return _xmlFormatGetOnlyCollectionReaderDelegate; } set { _xmlFormatGetOnlyCollectionReaderDelegate = value; } } private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context); private IncrementCollectionCountDelegate? _incrementCollectionCountDelegate; private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { } internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (_incrementCollectionCountDelegate == null) { switch (Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: { _incrementCollectionCountDelegate = (x, o, c) => { c.IncrementCollectionCount(x, (ICollection)o); }; } break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: { var buildIncrementCollectionCountDelegate = GetBuildIncrementCollectionCountGenericDelegate(ItemType); _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>())!; } break; case CollectionKind.GenericDictionary: { var buildIncrementCollectionCountDelegate = GetBuildIncrementCollectionCountGenericDelegate(typeof(KeyValuePair<,>).MakeGenericType(ItemType.GetGenericArguments())); _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>())!; } break; default: // Do nothing. _incrementCollectionCountDelegate = DummyIncrementCollectionCount; break; } } _incrementCollectionCountDelegate(xmlWriter, obj, context); [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "The call to MakeGenericMethod is safe due to the fact that CollectionDataContractCriticalHelper.BuildIncrementCollectionCountDelegate<T> is not annotated.")] static MethodInfo GetBuildIncrementCollectionCountGenericDelegate(Type type) => BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(type); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "The call to MakeGenericMethod is safe due to the fact that CollectionDataContractCriticalHelper.BuildIncrementCollectionCountDelegate<T> is not annotated.")] private MethodInfo GetBuildIncrementCollectionCountGenericDelegate(Type type) => BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(type); private static MethodInfo? s_buildIncrementCollectionCountDelegateMethod; private static MethodInfo BuildIncrementCollectionCountDelegateMethod { get { if (s_buildIncrementCollectionCountDelegateMethod == null) { s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!; } return s_buildIncrementCollectionCountDelegateMethod; } } private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>() { return (xmlwriter, obj, context) => { context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj); }; } private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator); private CreateGenericDictionaryEnumeratorDelegate? _createGenericDictionaryEnumeratorDelegate; internal IEnumerator GetEnumeratorForCollection(object obj) { IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator(); if (Kind == CollectionKind.GenericDictionary) { if (_createGenericDictionaryEnumeratorDelegate == null) { var keyValueTypes = ItemType.GetGenericArguments(); MethodInfo buildCreateGenericDictionaryEnumerator = GetBuildCreateGenericDictionaryEnumeratorGenericMethod(keyValueTypes); _createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>())!; } enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator); } else if (Kind == CollectionKind.Dictionary) { enumerator = new DictionaryEnumerator(((IDictionary)obj).GetEnumerator()); } return enumerator; [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "The call to MakeGenericMethod is safe due to the fact that CollectionDataContractCriticalHelper.BuildCreateGenericDictionaryEnumerator<K,V> is not annotated.")] static MethodInfo GetBuildCreateGenericDictionaryEnumeratorGenericMethod(Type[] keyValueTypes) => GetBuildCreateGenericDictionaryEnumeratorMethodInfo.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] 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; if (Kind == CollectionKind.GenericDictionary) { Type[] keyValueTypes = ItemType.GetGenericArguments(); enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes); } else if (Kind == CollectionKind.Dictionary) { enumeratorType = Globals.TypeOfDictionaryEnumerator; } else { enumeratorType = GetEnumeratorMethod.ReturnType; } MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Type.EmptyTypes); if (getCurrentMethod == null) { if (enumeratorType.IsInterface) { getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; } else { Type ienumeratorInterface = Globals.TypeOfIEnumerator; if (Kind == CollectionKind.GenericDictionary || Kind == CollectionKind.GenericCollection || Kind == CollectionKind.GenericEnumerable) { Type[] interfaceTypes = enumeratorType.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && interfaceType.GetGenericArguments()[0] == ItemType) { ienumeratorInterface = interfaceType; break; } } } getCurrentMethod = GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } Type elementType = getCurrentMethod.ReturnType; return elementType; } private static MethodInfo? s_buildCreateGenericDictionaryEnumerator; private static MethodInfo GetBuildCreateGenericDictionaryEnumeratorMethodInfo { get { if (s_buildCreateGenericDictionaryEnumerator == null) { s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!; } return s_buildCreateGenericDictionaryEnumerator; } } private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>() { return (enumerator) => { return new GenericDictionaryEnumerator<K, V>((IEnumerator<KeyValuePair<K, V>>)enumerator); }; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private DataContract? GetSharedTypeContract(Type type) { if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) { return this; } if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return new ClassDataContract(type); } return null; } internal static bool IsCollectionInterface(Type type) { if (type.IsGenericType) type = type.GetGenericTypeDefinition(); return ((IList<Type>)KnownInterfaces).Contains(type); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsCollection(Type type) { return IsCollection(type, out _); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsCollection(Type type, [NotNullWhen(true)] out Type? itemType) { return IsCollectionHelper(type, out itemType, true /*constructorRequired*/); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool IsCollection(Type type, bool constructorRequired) { return IsCollectionHelper(type, out _, constructorRequired); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool IsCollectionHelper(Type type, [NotNullWhen(true)] out Type? itemType, bool constructorRequired) { if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null) { itemType = type.GetElementType()!; return true; } return IsCollectionOrTryCreate(type, tryCreate: false, out _, out itemType, constructorRequired); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool TryCreate(Type type, [NotNullWhen(true)] out DataContract? dataContract) { return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: true); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool CreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: false); } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static bool TryCreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract == null) { if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, tryCreate: true, out dataContract!, out _, constructorRequired: false); } } else { if (dataContract is CollectionDataContract) { return true; } else { dataContract = null; return false; } } } // Once https://github.com/mono/linker/issues/1731 is fixed we can remove the suppression from here as it won't be needed any longer. [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:GetMethod", Justification = "The DynamicallyAccessedMembers declarations will ensure the interface methods will be preserved.")] internal static MethodInfo? GetTargetMethodWithName(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type interfaceType) { Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); return t?.GetMethod(name); } private static bool IsArraySegment(Type t) { return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract? dataContract, out Type itemType, bool constructorRequired) { dataContract = null; itemType = Globals.TypeOfObject; if (DataContract.GetBuiltInDataContract(type) != null) { return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/, SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract); } MethodInfo? addMethod, getEnumeratorMethod; bool hasCollectionDataContract = IsCollectionDataContract(type); bool isReadOnlyContract = false; string? deserializationExceptionMessage = null; Type? baseType = type.BaseType; bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false; // Avoid creating an invalid collection contract for Serializable types since we can create a ClassDataContract instead bool createContractWithException = isBaseTypeCollection && !type.IsSerializable; if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeCannotHaveDataContract, null, ref dataContract); } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type)) { return false; } if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } if (type.IsInterface) { Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { addMethod = null; if (type.IsGenericType) { Type[] genericArgs = type.GetGenericArguments(); if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric) { itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs); addMethod = type.GetMethod(Globals.AddMethodName); getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName)!; } else { itemType = genericArgs[0]; if (interfaceTypeToCheck == Globals.TypeOfICollectionGeneric || interfaceTypeToCheck == Globals.TypeOfIListGeneric) { addMethod = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType).GetMethod(Globals.AddMethodName); } getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName)!; } } else { if (interfaceTypeToCheck == Globals.TypeOfIDictionary) { itemType = typeof(KeyValue<object, object>); addMethod = type.GetMethod(Globals.AddMethodName); } else { itemType = Globals.TypeOfObject; // IList has AddMethod if (interfaceTypeToCheck == Globals.TypeOfIList) { addMethod = type.GetMethod(Globals.AddMethodName); } } getEnumeratorMethod = typeof(IEnumerable).GetMethod(Globals.GetEnumeratorMethodName)!; } if (tryCreate) dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/); return true; } } } ConstructorInfo? defaultCtor = null; if (!type.IsValueType) { defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.EmptyTypes); if (defaultCtor == null && constructorRequired) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. // Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons. // DataContract types and POCO types cannot be collection types, so they don't need to be factored in if (type.IsSerializable) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract); } else { isReadOnlyContract = true; GetReadOnlyCollectionExceptionMessages(type, SR.CollectionTypeDoesNotHaveDefaultCtor, null, out deserializationExceptionMessage); } } } Type? knownInterfaceType = null; CollectionKind kind = CollectionKind.None; bool multipleDefinitions = false; Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { CollectionKind currentKind = (CollectionKind)(i + 1); if (kind == CollectionKind.None || currentKind < kind) { kind = currentKind; knownInterfaceType = interfaceType; multipleDefinitions = false; } else if ((kind & currentKind) == currentKind) multipleDefinitions = true; break; } } } if (kind == CollectionKind.None) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } Debug.Assert(knownInterfaceType != null); if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable) { if (multipleDefinitions) knownInterfaceType = Globals.TypeOfIEnumerable; itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject; GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType }, false /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); Debug.Assert(getEnumeratorMethod != null); if (addMethod == null) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. // Collection types marked [Serializable] cannot be read-only collections for backward compatibility reasons. // DataContract types and POCO types cannot be collection types, so they don't need to be factored in. if (type.IsSerializable) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract); } else { isReadOnlyContract = true; GetReadOnlyCollectionExceptionMessages(type, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), out deserializationExceptionMessage); } } if (tryCreate) { dataContract = isReadOnlyContract ? new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) : new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } } else { if (multipleDefinitions) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract); } Type[]? addMethodTypeArray = null; switch (kind) { case CollectionKind.GenericDictionary: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition || (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter); itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.Dictionary: addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); itemType = addMethodTypeArray[0]; break; case CollectionKind.List: itemType = Globals.TypeOfObject; addMethodTypeArray = new Type[] { itemType }; break; } if (tryCreate) { Debug.Assert(addMethodTypeArray != null); GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray, true /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); Debug.Assert(getEnumeratorMethod != null); dataContract = isReadOnlyContract ? new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) : new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } } return true; } internal static bool IsCollectionDataContract(Type type) { return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string? param, ref DataContract? dataContract) { if (hasCollectionDataContract) { if (tryCreate) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param))); return true; } if (createContractWithException) { if (tryCreate) dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param)); return true; } return false; } private static void GetReadOnlyCollectionExceptionMessages(Type type, string message, string? param, out string deserializationExceptionMessage) { deserializationExceptionMessage = GetInvalidCollectionMessage(message, SR.Format(SR.ReadOnlyCollectionDeserialization, GetClrTypeFullName(type)), param); } private static string GetInvalidCollectionMessage(string message, string nestedMessage, string? param) { return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param); } // Once https://github.com/mono/linker/issues/1731 is fixed we can remove the suppression from here as it won't be needed any longer. [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:GetMethod", Justification = "The DynamicallyAccessedMembers declarations will ensure the interface methods will be preserved.")] private static void FindCollectionMethodsOnInterface( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type interfaceType, ref MethodInfo? addMethod, ref MethodInfo? getEnumeratorMethod) { Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); if (t != null) { addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod; getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod; } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private static void GetCollectionMethods( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo? getEnumeratorMethod, out MethodInfo? addMethod) { addMethod = getEnumeratorMethod = null; if (addMethodOnInterface) { addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, addMethodTypeArray); if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0]) { FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { Type[] parentInterfaceTypes = interfaceType.GetInterfaces(); // The for loop below depeneds on the order for the items in parentInterfaceTypes, which // doesnt' seem right. But it's the behavior of DCS on the full framework. // Sorting the array to make sure the behavior is consistent with Desktop's. Array.Sort(parentInterfaceTypes, (x, y) => string.Compare(x.FullName, y.FullName)); foreach (Type parentInterfaceType in parentInterfaceTypes) { if (IsKnownInterface(parentInterfaceType)) { FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { break; } } } } } } else { // GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, addMethodTypeArray); } if (getEnumeratorMethod == null) { getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Type.EmptyTypes); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { Type? ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); if (ienumerableInterface == null) ienumerableInterface = Globals.TypeOfIEnumerable; getEnumeratorMethod = GetIEnumerableGetEnumeratorMethod(type, ienumerableInterface); } } } private static MethodInfo? GetIEnumerableGetEnumeratorMethod( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type ienumerableInterface) => GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface); private static bool IsKnownInterface(Type type) { Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type; foreach (Type knownInterfaceType in KnownInterfaces) { if (typeToCheck == knownInterfaceType) { return true; } } return false; } internal override DataContract GetValidContract(SerializationMode mode) { if (InvalidCollectionInSharedContractMessage != null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage)); return this; } internal override DataContract GetValidContract() { if (this.IsConstructorCheckRequired) { CheckConstructor(); } return this; } private void CheckConstructor() { if (this.Constructor == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType)))); } else { this.IsConstructorCheckRequired = false; } } internal override bool IsValidContract(SerializationMode mode) { return (InvalidCollectionInSharedContractMessage == null); } /// <SecurityNote> /// Review - calculates whether this collection requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForRead(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(Constructor)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.AddMethod)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractAddMethodNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.AddMethod!.Name), securityException)); } return true; } return false; } /// <SecurityNote> /// Review - calculates whether this collection requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForWrite(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } return false; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { Debug.Assert(context != null); // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatWriterDelegate(xmlWriter, obj, context, this); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { Debug.Assert(context != null); xmlReader.Read(); object? o = null; if (context.IsGetOnlyCollection) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } else { o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } xmlReader.ReadEndElement(); return o; } internal sealed class DictionaryEnumerator : IEnumerator<KeyValue<object, object?>> { private readonly IDictionaryEnumerator _enumerator; public DictionaryEnumerator(IDictionaryEnumerator enumerator) { _enumerator = enumerator; } public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { return _enumerator.MoveNext(); } public KeyValue<object, object?> Current { get { return new KeyValue<object, object?>(_enumerator.Key, _enumerator.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { _enumerator.Reset(); } } internal sealed class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>> { private readonly IEnumerator<KeyValuePair<K, V>> _enumerator; public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator) { _enumerator = enumerator; } public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { return _enumerator.MoveNext(); } public KeyValue<K, V> Current { get { KeyValuePair<K, V> current = _enumerator.Current; return new KeyValue<K, V>(current.Key, current.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { _enumerator.Reset(); } } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b56154/b56154.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/ShroudedKeyBagTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Pkcs.Tests.Pkcs12 { public static class ShroudedKeyBagTests { private static readonly PbeParameters s_win7Pbe = new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 2000); private static readonly PbeParameters s_pbkdf2Pbe = new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 2000); private static readonly ReadOnlyMemory<byte> s_derNull = new byte[] { 0x05, 0x00 }; [Fact] public static void BuildWithCharsFactoryReadDirect() { using (RSA rsa = RSA.Create()) { Pkcs12SafeContents contents = new Pkcs12SafeContents(); Pkcs12ShroudedKeyBag keyBag = contents.AddShroudedKey(rsa, nameof(rsa), s_win7Pbe); using (RSA rsa2 = RSA.Create()) { rsa2.ImportEncryptedPkcs8PrivateKey( nameof(rsa), keyBag.EncryptedPkcs8PrivateKey.Span, out _); byte[] sig = new byte[rsa.KeySize / 8]; Assert.True(rsa2.TrySignData( keyBag.EncryptedPkcs8PrivateKey.Span, sig, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1, out int sigLen)); Assert.Equal(sig.Length, sigLen); Assert.True(rsa.VerifyData( keyBag.EncryptedPkcs8PrivateKey.Span, sig, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1)); } } } [Fact] public static void BuildWithBytesFactoryReadDirect() { using (RSA rsa = RSA.Create()) { Pkcs12SafeContents contents = new Pkcs12SafeContents(); byte[] encryptionKey = new byte[] { 1, 2, 3, 4, 5 }; Pkcs12ShroudedKeyBag keyBag = contents.AddShroudedKey(rsa, encryptionKey, s_pbkdf2Pbe); using (RSA rsa2 = RSA.Create()) { rsa2.ImportEncryptedPkcs8PrivateKey( encryptionKey, keyBag.EncryptedPkcs8PrivateKey.Span, out _); byte[] sig = new byte[rsa.KeySize / 8]; Assert.True(rsa2.TrySignData( keyBag.EncryptedPkcs8PrivateKey.Span, sig, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1, out int sigLen)); Assert.Equal(sig.Length, sigLen); Assert.True(rsa.VerifyData( keyBag.EncryptedPkcs8PrivateKey.Span, sig, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1)); } } } [Theory] [InlineData(false)] [InlineData(true)] public static void SkipCopyHonored(bool skipCopy) { Pkcs12ShroudedKeyBag shroudedKeyBag = new Pkcs12ShroudedKeyBag(s_derNull, skipCopy); if (skipCopy) { Assert.True( s_derNull.Span.Overlaps(shroudedKeyBag.EncryptedPkcs8PrivateKey.Span), "Same memory"); } else { Assert.False( s_derNull.Span.Overlaps(shroudedKeyBag.EncryptedPkcs8PrivateKey.Span), "Same memory"); } } [Theory] // No data [InlineData("", false)] // Length exceeds payload [InlineData("0401", false)] // Two values (aka length undershoots payload) [InlineData("0400020100", false)] // No length [InlineData("04", false)] // Legal [InlineData("0400", true)] // A legal tag-length-value, but not a legal BIT STRING value. [InlineData("0300", true)] // SEQUENCE (indefinite length) { // Constructed OCTET STRING (indefinite length) { // OCTET STRING (inefficient encoded length 01): 07 // } // } [InlineData("30802480048200017F00000000", true)] // Previous example, trailing byte [InlineData("30802480048200017F0000000000", false)] public static void CtorEnsuresValidBerValue(string inputHex, bool expectSuccess) { byte[] data = inputHex.HexToByteArray(); Func<Pkcs12ShroudedKeyBag> func = () => new Pkcs12ShroudedKeyBag(data, skipCopy: true); if (!expectSuccess) { Assert.ThrowsAny<CryptographicException>(func); } else { // Assert.NoThrow func(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Pkcs.Tests.Pkcs12 { public static class ShroudedKeyBagTests { private static readonly PbeParameters s_win7Pbe = new PbeParameters( PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 2000); private static readonly PbeParameters s_pbkdf2Pbe = new PbeParameters( PbeEncryptionAlgorithm.Aes256Cbc, HashAlgorithmName.SHA256, 2000); private static readonly ReadOnlyMemory<byte> s_derNull = new byte[] { 0x05, 0x00 }; [Fact] public static void BuildWithCharsFactoryReadDirect() { using (RSA rsa = RSA.Create()) { Pkcs12SafeContents contents = new Pkcs12SafeContents(); Pkcs12ShroudedKeyBag keyBag = contents.AddShroudedKey(rsa, nameof(rsa), s_win7Pbe); using (RSA rsa2 = RSA.Create()) { rsa2.ImportEncryptedPkcs8PrivateKey( nameof(rsa), keyBag.EncryptedPkcs8PrivateKey.Span, out _); byte[] sig = new byte[rsa.KeySize / 8]; Assert.True(rsa2.TrySignData( keyBag.EncryptedPkcs8PrivateKey.Span, sig, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1, out int sigLen)); Assert.Equal(sig.Length, sigLen); Assert.True(rsa.VerifyData( keyBag.EncryptedPkcs8PrivateKey.Span, sig, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1)); } } } [Fact] public static void BuildWithBytesFactoryReadDirect() { using (RSA rsa = RSA.Create()) { Pkcs12SafeContents contents = new Pkcs12SafeContents(); byte[] encryptionKey = new byte[] { 1, 2, 3, 4, 5 }; Pkcs12ShroudedKeyBag keyBag = contents.AddShroudedKey(rsa, encryptionKey, s_pbkdf2Pbe); using (RSA rsa2 = RSA.Create()) { rsa2.ImportEncryptedPkcs8PrivateKey( encryptionKey, keyBag.EncryptedPkcs8PrivateKey.Span, out _); byte[] sig = new byte[rsa.KeySize / 8]; Assert.True(rsa2.TrySignData( keyBag.EncryptedPkcs8PrivateKey.Span, sig, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1, out int sigLen)); Assert.Equal(sig.Length, sigLen); Assert.True(rsa.VerifyData( keyBag.EncryptedPkcs8PrivateKey.Span, sig, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1)); } } } [Theory] [InlineData(false)] [InlineData(true)] public static void SkipCopyHonored(bool skipCopy) { Pkcs12ShroudedKeyBag shroudedKeyBag = new Pkcs12ShroudedKeyBag(s_derNull, skipCopy); if (skipCopy) { Assert.True( s_derNull.Span.Overlaps(shroudedKeyBag.EncryptedPkcs8PrivateKey.Span), "Same memory"); } else { Assert.False( s_derNull.Span.Overlaps(shroudedKeyBag.EncryptedPkcs8PrivateKey.Span), "Same memory"); } } [Theory] // No data [InlineData("", false)] // Length exceeds payload [InlineData("0401", false)] // Two values (aka length undershoots payload) [InlineData("0400020100", false)] // No length [InlineData("04", false)] // Legal [InlineData("0400", true)] // A legal tag-length-value, but not a legal BIT STRING value. [InlineData("0300", true)] // SEQUENCE (indefinite length) { // Constructed OCTET STRING (indefinite length) { // OCTET STRING (inefficient encoded length 01): 07 // } // } [InlineData("30802480048200017F00000000", true)] // Previous example, trailing byte [InlineData("30802480048200017F0000000000", false)] public static void CtorEnsuresValidBerValue(string inputHex, bool expectSuccess) { byte[] data = inputHex.HexToByteArray(); Func<Pkcs12ShroudedKeyBag> func = () => new Pkcs12ShroudedKeyBag(data, skipCopy: true); if (!expectSuccess) { Assert.ThrowsAny<CryptographicException>(func); } else { // Assert.NoThrow func(); } } } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/Common/tests/System/Reflection/MockParameterInfo.cs
// 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; namespace System.Reflection { internal abstract class MockParameterInfo : ParameterInfo { public override ParameterAttributes Attributes => throw Unexpected; public override IEnumerable<CustomAttributeData> CustomAttributes => throw Unexpected; public override object DefaultValue => throw Unexpected; public override bool Equals(object obj) => throw Unexpected; public override object[] GetCustomAttributes(bool inherit) => throw Unexpected; public override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw Unexpected; public override IList<CustomAttributeData> GetCustomAttributesData() => throw Unexpected; public override int GetHashCode() => throw Unexpected; public override Type[] GetOptionalCustomModifiers() => throw Unexpected; public override Type[] GetRequiredCustomModifiers() => throw Unexpected; public override bool HasDefaultValue => throw Unexpected; public override bool IsDefined(Type attributeType, bool inherit) => throw Unexpected; public override MemberInfo Member => throw Unexpected; public override int MetadataToken => throw Unexpected; public override string Name => throw Unexpected; public override Type ParameterType => throw Unexpected; public override int Position => throw Unexpected; public override object RawDefaultValue => throw Unexpected; public override string ToString() => throw Unexpected; protected virtual Exception Unexpected => new Exception("Did not expect to be called."); } }
// 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; namespace System.Reflection { internal abstract class MockParameterInfo : ParameterInfo { public override ParameterAttributes Attributes => throw Unexpected; public override IEnumerable<CustomAttributeData> CustomAttributes => throw Unexpected; public override object DefaultValue => throw Unexpected; public override bool Equals(object obj) => throw Unexpected; public override object[] GetCustomAttributes(bool inherit) => throw Unexpected; public override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw Unexpected; public override IList<CustomAttributeData> GetCustomAttributesData() => throw Unexpected; public override int GetHashCode() => throw Unexpected; public override Type[] GetOptionalCustomModifiers() => throw Unexpected; public override Type[] GetRequiredCustomModifiers() => throw Unexpected; public override bool HasDefaultValue => throw Unexpected; public override bool IsDefined(Type attributeType, bool inherit) => throw Unexpected; public override MemberInfo Member => throw Unexpected; public override int MetadataToken => throw Unexpected; public override string Name => throw Unexpected; public override Type ParameterType => throw Unexpected; public override int Position => throw Unexpected; public override object RawDefaultValue => throw Unexpected; public override string ToString() => throw Unexpected; protected virtual Exception Unexpected => new Exception("Did not expect to be called."); } }
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/Marshal/ReadWrite/Int64Tests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Reflection.Emit; using Xunit; #pragma warning disable CS0618 // Type or member is obsolete namespace System.Runtime.InteropServices.Tests { public class Int64Tests { [Theory] [InlineData(new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, long.MaxValue })] public void WriteInt64_Pointer_Roundtrips(long[] values) { int sizeOfArray = Marshal.SizeOf(values[0]) * values.Length; IntPtr ptr = Marshal.AllocCoTaskMem(sizeOfArray); try { Marshal.WriteInt64(ptr, values[0]); for (int i = 1; i < values.Length; i++) { Marshal.WriteInt64(ptr, i * Marshal.SizeOf(values[0]), values[i]); } long value = Marshal.ReadInt64(ptr); Assert.Equal(values[0], value); for (int i = 1; i < values.Length; i++) { value = Marshal.ReadInt64(ptr, i * Marshal.SizeOf(values[0])); Assert.Equal(values[i], value); } } finally { Marshal.FreeCoTaskMem(ptr); } } [Fact] [SkipOnMono("Marshal.WriteInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_BlittableObject_Roundtrips() { int offset1 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value1)).ToInt32(); int offset2 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value2)).ToInt32(); object structure = new BlittableStruct { value1 = 10, value2 = 20 }; Marshal.WriteInt64(structure, offset1, 11); Marshal.WriteInt64(structure, offset2, 21); Assert.Equal(11, ((BlittableStruct)structure).value1); Assert.Equal(21, ((BlittableStruct)structure).value2); Assert.Equal(11, Marshal.ReadInt64(structure, offset1)); Assert.Equal(21, Marshal.ReadInt64(structure, offset2)); } [Fact] [SkipOnMono("Marshal.WriteInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_StructWithReferenceTypes_ReturnsExpected() { int pointerOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.pointerValue)).ToInt32(); int stringOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.stringValue)).ToInt32(); int arrayOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.byValueArray)).ToInt32(); object structure = new StructWithReferenceTypes { pointerValue = (IntPtr)100, stringValue = "ABC", byValueArray = new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }; if (IntPtr.Size == 8) { Marshal.WriteInt64(structure, pointerOffset, 200); } Marshal.WriteInt64(structure, arrayOffset + sizeof(long) * 9, 100); if (IntPtr.Size == 8) { Assert.Equal((IntPtr)200, ((StructWithReferenceTypes)structure).pointerValue); } Assert.Equal("ABC", ((StructWithReferenceTypes)structure).stringValue); Assert.Equal(new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 100 }, ((StructWithReferenceTypes)structure).byValueArray); if (IntPtr.Size == 8) { Assert.Equal(200, Marshal.ReadInt64(structure, pointerOffset)); } Assert.NotEqual(0, Marshal.ReadInt64(structure, stringOffset)); Assert.Equal(100, Marshal.ReadInt64(structure, arrayOffset + sizeof(long) * 9)); } [Fact] [SkipOnMono("Marshal.ReadInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_BlittableObject_ReturnsExpected() { int offset1 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value1)).ToInt32(); int offset2 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value2)).ToInt32(); object structure = new BlittableStruct { value1 = 10, value2 = 20 }; Assert.Equal(10, Marshal.ReadInt64(structure, offset1)); Assert.Equal(20, Marshal.ReadInt64(structure, offset2)); } [Fact] [SkipOnMono("Marshal.ReadInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_StructWithReferenceTypes_ReturnsExpected() { int pointerOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.pointerValue)).ToInt32(); int stringOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.stringValue)).ToInt32(); int arrayOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.byValueArray)).ToInt32(); object structure = new StructWithReferenceTypes { pointerValue = (IntPtr)100, stringValue = "ABC", byValueArray = new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }; if (IntPtr.Size == 8) { Assert.Equal(100, Marshal.ReadInt64(structure, pointerOffset)); } Assert.NotEqual(0, Marshal.ReadInt64(structure, stringOffset)); Assert.Equal(3, Marshal.ReadInt64(structure, arrayOffset + sizeof(long) * 2)); } [Fact] [SkipOnMono("Marshal.ReadByte will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_ZeroPointer_ThrowsException() { AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.ReadInt64(IntPtr.Zero)); AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.ReadInt64(IntPtr.Zero, 2)); } [Fact] [SkipOnMono("Marshal.ReadInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_NullObject_ThrowsAccessViolationException() { Assert.Throws<AccessViolationException>(() => Marshal.ReadInt64(null, 2)); } [Fact] [SkipOnMono("Marshal.ReadInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_NotReadable_ThrowsArgumentException() { AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); Type collectibleType = typeBuilder.CreateType(); object collectibleObject = Activator.CreateInstance(collectibleType); AssertExtensions.Throws<ArgumentException>(null, () => Marshal.ReadInt64(collectibleObject, 0)); } [Fact] [SkipOnMono("Marshal.ReadByte will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_ZeroPointer_ThrowsException() { AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.WriteInt64(IntPtr.Zero, 0)); AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.WriteInt64(IntPtr.Zero, 2, 0)); } [Fact] [SkipOnMono("Marshal.WriteInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_NullObject_ThrowsAccessViolationException() { Assert.Throws<AccessViolationException>(() => Marshal.WriteInt64(null, 2, 0)); } [Fact] [SkipOnMono("Marshal.WriteInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_NotReadable_ThrowsArgumentException() { AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); Type collectibleType = typeBuilder.CreateType(); object collectibleObject = Activator.CreateInstance(collectibleType); AssertExtensions.Throws<ArgumentException>(null, () => Marshal.WriteInt64(collectibleObject, 0, 0)); } public struct BlittableStruct { public long value1; public int padding; public long value2; } public struct StructWithReferenceTypes { public IntPtr pointerValue; public string stringValue; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public long[] byValueArray; } } } #pragma warning restore CS0618 // Type or member is obsolete
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Reflection.Emit; using Xunit; #pragma warning disable CS0618 // Type or member is obsolete namespace System.Runtime.InteropServices.Tests { public class Int64Tests { [Theory] [InlineData(new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, long.MaxValue })] public void WriteInt64_Pointer_Roundtrips(long[] values) { int sizeOfArray = Marshal.SizeOf(values[0]) * values.Length; IntPtr ptr = Marshal.AllocCoTaskMem(sizeOfArray); try { Marshal.WriteInt64(ptr, values[0]); for (int i = 1; i < values.Length; i++) { Marshal.WriteInt64(ptr, i * Marshal.SizeOf(values[0]), values[i]); } long value = Marshal.ReadInt64(ptr); Assert.Equal(values[0], value); for (int i = 1; i < values.Length; i++) { value = Marshal.ReadInt64(ptr, i * Marshal.SizeOf(values[0])); Assert.Equal(values[i], value); } } finally { Marshal.FreeCoTaskMem(ptr); } } [Fact] [SkipOnMono("Marshal.WriteInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_BlittableObject_Roundtrips() { int offset1 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value1)).ToInt32(); int offset2 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value2)).ToInt32(); object structure = new BlittableStruct { value1 = 10, value2 = 20 }; Marshal.WriteInt64(structure, offset1, 11); Marshal.WriteInt64(structure, offset2, 21); Assert.Equal(11, ((BlittableStruct)structure).value1); Assert.Equal(21, ((BlittableStruct)structure).value2); Assert.Equal(11, Marshal.ReadInt64(structure, offset1)); Assert.Equal(21, Marshal.ReadInt64(structure, offset2)); } [Fact] [SkipOnMono("Marshal.WriteInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_StructWithReferenceTypes_ReturnsExpected() { int pointerOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.pointerValue)).ToInt32(); int stringOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.stringValue)).ToInt32(); int arrayOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.byValueArray)).ToInt32(); object structure = new StructWithReferenceTypes { pointerValue = (IntPtr)100, stringValue = "ABC", byValueArray = new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }; if (IntPtr.Size == 8) { Marshal.WriteInt64(structure, pointerOffset, 200); } Marshal.WriteInt64(structure, arrayOffset + sizeof(long) * 9, 100); if (IntPtr.Size == 8) { Assert.Equal((IntPtr)200, ((StructWithReferenceTypes)structure).pointerValue); } Assert.Equal("ABC", ((StructWithReferenceTypes)structure).stringValue); Assert.Equal(new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 100 }, ((StructWithReferenceTypes)structure).byValueArray); if (IntPtr.Size == 8) { Assert.Equal(200, Marshal.ReadInt64(structure, pointerOffset)); } Assert.NotEqual(0, Marshal.ReadInt64(structure, stringOffset)); Assert.Equal(100, Marshal.ReadInt64(structure, arrayOffset + sizeof(long) * 9)); } [Fact] [SkipOnMono("Marshal.ReadInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_BlittableObject_ReturnsExpected() { int offset1 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value1)).ToInt32(); int offset2 = Marshal.OffsetOf<BlittableStruct>(nameof(BlittableStruct.value2)).ToInt32(); object structure = new BlittableStruct { value1 = 10, value2 = 20 }; Assert.Equal(10, Marshal.ReadInt64(structure, offset1)); Assert.Equal(20, Marshal.ReadInt64(structure, offset2)); } [Fact] [SkipOnMono("Marshal.ReadInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_StructWithReferenceTypes_ReturnsExpected() { int pointerOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.pointerValue)).ToInt32(); int stringOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.stringValue)).ToInt32(); int arrayOffset = Marshal.OffsetOf<StructWithReferenceTypes>(nameof(StructWithReferenceTypes.byValueArray)).ToInt32(); object structure = new StructWithReferenceTypes { pointerValue = (IntPtr)100, stringValue = "ABC", byValueArray = new long[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }; if (IntPtr.Size == 8) { Assert.Equal(100, Marshal.ReadInt64(structure, pointerOffset)); } Assert.NotEqual(0, Marshal.ReadInt64(structure, stringOffset)); Assert.Equal(3, Marshal.ReadInt64(structure, arrayOffset + sizeof(long) * 2)); } [Fact] [SkipOnMono("Marshal.ReadByte will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_ZeroPointer_ThrowsException() { AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.ReadInt64(IntPtr.Zero)); AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.ReadInt64(IntPtr.Zero, 2)); } [Fact] [SkipOnMono("Marshal.ReadInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_NullObject_ThrowsAccessViolationException() { Assert.Throws<AccessViolationException>(() => Marshal.ReadInt64(null, 2)); } [Fact] [SkipOnMono("Marshal.ReadInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void ReadInt64_NotReadable_ThrowsArgumentException() { AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); Type collectibleType = typeBuilder.CreateType(); object collectibleObject = Activator.CreateInstance(collectibleType); AssertExtensions.Throws<ArgumentException>(null, () => Marshal.ReadInt64(collectibleObject, 0)); } [Fact] [SkipOnMono("Marshal.ReadByte will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_ZeroPointer_ThrowsException() { AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.WriteInt64(IntPtr.Zero, 0)); AssertExtensions.ThrowsAny<AccessViolationException, NullReferenceException>(() => Marshal.WriteInt64(IntPtr.Zero, 2, 0)); } [Fact] [SkipOnMono("Marshal.WriteInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_NullObject_ThrowsAccessViolationException() { Assert.Throws<AccessViolationException>(() => Marshal.WriteInt64(null, 2, 0)); } [Fact] [SkipOnMono("Marshal.WriteInt64 will not be implemented in Mono, see https://github.com/mono/mono/issues/15085.")] public void WriteInt64_NotReadable_ThrowsArgumentException() { AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); Type collectibleType = typeBuilder.CreateType(); object collectibleObject = Activator.CreateInstance(collectibleType); AssertExtensions.Throws<ArgumentException>(null, () => Marshal.WriteInt64(collectibleObject, 0, 0)); } public struct BlittableStruct { public long value1; public int padding; public long value2; } public struct StructWithReferenceTypes { public IntPtr pointerValue; public string stringValue; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public long[] byValueArray; } } } #pragma warning restore CS0618 // Type or member is obsolete
-1
dotnet/runtime
66,018
Some more clean up for RegexOptions.NonBacktracking
- Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
stephentoub
2022-03-01T18:59:28Z
2022-03-04T15:52:45Z
47191c04d8aeca28adbb6fd1ce0f878a87655aa4
6dcefe002035fa19c3288d54d8d10f6533cb94fc
Some more clean up for RegexOptions.NonBacktracking. - Deleted some dead code - Avoiding passing things around as IEnumerable when we could pass a stronger type - Cleaned up BitVector and made it a struct - Moved code out of the Algebras folder into the main folder
./src/libraries/System.Diagnostics.Tools/System.Diagnostics.Tools.sln
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "..\..\coreclr\System.Private.CoreLib\System.Private.CoreLib.csproj", "{4E534B56-D245-41B7-B4D0-F8AB7BCC8877}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{6FF6D8F0-403D-40DF-9D75-895E2AF22B88}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.Tools", "ref\System.Diagnostics.Tools.csproj", "{E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.Tools", "src\System.Diagnostics.Tools.csproj", "{566DC861-7C05-45AE-8F59-83D1A175A619}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.Tools.Tests", "tests\System.Diagnostics.Tools.Tests.csproj", "{A63F3AEA-F4ED-4047-A11F-490325530D92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib.Generators", "..\System.Private.CoreLib\gen\System.Private.CoreLib.Generators.csproj", "{103898BF-8D8F-4A35-A943-027A47E4BD36}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{78C30412-0737-4680-AC94-CBD44DBDFCB9}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{15569044-E5D8-40B5-B718-A51ECAA6B259}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0EFD8A36-ACB0-4451-800E-DA867389324D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{F8D19CA8-D65B-4C4B-9851-8E2836CFD72E}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{F5CD84BD-2A56-47BD-A14E-531D0391918A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 Checked|Any CPU = Checked|Any CPU Checked|x64 = Checked|x64 Checked|x86 = Checked|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|Any CPU.ActiveCfg = Debug|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|Any CPU.Build.0 = Debug|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|x64.ActiveCfg = Debug|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|x64.Build.0 = Debug|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|x86.ActiveCfg = Debug|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|x86.Build.0 = Debug|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|Any CPU.ActiveCfg = Release|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|Any CPU.Build.0 = Release|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|x64.ActiveCfg = Release|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|x64.Build.0 = Release|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|x86.ActiveCfg = Release|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|x86.Build.0 = Release|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|Any CPU.ActiveCfg = Checked|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|Any CPU.Build.0 = Checked|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|x64.ActiveCfg = Checked|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|x64.Build.0 = Checked|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|x86.ActiveCfg = Checked|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|x86.Build.0 = Checked|x86 {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|Any CPU.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|x64.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|x64.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|x86.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|x86.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|Any CPU.ActiveCfg = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|Any CPU.Build.0 = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|x64.ActiveCfg = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|x64.Build.0 = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|x86.ActiveCfg = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|x86.Build.0 = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|Any CPU.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|x64.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|x64.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|x86.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|x86.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|Any CPU.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|x64.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|x64.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|x86.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|x86.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|Any CPU.ActiveCfg = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|Any CPU.Build.0 = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|x64.ActiveCfg = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|x64.Build.0 = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|x86.ActiveCfg = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|x86.Build.0 = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|Any CPU.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|x64.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|x64.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|x86.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|x86.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|Any CPU.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|x64.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|x64.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|x86.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|x86.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|Any CPU.ActiveCfg = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|Any CPU.Build.0 = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|x64.ActiveCfg = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|x64.Build.0 = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|x86.ActiveCfg = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|x86.Build.0 = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|Any CPU.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|x64.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|x64.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|x86.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|x86.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|Any CPU.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|x64.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|x64.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|x86.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|x86.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|Any CPU.ActiveCfg = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|Any CPU.Build.0 = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|x64.ActiveCfg = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|x64.Build.0 = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|x86.ActiveCfg = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|x86.Build.0 = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|Any CPU.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|x64.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|x64.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|x86.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|x86.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|Any CPU.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|x64.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|x64.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|x86.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|x86.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|Any CPU.ActiveCfg = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|Any CPU.Build.0 = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|x64.ActiveCfg = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|x64.Build.0 = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|x86.ActiveCfg = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|x86.Build.0 = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|Any CPU.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|x64.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|x64.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|x86.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|x86.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|Any CPU.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|x64.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|x64.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|x86.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|x86.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|Any CPU.ActiveCfg = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|Any CPU.Build.0 = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|x64.ActiveCfg = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|x64.Build.0 = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|x86.ActiveCfg = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|x86.Build.0 = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|Any CPU.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|x64.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|x64.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|x86.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|x86.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|Any CPU.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|x64.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|x64.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|x86.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|x86.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|Any CPU.ActiveCfg = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|Any CPU.Build.0 = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|x64.ActiveCfg = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|x64.Build.0 = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|x86.ActiveCfg = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|x86.Build.0 = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|Any CPU.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|x64.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|x64.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|x86.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|x86.Build.0 = Debug|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {4E534B56-D245-41B7-B4D0-F8AB7BCC8877} = {15569044-E5D8-40B5-B718-A51ECAA6B259} {566DC861-7C05-45AE-8F59-83D1A175A619} = {15569044-E5D8-40B5-B718-A51ECAA6B259} {6FF6D8F0-403D-40DF-9D75-895E2AF22B88} = {0EFD8A36-ACB0-4451-800E-DA867389324D} {A63F3AEA-F4ED-4047-A11F-490325530D92} = {0EFD8A36-ACB0-4451-800E-DA867389324D} {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B} = {F8D19CA8-D65B-4C4B-9851-8E2836CFD72E} {103898BF-8D8F-4A35-A943-027A47E4BD36} = {F5CD84BD-2A56-47BD-A14E-531D0391918A} {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE} = {F5CD84BD-2A56-47BD-A14E-531D0391918A} {78C30412-0737-4680-AC94-CBD44DBDFCB9} = {F5CD84BD-2A56-47BD-A14E-531D0391918A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {74CBBF59-B32F-49B5-9402-F495E129FC3E} EndGlobalSection EndGlobal
Microsoft Visual Studio Solution File, Format Version 12.00 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib", "..\..\coreclr\System.Private.CoreLib\System.Private.CoreLib.csproj", "{4E534B56-D245-41B7-B4D0-F8AB7BCC8877}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestUtilities", "..\Common\tests\TestUtilities\TestUtilities.csproj", "{6FF6D8F0-403D-40DF-9D75-895E2AF22B88}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.Tools", "ref\System.Diagnostics.Tools.csproj", "{E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.Tools", "src\System.Diagnostics.Tools.csproj", "{566DC861-7C05-45AE-8F59-83D1A175A619}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Diagnostics.Tools.Tests", "tests\System.Diagnostics.Tools.Tests.csproj", "{A63F3AEA-F4ED-4047-A11F-490325530D92}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Private.CoreLib.Generators", "..\System.Private.CoreLib\gen\System.Private.CoreLib.Generators.csproj", "{103898BF-8D8F-4A35-A943-027A47E4BD36}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibraryImportGenerator", "..\System.Runtime.InteropServices\gen\LibraryImportGenerator\LibraryImportGenerator.csproj", "{EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Interop.SourceGeneration", "..\System.Runtime.InteropServices\gen\Microsoft.Interop.SourceGeneration\Microsoft.Interop.SourceGeneration.csproj", "{78C30412-0737-4680-AC94-CBD44DBDFCB9}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{15569044-E5D8-40B5-B718-A51ECAA6B259}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0EFD8A36-ACB0-4451-800E-DA867389324D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{F8D19CA8-D65B-4C4B-9851-8E2836CFD72E}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "gen", "gen", "{F5CD84BD-2A56-47BD-A14E-531D0391918A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 Checked|Any CPU = Checked|Any CPU Checked|x64 = Checked|x64 Checked|x86 = Checked|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|Any CPU.ActiveCfg = Debug|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|Any CPU.Build.0 = Debug|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|x64.ActiveCfg = Debug|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|x64.Build.0 = Debug|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|x86.ActiveCfg = Debug|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Debug|x86.Build.0 = Debug|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|Any CPU.ActiveCfg = Release|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|Any CPU.Build.0 = Release|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|x64.ActiveCfg = Release|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|x64.Build.0 = Release|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|x86.ActiveCfg = Release|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Release|x86.Build.0 = Release|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|Any CPU.ActiveCfg = Checked|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|Any CPU.Build.0 = Checked|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|x64.ActiveCfg = Checked|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|x64.Build.0 = Checked|x64 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|x86.ActiveCfg = Checked|x86 {4E534B56-D245-41B7-B4D0-F8AB7BCC8877}.Checked|x86.Build.0 = Checked|x86 {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|Any CPU.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|x64.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|x64.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|x86.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Debug|x86.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|Any CPU.ActiveCfg = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|Any CPU.Build.0 = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|x64.ActiveCfg = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|x64.Build.0 = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|x86.ActiveCfg = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Release|x86.Build.0 = Release|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|Any CPU.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|x64.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|x64.Build.0 = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|x86.ActiveCfg = Debug|Any CPU {6FF6D8F0-403D-40DF-9D75-895E2AF22B88}.Checked|x86.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|Any CPU.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|x64.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|x64.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|x86.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Debug|x86.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|Any CPU.ActiveCfg = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|Any CPU.Build.0 = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|x64.ActiveCfg = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|x64.Build.0 = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|x86.ActiveCfg = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Release|x86.Build.0 = Release|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|Any CPU.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|x64.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|x64.Build.0 = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|x86.ActiveCfg = Debug|Any CPU {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B}.Checked|x86.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|Any CPU.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|x64.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|x64.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|x86.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Debug|x86.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|Any CPU.ActiveCfg = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|Any CPU.Build.0 = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|x64.ActiveCfg = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|x64.Build.0 = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|x86.ActiveCfg = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Release|x86.Build.0 = Release|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|Any CPU.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|x64.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|x64.Build.0 = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|x86.ActiveCfg = Debug|Any CPU {566DC861-7C05-45AE-8F59-83D1A175A619}.Checked|x86.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|Any CPU.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|x64.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|x64.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|x86.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Debug|x86.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|Any CPU.ActiveCfg = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|Any CPU.Build.0 = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|x64.ActiveCfg = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|x64.Build.0 = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|x86.ActiveCfg = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Release|x86.Build.0 = Release|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|Any CPU.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|x64.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|x64.Build.0 = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|x86.ActiveCfg = Debug|Any CPU {A63F3AEA-F4ED-4047-A11F-490325530D92}.Checked|x86.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|Any CPU.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|x64.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|x64.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|x86.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Debug|x86.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|Any CPU.ActiveCfg = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|Any CPU.Build.0 = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|x64.ActiveCfg = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|x64.Build.0 = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|x86.ActiveCfg = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Release|x86.Build.0 = Release|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|Any CPU.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|x64.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|x64.Build.0 = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|x86.ActiveCfg = Debug|Any CPU {103898BF-8D8F-4A35-A943-027A47E4BD36}.Checked|x86.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|Any CPU.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|x64.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|x64.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|x86.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Debug|x86.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|Any CPU.ActiveCfg = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|Any CPU.Build.0 = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|x64.ActiveCfg = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|x64.Build.0 = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|x86.ActiveCfg = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Release|x86.Build.0 = Release|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|Any CPU.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|x64.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|x64.Build.0 = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|x86.ActiveCfg = Debug|Any CPU {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE}.Checked|x86.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|Any CPU.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|x64.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|x64.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|x86.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Debug|x86.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|Any CPU.ActiveCfg = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|Any CPU.Build.0 = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|x64.ActiveCfg = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|x64.Build.0 = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|x86.ActiveCfg = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Release|x86.Build.0 = Release|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|Any CPU.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|Any CPU.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|x64.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|x64.Build.0 = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|x86.ActiveCfg = Debug|Any CPU {78C30412-0737-4680-AC94-CBD44DBDFCB9}.Checked|x86.Build.0 = Debug|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {4E534B56-D245-41B7-B4D0-F8AB7BCC8877} = {15569044-E5D8-40B5-B718-A51ECAA6B259} {566DC861-7C05-45AE-8F59-83D1A175A619} = {15569044-E5D8-40B5-B718-A51ECAA6B259} {6FF6D8F0-403D-40DF-9D75-895E2AF22B88} = {0EFD8A36-ACB0-4451-800E-DA867389324D} {A63F3AEA-F4ED-4047-A11F-490325530D92} = {0EFD8A36-ACB0-4451-800E-DA867389324D} {E5F5CCFF-4DBA-4323-82A6-8D472C488C0B} = {F8D19CA8-D65B-4C4B-9851-8E2836CFD72E} {103898BF-8D8F-4A35-A943-027A47E4BD36} = {F5CD84BD-2A56-47BD-A14E-531D0391918A} {EDA8C760-7617-4CD5-9320-CDE02AB6FDEE} = {F5CD84BD-2A56-47BD-A14E-531D0391918A} {78C30412-0737-4680-AC94-CBD44DBDFCB9} = {F5CD84BD-2A56-47BD-A14E-531D0391918A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {74CBBF59-B32F-49B5-9402-F495E129FC3E} EndGlobalSection EndGlobal
-1